-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathuseNoteResolver.ts
More file actions
73 lines (67 loc) · 2.38 KB
/
useNoteResolver.ts
File metadata and controls
73 lines (67 loc) · 2.38 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
import type { FastifyRequest, preHandlerHookHandler } from 'fastify';
import type NoteService from '@domain/service/note.js';
import { notEmpty } from '@infrastructure/utils/empty.js';
import { StatusCodes } from 'http-status-codes';
import hasProperty from '@infrastructure/utils/hasProperty.js';
import { getRequestLogger } from '@infrastructure/logging/index.js';
import type { Note, NotePublicId } from '@domain/entities/note.js';
/**
* Add middleware for resolve Note by public id and add it to request
* @param noteService - note domain service
*/
export default function useNoteResolver(noteService: NoteService): {
/**
* Resolve Note by public id and add it to request
*
* Use this middleware as "preHandler" hook with a particular route
*/
noteResolver: preHandlerHookHandler;
} {
/**
* Search for Note by public id in passed payload and resolves a note by it
* @param requestData - fastify request data. Can be query, params or body
*/
async function resolveNoteByPublicId(requestData: FastifyRequest['query']): Promise<Note | undefined> {
/**
* Request params validation
*/
if (hasProperty(requestData, 'notePublicId') && notEmpty(requestData.notePublicId)) {
const publicId = requestData.notePublicId as NotePublicId;
return await noteService.getNoteByPublicId(publicId);
}
}
return {
noteResolver: async function noteIdResolver(request, reply) {
const logger = getRequestLogger('middlewares');
let note: Note | undefined;
let statusCode = StatusCodes.NOT_ACCEPTABLE;
/**
* This status code occurs only when request is get note by id
*/
if (request.method == 'GET') {
statusCode = StatusCodes.NOT_FOUND;
}
try {
/**
* All methods (GET, POST, PATCH, etc) could have note public id just in route params,
* so we don't check for query and body at the moment
*/
note = await resolveNoteByPublicId(request.params);
if (note) {
request.note = note;
logger.debug('Note resolved by public ID');
} else {
throw new Error('Note not found');
}
} catch (error) {
logger.error('Invalid Note public passed');
logger.error(error);
await reply
.code(statusCode)
.send({
message: 'Note not found',
});
}
},
};
}