-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.js
More file actions
74 lines (62 loc) · 1.72 KB
/
handler.js
File metadata and controls
74 lines (62 loc) · 1.72 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
const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
const {
DynamoDBDocumentClient,
GetCommand,
PutCommand,
} = require("@aws-sdk/lib-dynamodb");
const express = require("express");
const serverless = require("serverless-http");
const app = express();
const USERS_TABLE = process.env.USERS_TABLE;
const client = new DynamoDBClient();
const docClient = DynamoDBDocumentClient.from(client);
app.use(express.json());
app.get("/users/:userId", async (req, res) => {
const params = {
TableName: USERS_TABLE,
Key: {
userId: req.params.userId,
},
};
try {
const command = new GetCommand(params);
const { Item } = await docClient.send(command);
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 retrieve user" });
}
});
app.post("/users", async (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, name },
};
try {
const command = new PutCommand(params);
await docClient.send(command);
res.json({ userId, name });
} catch (error) {
console.error(error);
res.status(500).json({ error: "Could not create user" });
}
});
app.use((req, res, next) => {
return res.status(404).json({
error: "Not Found",
});
});
exports.handler = serverless(app);