-
Notifications
You must be signed in to change notification settings - Fork 0
/
update.ts
50 lines (47 loc) · 1.62 KB
/
update.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
import HttpError from "http-errors";
import middy from "middy";
import { jsonBodyParser, cors } from "middy/middlewares";
import { encodeResponse, jsonErrorHandler } from "@internote/lib/middlewares";
import { success } from "@internote/lib/responses";
import { getUserIdentityId } from "@internote/lib/user";
import { updateNoteById, findNoteById } from "./db/queries";
import { UpdateHandler } from "@internote/lib/types";
import { required, isArray, isString } from "@internote/lib/validator";
import { validateRequestBody } from "@internote/lib/middlewares";
import { UpdateNoteDTO } from "./types";
const update: UpdateHandler<UpdateNoteDTO, { noteId: string }> = async (
event,
_ctx,
callback
) => {
const userId = getUserIdentityId(event);
const { noteId } = event.pathParameters;
const existingNote = await findNoteById(noteId, userId);
if (
!event.body.overwrite &&
existingNote.dateUpdated &&
event.body.dateUpdated &&
existingNote.dateUpdated > event.body.dateUpdated
) {
throw new HttpError.Conflict(
`There is a newer version of note ${noteId} in the database`
);
}
const note = await updateNoteById(noteId, userId, event.body);
return callback(null, success(note));
};
export const validator = validateRequestBody<UpdateNoteDTO>({
noteId: [],
userId: [],
content: [required], // TODO: validate slate schema
title: [required, isString],
tags: [required, isArray(v => typeof v === "string")],
dateUpdated: [],
overwrite: []
});
export const handler = middy(update)
.use(jsonBodyParser())
.use(validator)
.use(encodeResponse())
.use(jsonErrorHandler())
.use(cors());