-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhandler.js
More file actions
52 lines (44 loc) · 1.25 KB
/
handler.js
File metadata and controls
52 lines (44 loc) · 1.25 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
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) {
userId = req.params.userId;
try {
res.status(200).json({ success: 'Hello World' })
} 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);