-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetPost.ts
77 lines (71 loc) · 2.09 KB
/
getPost.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
// write get posts lambda
import { lambda, sdk } from '@pulumi/aws';
import type { lambdaEvent } from '#utils/util';
import { PostsTable, TagsTable } from '#tables/index';
import {
deconstruct,
postEpoch,
currentEndpoint,
CUSTOM_ERROR_CODES,
makeCustomError,
populateResponse,
STATUS_CODES,
} from '#utils/util';
/**
* Get a post
* @description
* - The post is retrieved from the database
* - The lambda is triggered by a GET request to /posts/post/{postID}
*
* @see https://www.pulumi.com/docs/guides/crosswalk/aws/api-gateway/#lambda-request-handling
*/
export const getPost = new lambda.CallbackFunction<
lambdaEvent,
{
body: string;
statusCode: number;
}
>('getPost', {
runtime: lambda.Runtime.NodeJS16dX,
callback: async event => {
const { postID } = event.pathParameters!;
const client = new sdk.DynamoDB.DocumentClient(currentEndpoint);
try {
const { Items } = await client
.query({
TableName: PostsTable.get(),
KeyConditionExpression: 'postID = :postID',
ExpressionAttributeValues: {
':postID': postID,
},
IndexName: 'postID',
})
.promise();
if (!Items?.[0])
return populateResponse(
STATUS_CODES.NOT_FOUND,
makeCustomError('Post not found', CUSTOM_ERROR_CODES.RESOURCE_NOT_FOUND),
);
const post = Items[0];
const { Items: tags } = await client
.query({
TableName: TagsTable.get(),
IndexName: 'postID',
KeyConditionExpression: 'postID = :postID',
ExpressionAttributeValues: {
':postID': postID,
},
})
.promise();
if (tags) post.tags = tags.map(tag => tag.tag);
const { timestamp } = deconstruct(post.postID, postEpoch);
return populateResponse(STATUS_CODES.OK, { ...post, createdAt: timestamp });
} catch (error) {
console.error(error);
return populateResponse(
STATUS_CODES.INTERNAL_SERVER_ERROR,
makeCustomError('Internal Server Error', CUSTOM_ERROR_CODES.POST_ERROR),
);
}
},
});