-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Expand file tree
/
Copy pathhandler.js
More file actions
80 lines (70 loc) · 1.95 KB
/
handler.js
File metadata and controls
80 lines (70 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
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 = {
ClientRequestToken: req.context.awsRequestId,
TransactItems: [
{
Update: {
TableName: USERS_TABLE,
Key: { userId: userId },
UpdateExpression: 'set #a = :v',
ExpressionAttributeNames: {'#a' : 'name'},
ExpressionAttributeValues: {
':v': name
}
}
}
]
};
try {
await dynamoDbClient.transactWrite(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,{
request: function(req, _event, context) {
req.context = context;
}
});