-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
Copy pathhandler.js
68 lines (57 loc) · 1.54 KB
/
handler.js
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
const AWS = require("aws-sdk");
const express = require("express");
const serverless = require("serverless-http");
const app = express();
const USERS_TABLE = process.env.USERS_TABLE;
const dynamoDbClient = new AWS.DynamoDB.DocumentClient();
app.use(express.json());
app.get("/users/:userId", async function (req, res) {
const params = {
TableName: USERS_TABLE,
Key: {
userId: req.params.userId,
},
};
try {
const { Item } = await dynamoDbClient.get(params).promise();
if (Item) {
const { userId, name } = Item;
res.json({ userId, name });
} else {
res
.status(404)
.json({ error: 'Could not find user with provided "userId"' });
}
} catch (error) {
console.log(error);
res.status(500).json({ error: "Could not retreive user" });
}
});
app.post("/users", async 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,
},
};
try {
await dynamoDbClient.put(params).promise();
res.json({ userId, name });
} catch (error) {
console.log(error);
res.status(500).json({ error: "Could not create user" });
}
});
app.use((req, res, next) => {
return res.status(404).json({
error: "Not Found",
});
});
module.exports.handler = serverless(app);