-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.js
More file actions
82 lines (67 loc) · 1.95 KB
/
Copy pathhandler.js
File metadata and controls
82 lines (67 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
const serverless = require('serverless-http');
const bodyParser = require('body-parser');
const express = require('express')
const app = express()
const AWS = require('aws-sdk');
const USERS_TABLE = process.env.USERS_TABLE;
const IS_OFFLINE = process.env.IS_OFFLINE;
let dynamoDb;
if (IS_OFFLINE === 'true') {
dynamoDb = new AWS.DynamoDB.DocumentClient({
region: 'localhost',
endpoint: 'http://localhost:8000'
})
console.log(dynamoDb);
} else {
dynamoDb = new AWS.DynamoDB.DocumentClient();
}
app.use(bodyParser.json({ strict: false }));
app.get('/test', function (req, res) {
res.send('Hello World!')
})
// Get User endpoint
app.get('/users/:userId', function (req, res) {
const params = {
TableName: USERS_TABLE,
Key: {
userId: req.params.userId,
},
}
console.log('test');
dynamoDb.get(params, (error, result) => {
if (error) {
console.log(error);
res.status(400).json({ error: 'Could not get user' });
}
if (result.Item) {
const {userId, name} = result.Item;
res.json({ userId, name });
} else {
res.status(404).json({ error: "User not found" });
}
});
})
// Create User endpoint
app.post('/users', function (req, res) {
const { userId, name } = req.body;
if (typeof userId !== 'string') {
res.status(400).json({ error: '"userId" must be a string' });
} else if (typeof name !== 'string') {
res.status(400).json({ error: '"name" must be a string' });
}
const params = {
TableName: USERS_TABLE,
Item: {
userId: userId,
name: name,
},
};
dynamoDb.put(params, (error) => {
if (error) {
console.log(error);
res.status(400).json({ error: 'Could not create user' });
}
res.json({ userId, name });
});
})
module.exports.handler = serverless(app);