diff --git a/striker-ui-api/src/lib/request_handlers/buildDeleteRequestHandler.ts b/striker-ui-api/src/lib/request_handlers/buildDeleteRequestHandler.ts new file mode 100644 index 00000000..bc4c5c27 --- /dev/null +++ b/striker-ui-api/src/lib/request_handlers/buildDeleteRequestHandler.ts @@ -0,0 +1,65 @@ +import { AssertionError } from 'assert'; +import { RequestHandler } from 'express'; + +import { sanitize } from '../sanitize'; +import { stderr, stdoutVar } from '../shell'; + +export const buildDeleteRequestHandler = + < + P extends Record = Record, + ResBody = undefined, + ReqBody extends Record | undefined = Record< + string, + unknown + >, + ReqQuery = qs.ParsedQs, + Locals extends Record = Record, + >({ + delete: handleDelete, + key = 'uuid', + listKey = 'uuids', + }: { + delete: ( + list: string[], + ...handlerArgs: Parameters< + RequestHandler + > + ) => Promise; + key?: string; + listKey?: string; + }): RequestHandler => + async (...handlerArgs) => { + const { 0: request, 1: response } = handlerArgs; + const { + body: { [listKey]: rList } = {}, + params: { [key]: rId }, + } = request; + + const list = sanitize(rList, 'string[]'); + + if (rId !== undefined) { + list.push(rId); + } + + stdoutVar(list, `Process delete request with list: `); + + try { + await handleDelete(list, ...handlerArgs); + } catch (error) { + let scode; + + if (error instanceof AssertionError) { + scode = 400; + + stderr(`Failed to assert value during delete request; CAUSE: ${error}`); + } else { + scode = 500; + + stderr(`Failed to complete delete request; CAUSE: ${error}`); + } + + return response.status(scode).send(); + } + + return response.status(204).send(); + };