|
| 1 | +import { NextApiRequest, NextApiResponse } from 'next' |
| 2 | +import morgan from 'morgan' |
| 3 | +import { Method, Status } from 'simple-http-status' |
| 4 | + |
| 5 | +import { CustomError } from './errors/custom-error' |
| 6 | +import { NotFoundError } from './errors/not-found-error' |
| 7 | +import { Hook, ServiceMethods } from './types' |
| 8 | + |
| 9 | +interface Pk { |
| 10 | + name?: string |
| 11 | + cast?: (pk: string) => string |
| 12 | +} |
| 13 | + |
| 14 | +interface Hooks { |
| 15 | + all?: Hook[] |
| 16 | + find?: Hook[] |
| 17 | + create?: Hook[] |
| 18 | + get?: Hook[] |
| 19 | + update?: Hook[] |
| 20 | + patch?: Hook[] |
| 21 | + remove?: Hook[] |
| 22 | +} |
| 23 | + |
| 24 | +interface ServiceOptions extends ServiceMethods { |
| 25 | + pk?: Pk |
| 26 | + hooks?: { |
| 27 | + before?: Hooks |
| 28 | + after?: Hooks |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +const logger = morgan( |
| 33 | + ':method :url :status :res[content-length] - :response-time ms', |
| 34 | +) |
| 35 | + |
| 36 | +const getPk = (pk: Pk = {}, query: NextApiRequest['query']): string | null => { |
| 37 | + const queryValue = pk?.name ? query[pk?.name] : query?.id || query?.pk |
| 38 | + const [value] = Array.isArray(queryValue) ? queryValue : [queryValue] |
| 39 | + return pk?.cast && value ? pk.cast(value!) : value |
| 40 | +} |
| 41 | + |
| 42 | +const getStatusCode = (type: keyof ServiceMethods) => { |
| 43 | + switch (type) { |
| 44 | + case 'create': |
| 45 | + return Status.HTTP_201_CREATED |
| 46 | + default: |
| 47 | + return Status.HTTP_200_OK |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +const runHandler = async ( |
| 52 | + type: keyof ServiceMethods, |
| 53 | + options: ServiceOptions, |
| 54 | + req: NextApiRequest, |
| 55 | + pk: string, |
| 56 | +) => { |
| 57 | + switch (type) { |
| 58 | + case 'find': |
| 59 | + return options.find!(req.query) |
| 60 | + case 'create': |
| 61 | + return options.create!(req.body) |
| 62 | + case 'get': |
| 63 | + return options.get!(pk, req.query) |
| 64 | + case 'update': |
| 65 | + return options.update!(pk, req.body, req.query) |
| 66 | + case 'patch': |
| 67 | + return options.patch!(pk, req.body, req.query) |
| 68 | + case 'remove': |
| 69 | + return options.remove!(pk) |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +const handleService = async ( |
| 74 | + type: keyof ServiceMethods, |
| 75 | + options: ServiceOptions, |
| 76 | + req: NextApiRequest, |
| 77 | + res: NextApiResponse, |
| 78 | +) => { |
| 79 | + const pk = getPk(options.pk, req.query) |
| 80 | + |
| 81 | + const runHooks = async (hooks: Hook[]) => { |
| 82 | + for (let index = 0; index < hooks.length; index++) { |
| 83 | + await hooks[index](req, res, () => {}) |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + const allBeforeHooks = options.hooks?.before?.all ?? [] |
| 88 | + const beforeHooks = options.hooks?.before?.[type] ?? [] |
| 89 | + await runHooks([...allBeforeHooks, ...beforeHooks]) |
| 90 | + |
| 91 | + const result = await runHandler(type, options, req, pk!) |
| 92 | + |
| 93 | + const allAfterHooks = options.hooks?.after?.all ?? [] |
| 94 | + const afterHooks = options.hooks?.after?.[type] ?? [] |
| 95 | + await runHooks([...allAfterHooks, ...afterHooks]) |
| 96 | + |
| 97 | + const statusCode = getStatusCode(type) |
| 98 | + |
| 99 | + return res.status(statusCode).json(result) |
| 100 | +} |
| 101 | + |
| 102 | +export const createService = (options: ServiceOptions) => async ( |
| 103 | + req: NextApiRequest, |
| 104 | + res: NextApiResponse, |
| 105 | +) => { |
| 106 | + logger(req, res, () => {}) |
| 107 | + |
| 108 | + try { |
| 109 | + const pk = getPk(options.pk, req.query) |
| 110 | + const { method } = req |
| 111 | + |
| 112 | + switch (true) { |
| 113 | + case options.get && pk && method === Method.GET: |
| 114 | + return handleService('get', options, req, res) |
| 115 | + |
| 116 | + case options.update && pk && method === Method.PUT: |
| 117 | + return handleService('update', options, req, res) |
| 118 | + |
| 119 | + case options.patch && pk && method === Method.PATCH: |
| 120 | + return handleService('patch', options, req, res) |
| 121 | + |
| 122 | + case options.remove && pk && method === Method.DELETE: |
| 123 | + return handleService('remove', options, req, res) |
| 124 | + |
| 125 | + case options.find && !pk && method === Method.GET: |
| 126 | + return handleService('find', options, req, res) |
| 127 | + |
| 128 | + case options.create && !pk && method === Method.POST: |
| 129 | + return handleService('create', options, req, res) |
| 130 | + |
| 131 | + default: |
| 132 | + throw new NotFoundError() |
| 133 | + } |
| 134 | + } catch (err) { |
| 135 | + if (err instanceof CustomError) { |
| 136 | + return res.status(err.statusCode).json({ |
| 137 | + errors: err.serializeErrors(), |
| 138 | + }) |
| 139 | + } |
| 140 | + |
| 141 | + return res.status(Status.HTTP_500_INTERNAL_SERVER_ERROR).json({ |
| 142 | + errors: [{ message: 'Something went wrong' }], |
| 143 | + }) |
| 144 | + } |
| 145 | +} |
0 commit comments