|
| 1 | +/** |
| 2 | + * Parameter validation helpers. |
| 3 | + * |
| 4 | + * These utilities exist to help migrate legacy `:param(regex)` usage from older |
| 5 | + * router/path-to-regexp versions to v14+ (path-to-regexp v8), where inline |
| 6 | + * parameter regexes are no longer supported in route strings. |
| 7 | + */ |
| 8 | + |
| 9 | +import createHttpError from 'http-errors'; |
| 10 | + |
| 11 | +import type { |
| 12 | + RouterContext, |
| 13 | + RouterMiddleware, |
| 14 | + RouterParameterMiddleware |
| 15 | +} from '../types'; |
| 16 | + |
| 17 | +/** |
| 18 | + * Options for createParameterValidationMiddleware helper |
| 19 | + */ |
| 20 | +export type ParameterValidationOptions = { |
| 21 | + /** |
| 22 | + * HTTP status to use when the value does not match |
| 23 | + * @default 400 |
| 24 | + */ |
| 25 | + status?: number; |
| 26 | + |
| 27 | + /** |
| 28 | + * Error message to use when the value does not match |
| 29 | + * @default `Invalid value for parameter "<parameterName>"` |
| 30 | + */ |
| 31 | + message?: string; |
| 32 | + |
| 33 | + /** |
| 34 | + * Whether the error message should be exposed to the client. |
| 35 | + * Passed through to HttpError#expose. |
| 36 | + */ |
| 37 | + expose?: boolean; |
| 38 | + |
| 39 | + /** |
| 40 | + * Optional custom error factory. If provided, it is used |
| 41 | + * instead of the default HttpError. |
| 42 | + */ |
| 43 | + createError?: (parameterName: string, value: string) => Error; |
| 44 | +}; |
| 45 | + |
| 46 | +/** |
| 47 | + * Convenience helper to recreate legacy `:param(regex)` validation. |
| 48 | + * |
| 49 | + * @example |
| 50 | + * const validateUuid = createParameterValidationMiddleware('id', uuidRegex); |
| 51 | + * router.param('id', validateUuid).get('/role/:id', handler); |
| 52 | + * router.get('/role/:id', createParameterValidationMiddleware('id', uuidRegex) |
| 53 | + */ |
| 54 | +export function createParameterValidationMiddleware( |
| 55 | + parameterName: string, |
| 56 | + pattern: RegExp, |
| 57 | + options: ParameterValidationOptions = {} |
| 58 | +): RouterMiddleware<any, any, any> & RouterParameterMiddleware<any, any, any> { |
| 59 | + if (!(pattern instanceof RegExp)) { |
| 60 | + throw new TypeError('pattern must be a RegExp instance'); |
| 61 | + } |
| 62 | + |
| 63 | + // clone the RegExp once so we do not mutate the caller's instance |
| 64 | + const matcher = new RegExp(pattern.source, pattern.flags); |
| 65 | + |
| 66 | + const createDefaultHttpError = (message: string) => { |
| 67 | + const httpError = createHttpError(options.status ?? 400, message); |
| 68 | + if (options.expose !== undefined) { |
| 69 | + httpError.expose = options.expose; |
| 70 | + } |
| 71 | + |
| 72 | + return httpError; |
| 73 | + }; |
| 74 | + |
| 75 | + const validateValue = (value: string) => { |
| 76 | + // ensure deterministic behavior even when /g or /y flags are present |
| 77 | + if (matcher.global || matcher.sticky) { |
| 78 | + matcher.lastIndex = 0; |
| 79 | + } |
| 80 | + |
| 81 | + if (matcher.test(value)) { |
| 82 | + return; |
| 83 | + } |
| 84 | + |
| 85 | + if (options.createError) { |
| 86 | + throw options.createError(parameterName, value); |
| 87 | + } |
| 88 | + |
| 89 | + throw createDefaultHttpError( |
| 90 | + options.message ?? |
| 91 | + `Invalid value for parameter "${parameterName}": "${value}"` |
| 92 | + ); |
| 93 | + }; |
| 94 | + |
| 95 | + const middleware: RouterMiddleware<any, any, any> & |
| 96 | + RouterParameterMiddleware<any, any, any> = async ( |
| 97 | + argument1: unknown, |
| 98 | + argument2: unknown, |
| 99 | + argument3?: unknown |
| 100 | + ) => { |
| 101 | + // called as a normal route middleware: (ctx, next) |
| 102 | + if (typeof argument1 !== 'string') { |
| 103 | + const context = argument1 as RouterContext<any, any, any> & { |
| 104 | + params?: Record<string, string>; |
| 105 | + }; |
| 106 | + const next = argument2 as Parameters<RouterMiddleware<any, any, any>>[1]; |
| 107 | + |
| 108 | + const parameterValue = |
| 109 | + context.params && parameterName in context.params |
| 110 | + ? context.params[parameterName] |
| 111 | + : undefined; |
| 112 | + |
| 113 | + if (typeof parameterValue !== 'string') { |
| 114 | + throw createDefaultHttpError( |
| 115 | + options.message ?? |
| 116 | + `Missing required parameter "${parameterName}" in route params` |
| 117 | + ); |
| 118 | + } |
| 119 | + |
| 120 | + validateValue(parameterValue); |
| 121 | + return next(); |
| 122 | + } |
| 123 | + |
| 124 | + // called as router.param middleware: (value, ctx, next) |
| 125 | + const value = argument1 as string; |
| 126 | + // // keep for compatibility (router.param passes ctx as second arg) |
| 127 | + // void argument2; |
| 128 | + const next = argument3 as () => Promise<unknown>; |
| 129 | + |
| 130 | + validateValue(value); |
| 131 | + return next(); |
| 132 | + }; |
| 133 | + |
| 134 | + return middleware; |
| 135 | +} |
0 commit comments