-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.ts
78 lines (69 loc) · 2.69 KB
/
index.ts
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
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, GetCommand, PutCommand } from "@aws-sdk/lib-dynamodb";
import { APIGatewayProxyEvent, APIGatewayProxyResult } from "aws-lambda";
import { Endpoint, Method, Router, RouteHandler, Either } from "yatro";
import { renderCounterPage } from "./pages/counterPage";
import { LogUtil } from "./utils/log";
interface IPayload {
event: APIGatewayProxyEvent;
}
const counterEndpoint = Endpoint.build("/");
const counterHandler: RouteHandler<IPayload, APIGatewayProxyResult, typeof counterEndpoint> = async () => {
const client = new DynamoDBClient({});
const dynamo = DynamoDBDocumentClient.from(client);
const result = await dynamo.send(
new GetCommand({
TableName: process.env.TABLE_COUNTER!,
Key: { key: "mycounter" },
})
);
return {
statusCode: 200,
body: renderCounterPage(result.Item?.value || 1),
headers: { "Content-Type": "text/html" },
};
};
const incrementEndpoint = Endpoint.build("/increment/:value|i");
const incrementHandler: RouteHandler<IPayload, APIGatewayProxyResult, typeof incrementEndpoint> = async ({
match: { params },
}) => {
const client = new DynamoDBClient({});
const dynamo = DynamoDBDocumentClient.from(client);
await dynamo.send(
new PutCommand({
TableName: process.env.TABLE_COUNTER!,
Item: { key: "mycounter", value: params.value },
})
);
return { statusCode: 200, body: JSON.stringify({ value: params.value }) };
};
export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
const log = new LogUtil();
const time = Date.now();
log.log("--------> Starting request", event.httpMethod, event.path);
const request: IPayload = { event };
const router = new Router<IPayload, APIGatewayProxyResult>(request)
.get(counterEndpoint, counterHandler)
.post(incrementEndpoint, incrementHandler);
const url = new URL(event.path, "http://example.com");
for (const key of Object.keys(event.queryStringParameters || {})) {
const value = (event.queryStringParameters || {})[key];
url.searchParams.set(key, value || "");
}
let resp: Either<APIGatewayProxyResult>;
try {
resp = await router.route(event.httpMethod as Method, url.pathname + url.search);
} catch (e) {
console.error(e);
log.log("<-------- Responding for", event.httpMethod, event.path, 500, `${Date.now() - time}ms`);
return { statusCode: 500, body: "Internal Server Error" };
}
log.log(
"<-------- Responding for",
event.httpMethod,
event.path,
resp.success ? resp.data.statusCode : 404,
`${Date.now() - time}ms`
);
return resp.success ? resp.data : { statusCode: 404, body: "Not Found" };
};