|
| 1 | +import type * as Types from '@interfaces/index.ts' |
| 2 | +import * as Core from '@core/index.ts' |
| 3 | +import * as Middleware from '@middleware/index.ts' |
| 4 | +import * as Validation from '@validation/index.ts' |
| 5 | +import type { ContractFn } from '@neabyte/typebox' |
| 6 | + |
| 7 | +/** |
| 8 | + * Request validation middleware for sources. |
| 9 | + * @description Runs source contracts, stores validated data on context. |
| 10 | + */ |
| 11 | +export class Validator { |
| 12 | + /** |
| 13 | + * Create validation middleware from schema. |
| 14 | + * @description Validates each source contract, stores result on context. |
| 15 | + * @param schema - Per-source validation contracts |
| 16 | + * @returns Middleware that validates request sources |
| 17 | + * @throws {Deno.errors.InvalidData} When schema has no source contract |
| 18 | + * @throws {Deno.errors.InvalidData} When schema validates params, unavailable before routing |
| 19 | + */ |
| 20 | + static create(schema: Types.ValidationSchema): Types.MiddlewareFn { |
| 21 | + const entries = Object.entries(schema).filter( |
| 22 | + (entry): entry is [Types.ValidationSource, ContractFn] => typeof entry[1] === 'function' |
| 23 | + ) |
| 24 | + if (entries.length === 0) { |
| 25 | + throw new Deno.errors.InvalidData('Validator requires at least one source contract') |
| 26 | + } |
| 27 | + if (entries.some(([source]) => source === 'params')) { |
| 28 | + throw new Deno.errors.InvalidData( |
| 29 | + 'Validator cannot validate params in middleware, route params resolve after middleware runs, validate them inside the handler with Validator.check(contract, ctx.params())' |
| 30 | + ) |
| 31 | + } |
| 32 | + return Middleware.WrapMware('Validation error', async (ctx, next) => { |
| 33 | + const existing = ctx.getState(Core.Handler.stateKeys.validated) |
| 34 | + const validated: Types.DataRecord = { ...existing } |
| 35 | + for (const [source, contract] of entries) { |
| 36 | + const input = await Validation.Source.extract(source, ctx) |
| 37 | + try { |
| 38 | + validated[source] = contract(input as never) |
| 39 | + } catch (error) { |
| 40 | + throw Validation.Reason.toStatusError(error) |
| 41 | + } |
| 42 | + } |
| 43 | + ctx[Core.InternalContext].setInternalState(Core.Handler.stateKeys.validated, validated) |
| 44 | + return await next() |
| 45 | + }) |
| 46 | + } |
| 47 | +} |
0 commit comments