@nahkies/typescript-koa-runtime
Version:
Runtime package for code generated by @nahkies/openapi-code-generator using the typescript-koa template
1 lines • 2.78 kB
Source Map (JSON)
{"version":3,"file":"joi.mjs","names":[],"sources":["../../src/joi.ts"],"sourcesContent":["import {findMatchingSchema} from \"@nahkies/typescript-common-runtime/validation\"\n\nimport type {Schema as JoiSchema} from \"joi\"\nimport {KoaRuntimeError, type RequestInputType} from \"./errors.ts\"\n\n// Note: joi types don't appear to have an equivalent of z.infer,\n// hence any seems about as good as we can do here.\nexport function parseRequestInput<Schema extends JoiSchema>(\n schema: Schema,\n input: unknown,\n type: RequestInputType,\n // biome-ignore lint/suspicious/noExplicitAny: needed\n): any\nexport function parseRequestInput(\n schema: undefined,\n input: unknown,\n type: RequestInputType,\n): undefined\nexport function parseRequestInput<Schema extends JoiSchema>(\n schema: Schema | undefined,\n input: unknown,\n type: RequestInputType,\n // biome-ignore lint/suspicious/noExplicitAny: needed\n): any {\n try {\n if (!schema) {\n return undefined\n }\n\n const result = schema.validate(input, {stripUnknown: true})\n\n if (result.error) {\n throw result.error\n }\n\n return result.value\n } catch (err) {\n throw KoaRuntimeError.RequestError(err, type)\n }\n}\n\nexport function responseValidationFactory(\n possibleResponses: [string, JoiSchema][],\n defaultResponse?: JoiSchema,\n) {\n // Exploit the natural ordering matching the desired specificity of eg: 404 vs 4xx\n possibleResponses.sort((x, y) => (x[0] < y[0] ? -1 : 1))\n\n return (status: number, value: unknown) => {\n try {\n const schema = findMatchingSchema(status, possibleResponses)\n\n if (schema) {\n const result = schema.validate(value)\n\n if (result.error) {\n throw result.error\n }\n\n return result.value\n }\n\n if (defaultResponse) {\n const result = defaultResponse.validate(value)\n\n if (result.error) {\n throw result.error\n }\n\n return result.value\n }\n\n return value\n } catch (err) {\n throw KoaRuntimeError.ResponseError(err)\n }\n }\n}\n"],"mappings":";;;AAkBA,SAAgB,kBACd,QACA,OACA,MAEK;CACL,IAAI;EACF,IAAI,CAAC,QACH;EAGF,MAAM,SAAS,OAAO,SAAS,OAAO,EAAC,cAAc,KAAI,CAAC;EAE1D,IAAI,OAAO,OACT,MAAM,OAAO;EAGf,OAAO,OAAO;CAChB,SAAS,KAAK;EACZ,MAAM,gBAAgB,aAAa,KAAK,IAAI;CAC9C;AACF;AAEA,SAAgB,0BACd,mBACA,iBACA;CAEA,kBAAkB,MAAM,GAAG,MAAO,EAAE,KAAK,EAAE,KAAK,KAAK,CAAE;CAEvD,QAAQ,QAAgB,UAAmB;EACzC,IAAI;GACF,MAAM,SAAS,mBAAmB,QAAQ,iBAAiB;GAE3D,IAAI,QAAQ;IACV,MAAM,SAAS,OAAO,SAAS,KAAK;IAEpC,IAAI,OAAO,OACT,MAAM,OAAO;IAGf,OAAO,OAAO;GAChB;GAEA,IAAI,iBAAiB;IACnB,MAAM,SAAS,gBAAgB,SAAS,KAAK;IAE7C,IAAI,OAAO,OACT,MAAM,OAAO;IAGf,OAAO,OAAO;GAChB;GAEA,OAAO;EACT,SAAS,KAAK;GACZ,MAAM,gBAAgB,cAAc,GAAG;EACzC;CACF;AACF"}