import { Request, Response } from 'hyper-express'; import { Logger } from '../Logger/Logger'; import { Action } from '../Action/Action'; import { v4 } from 'uuid'; import { BackendError } from '../BackendError/BackendError'; import { z, ZodEnum, ZodError, ZodFile, ZodObject, ZodOptional, ZodString, ZodType, ZodUnion, } from 'zod'; import { WorkerManager } from '../Workers/WorkerManager'; import { FileField, JsonField, multipart, MultipartParams, StringField, } from '../multipart/multipart.ts'; import { getFileMimeFromZod } from '../utils/getFileMimeFromZod.ts'; export interface RouteHandlerParams< Query extends ZodObject, Path extends ZodObject, Headers extends ZodObject, Body extends ZodObject, > { readonly res: Response; readonly req: Request; readonly logger: Logger; readonly action: (name: string) => Action; readonly json?: object; readonly query: z.infer; readonly path: z.infer; readonly headers: z.infer; readonly body: z.infer; readonly requestWorker: (params: P) => Promise; } export interface RouteConfig< Result extends ZodObject, Query extends ZodObject, Path extends ZodObject, Headers extends ZodObject, Body extends ZodObject, > { readonly info: { readonly method: 'get' | 'post' | 'put' | 'delete' | 'patch'; readonly summary: string; readonly route: string; readonly tags: string[]; readonly result: { readonly status: number; readonly content: Result; }; readonly query?: Query; readonly path?: Path; readonly headers?: Headers; readonly body?: { readonly contentType: 'application/json' | 'multipart/form-data'; readonly fileSizeLimit?: number; readonly payload: Body; }; }; readonly handler: ( params: RouteHandlerParams, ) => Promise> | z.infer; } const fallbackKey = '__withFallback__'; export const zFallbackFile = < File extends ZodFile | ZodOptional, Fallback extends ZodEnum | ZodString | ZodOptional, >( zFileOrOptional: File, zFallback: Fallback, ): ZodUnion<[File, Fallback]> => { if (zFileOrOptional instanceof ZodOptional) { if (!(zFileOrOptional.unwrap() instanceof ZodFile)) { throw new BackendError({ status: 400, cause: 'INVALID_PARAMS', message: 'Optional must be a file', }); } } if (zFallback instanceof ZodOptional) { if ( !( zFallback.unwrap() instanceof ZodEnum || zFallback.unwrap() instanceof ZodString ) ) { throw new BackendError({ status: 400, cause: 'INVALID_PARAMS', message: 'Optional must be a string or enum', }); } } const result = z.union([zFileOrOptional, zFallback]); // TODO: FIX DIRTY HACK //@ts-ignore result[fallbackKey] = true; return result as ZodUnion<[File, Fallback]>; }; const unpackFileWithFallback = (zUnion: ZodUnion): FileField => { const [zFile, zFallback] = zUnion.options as [ ZodFile | ZodOptional, ZodEnum | ZodString | ZodOptional, ]; return { type: 'file', supportedMimes: zFile instanceof ZodFile ? getFileMimeFromZod(zFile) : getFileMimeFromZod(zFile.unwrap()), optional: zFile instanceof ZodOptional, or: { type: 'string', optional: zFallback instanceof ZodOptional, }, }; }; const getMultipartField = ( zType: ZodType, optional: boolean = false, ): JsonField | StringField | FileField => { // @ts-ignore if (zType instanceof ZodUnion && zType[fallbackKey]) { return unpackFileWithFallback(zType); } if (zType instanceof ZodOptional) { return getMultipartField(zType.unwrap() as ZodType, true); } if (zType instanceof ZodFile) { return { type: 'file', supportedMimes: getFileMimeFromZod(zType), optional, }; } if (zType instanceof ZodObject) { return { type: 'json', optional, }; } if (zType instanceof ZodString) { return { type: 'string', optional, }; } throw new BackendError({ status: 400, cause: 'INVALID_PARAMS', message: `Invalid field type: ${zType.constructor.name}`, }); }; const getMultipartFields = ( zType: ZodObject, ): MultipartParams['fields'] => { const fields: MultipartParams['fields'] = {}; for (let item in zType.shape) { fields[item] = getMultipartField(zType.shape[item]); } return fields; }; export class Route< Result extends ZodObject, Query extends ZodObject, Path extends ZodObject, Headers extends ZodObject, Body extends ZodObject, > { static new< Result extends ZodObject, Query extends ZodObject, Path extends ZodObject, Headers extends ZodObject, Body extends ZodObject, >(params: RouteConfig) { return new Route(params); } public readonly info: RouteConfig['info']; public readonly handler: ( workerManager: WorkerManager | undefined, ) => (req: Request, res: Response) => void; private assertZod(zodObject: ZodObject | undefined, data: any): any { if (!zodObject) { return true; } try { return zodObject.parse(data); } catch (e) { if (e instanceof ZodError) { throw new BackendError({ status: 400, cause: 'INVALID_PARAMS', message: e.message, stack: '', }); } throw new BackendError({ status: 400, cause: 'INVALID_PARAMS', message: e as string, stack: '', }); } } private constructor({ info, handler, }: RouteConfig) { this.info = info; this.handler = (workerManager) => async (req, res) => { const requestId = v4(); const logger = Logger.new(requestId); const action = (name: string) => Action.new({ name, logger }); const reqContentType = req.headers['content-type']; logger.debug( `Start "${info.method.toUpperCase()} ${info.route}" method execution`, ); try { if ( this.info.body?.contentType && !reqContentType.startsWith(this.info.body.contentType) ) { throw new BackendError({ cause: 'content-type', status: 400, message: 'Unsupported content type', }); } const query = req.query; const path = req.params; const headers = req.headers; let body = req.body; if (this.info.body?.contentType === 'application/json') { body = await req.json(); } if (this.info.body?.contentType === 'multipart/form-data') { const fields: MultipartParams['fields'] = getMultipartFields( this.info.body.payload, ); body = await multipart(req, { limits: { fileSize: this.info.body.fileSizeLimit || 1024 * 1024, }, fields, }); } logger.debug({ message: `Start "${info.method.toUpperCase()} ${info.route}" method execution`, input: { contentType: req.headers['content-type'], body, query, path, headers, }, }); logger.debug('start received data check:'); const parsedPath = this.assertZod(this.info.path, path); const parsedHeaders = this.assertZod(this.info.headers, headers); const parsedBody = this.assertZod(this.info.body?.payload, body); const parsedQuery = this.assertZod(this.info.query, query); const result = await Promise.resolve().then(() => handler({ req, res, logger, action, query: parsedQuery, path: parsedPath, headers: parsedHeaders, body: parsedBody, requestWorker: (params) => { if (!workerManager) { throw new Error('Setup worker manager before'); } return workerManager.request(params, logger); }, }), ); logger.debug({ message: `"${info.method.toUpperCase()} ${info.route}" method execution: Success`, response: result, }); res.status(this.info.result.status).json(result); } catch (e) { const errorObject = e instanceof BackendError ? { cause: e.cause, message: e.message, status: e.status, } : { cause: 'Unknown', message: e instanceof Error ? e.message : (e as string), status: 400, }; logger.error({ message: `"${req.url}" method execution: Error.`, error: errorObject, }); res.status(errorObject.status).json({ cause: errorObject.cause, message: errorObject.message, requestId: requestId, }); } }; } }