-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupdatePosts.ts
159 lines (143 loc) · 4.25 KB
/
updatePosts.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import { lambda, sdk } from '@pulumi/aws';
import { getToken } from '../../auth';
import type { CPost, IPost } from '#tables/tables/post';
import type { lambdaEvent } from '#utils/util';
import { PostsTable, TagsTable } from '#tables/index';
import { validatePostBody } from '#tables/validation/posts';
import {
currentEndpoint,
CUSTOM_ERROR_CODES,
makeCustomError,
decodeJWT,
populateResponse,
STATUS_CODES,
updateObject,
} from '#utils/util';
/**
* The update post lambda
* @description
* - The lambda is used to update a post
* - The lambda is triggered by a POST request to /posts/update
*
* @see https://www.pulumi.com/docs/guides/crosswalk/aws/api-gateway/#lambda-request-handling
*/
export const updatePosts = new lambda.CallbackFunction<
lambdaEvent,
{
body: string;
statusCode: number;
}
>('updatePosts', {
runtime: lambda.Runtime.NodeJS16dX,
callback: async event => {
const { error, parsed } = validatePostBody(event, {});
if (!parsed || error) {
return populateResponse(
STATUS_CODES.BAD_REQUEST,
makeCustomError(error ?? 'Bad Request', CUSTOM_ERROR_CODES.BODY_NOT_VALID),
);
}
const { postID } = event.pathParameters!;
const { title, content, tags } = parsed as IPost & Pick<CPost, 'postID'>;
const userID = decodeJWT(getToken(event)).data?.id;
if (!userID) {
return populateResponse(
STATUS_CODES.UNAUTHORIZED,
makeCustomError('Unauthorized', CUSTOM_ERROR_CODES.USER_NOT_AUTHORIZED),
);
}
const updateObj = {
...(title && { title }),
...(content && { content }),
...(title || content || tags ? { updated: Date.now() } : {}),
};
const tagsToStore =
tags?.map((tag: string) => ({
Put: {
TableName: TagsTable.get(),
Item: {
postID,
tag,
},
},
})) ?? null;
if (!Object.keys(updateObj).length) {
return populateResponse(
STATUS_CODES.BAD_REQUEST,
makeCustomError('No fields to update', CUSTOM_ERROR_CODES.POST_ERROR),
);
}
const { ExpressionAttributeNames, ExpressionAttributeValues, UpdateExpression } = updateObject(updateObj);
const client = new sdk.DynamoDB.DocumentClient(currentEndpoint);
try {
// fetch the tag first
if (tagsToStore?.length) {
const { Items } = await client
.query({
TableName: TagsTable.get(),
IndexName: 'postID',
KeyConditionExpression: 'postID = :postID',
ExpressionAttributeValues: {
':postID': postID,
},
})
.promise();
if (!Items?.length)
return populateResponse(
STATUS_CODES.NOT_FOUND,
makeCustomError('Post not found', CUSTOM_ERROR_CODES.POST_ERROR),
);
const oldTag = Items[0].tag;
// delete old tag from tag table
await client
.transactWrite({
TransactItems: [
// delete old tag
{
Delete: {
TableName: TagsTable.get(),
Key: {
postID,
tag: oldTag,
},
},
},
// add new tags
...tagsToStore,
],
})
.promise();
}
await client
.update({
TableName: PostsTable.get(),
Key: {
userID,
postID,
},
ConditionExpression: 'attribute_exists(postID)',
UpdateExpression,
ExpressionAttributeNames,
ExpressionAttributeValues,
})
.promise();
return populateResponse(STATUS_CODES.OK, {
patchedFields: {
...updateObj,
},
});
} catch (error) {
console.error(error);
if ((error as any).code === 'ConditionalCheckFailedException') {
return populateResponse(
STATUS_CODES.NOT_FOUND,
makeCustomError('You cannot update this post', CUSTOM_ERROR_CODES.USER_NOT_AUTHORIZED),
);
}
return populateResponse(
STATUS_CODES.INTERNAL_SERVER_ERROR,
makeCustomError('Error updating post', CUSTOM_ERROR_CODES.POST_ERROR),
);
}
},
});