feat: another idea of Validator Middleware (#535)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat: Another idea of validator middleware * denoify * set property value in constructor * rename `option` to `options` * add test for handling type error * use `test` instead of `match`
authored by Yusuke Wada · committed by GitHub · parent 5573c59 · Browse files · 24 files·+1212 added−984 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
24 files+1212 added−984 removed
- tests:+299 added−293 removed
- other:+913 added−691 removed
Provenance
- Commit
a2cc1a0- Tree
a4561ef- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
5573c59
24 files changed+1212 added−984 removed
modified:deno_dist/middleware/validator/index.ts+1 added-4 removed
123452import { validatorMiddleware } from './middleware.ts'import { validator } from './validator.ts'
const validation = validatorMiddleware<typeof validator>(validator)export { validation }export { validatorMiddleware as validator }modified:deno_dist/middleware/validator/middleware.ts+50 added-192 removed
1232345567891011121314671617181920212289101112131415161718192021222324252630313233342728363738394041424344293031323334464748353637383940415051525354555657585942436162636465666768697071727374757677787980818283848586878889909192939495969798991004445464748495051525354102103104105106107108109110111112113114115116117118119120121122123124555657581271281291301311321331341351361371381391405960616263646514314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820966672102116869707172import type { Context } from '../../context.ts'import type { MiddlewareHandler } from '../../hono.ts'import { JSONPathCopy } from '../../utils/json.ts'import type { Environment, Handler } from '../../hono.ts'import { Validator } from './validator.ts'import type { VBase, VString, VNumber, VBoolean, VObject, ValidateResult } from './validator.ts'
type Param = | string | number | string[] | number[] | Record<string, string | number> | ValidatorMessagetype Rule = Function | [Function, ...Param[]]type Rules = Rule | Rule[]type Done = (resultSet: ResultSet, context: Context) => Response | voidtype ValidationFunction<T> = (v: Validator, c: Context) => T
type RuleSet = { body: Record<string, Rules> json: Record<string, Rules> header: Record<string, Rules> query: Record<string, Rules> done: Done removeAdditional: booleantype Schema = Record<string, VString | VNumber | VBoolean | VObject>type SchemaToProp<T> = { [K in keyof T]: T[K] extends VBase ? T[K]['type'] extends 'number' ? number : T[K]['type'] extends 'boolean' ? boolean : T[K]['type'] extends 'string' ? string : never : never}
type ResultSet = { hasError: boolean messages: string[] results: ValidateResult[]}
type Result = { rule: Function params: Param[] message?: string}type Done = (resultSet: ResultSet, context: Context) => Response | void
export class ValidatorMessage { value: string constructor(value: string) { this.value = value } getMessage(): string { return this.value }}export const validatorMiddleware = <T extends Schema>( validationFunction: ValidationFunction<T>, options?: { done?: Done }) => { const v = new Validator()
const message = (value: string): ValidatorMessage => { return new ValidatorMessage(value)} const handler: Handler<string, Environment, SchemaToProp<T>> = async (c, next) => { const resultSet: ResultSet = { hasError: false, messages: [], results: [], }
export const validatorMiddleware = <Validator>(validator: Validator) => { return ( validatorFunction: ( validator: Validator, message: (value: string) => ValidatorMessage, context: Context ) => Partial<RuleSet> ): MiddlewareHandler => { return async (c, next) => { const validations = validatorFunction(validator, message, c) const schema = validationFunction(v, c)
const result: ResultSet = { hasError: false, messages: [], }
const v = validations v.removeAdditional = v.removeAdditional === undefined ? true : v.removeAdditional // default value is `true`
function validate(rules: Rules, value: string, messageFunc: (ruleName: string) => string) { value ||= ''
let count = 0 const results: Result[] = []
const check = (rules: Rules) => { if (!Array.isArray(rules)) { if (rules instanceof ValidatorMessage) { if (results[count - 1]) { results[count - 1].message = rules.getMessage() } } else if (typeof rules === 'function') { results[count] = { rule: rules, params: [], } count++ } else { results[count - 1].params.push(rules) } } else { if (typeof rules[0] === ('string' || 'number')) { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore results[count - 1].params.push(rules) } else { for (const rule of rules) { check(rule as Rules) } } } for (const key of Object.keys(schema)) { const validator = schema[key] const result = await validator.validate(c.req) if (result.isValid) { // Set data on request object c.req.valid(key, result.value) } else { resultSet.hasError = true if (result.message !== undefined) { resultSet.messages.push(result.message) } check(rules)
let invalid = false results.map((r) => { const ok = r.rule(value, ...r.params) if (!invalid && ok === false) { invalid = true if (r.message) { result.messages.push(r.message) } else { result.messages.push(messageFunc(r.rule.name)) } } if (typeof ok !== 'boolean') { // ok is sanitized string value = ok } })
if (invalid) { result.hasError = true return } } resultSet.results.push(result) }
if (v.query) { const query = v.query const realQueries = c.req.query() const validatedQueries: Record<string, string> = {}
Object.keys(query).map((key) => { validatedQueries[key] = realQueries[key] || '' const message = (name: string) => `Invalid Value: the query parameter "${key}" is invalid - ${name}` validate(query[key], validatedQueries[key], message) }) if (!result.hasError && v.removeAdditional) { c.req.queryData = validatedQueries } if (options && options.done) { const res = options.done(resultSet, c) if (res) { return res } }
if (v.header) { const header = v.header const realHeaders: Record<string, string> = {} for (const key of c.req.headers.keys()) { realHeaders[key] = c.req.headers.get(key) || '' } const validatedHeaders: Record<string, string> = {}
Object.keys(header).map((key) => { validatedHeaders[key] = realHeaders[key] || '' const message = (name: string) => `Invalid Value: the request header "${key}" is invalid - ${name}` validate(header[key], validatedHeaders[key], message) }) if (!result.hasError && v.removeAdditional) { c.req.headerData = validatedHeaders } }
if (v.body) { const field = v.body const parsedBody = (await c.req.parseBody()) as Record<string, string> const kv = { ...parsedBody } const validatedKv: Record<string, string> = {}
Object.keys(field).map(async (key) => { validatedKv[key] = kv[key] || '' const message = (name: string) => `Invalid Value: the request body "${key}" is invalid - ${name}` validate(field[key], validatedKv[key], message) }) if (!result.hasError && v.removeAdditional) { c.req.bodyData = validatedKv } }
if (v.json) { const field = v.json let json: object try { json = await c.req.json() } catch { json = {} } const validatedJson: object = new (json as any).constructor()
Object.keys(field).map(async (key) => { const value = JSONPathCopy(json, validatedJson, key) const message = (name: string) => `Invalid Value: the JSON body "${key}" is invalid - ${name}` validate(field[key], value, message) })
if (!result.hasError && v.removeAdditional) { c.req.jsonData = validatedJson } }
if (v.done) { const res = v.done(result, c) if (res) { return res } }
if (result.hasError) { return c.text(result.messages.join('\n'), 400) if (resultSet.hasError) { return c.text(resultSet.messages.join('\n'), 400) } await next() } await next() } return handler}added:deno_dist/middleware/validator/rule.ts+83 added
1+// Some validation rules is are based on Validator.js2+// Validator.js3+// License (MIT)4+// Copyright (c) 2018 Chris O'Hara <cohara87@gmail.com>5+// https://github.com/validatorjs/validator.js6+7+export const rule = {8+ // string9+ isEmpty(10+ value: string,11+ options: {12+ ignore_whitespace: boolean13+ } = { ignore_whitespace: false }14+ ): boolean {15+ return (options.ignore_whitespace ? value.trim().length : value.length) === 016+ },17+18+ isLength: (19+ value: string,20+ options: Partial<{ min: number; max: number }> | number,21+ arg2?: number22+ ) => {23+ let min: number24+ let max: number | undefined25+ if (typeof options === 'object') {26+ min = options.min || 027+ max = options.max28+ } else {29+ // backwards compatibility: isLength(str, min [, max])30+ min = options || 031+ max = arg232+ }33+ const presentationSequences = value.match(/(\uFE0F|\uFE0E)/g) || []34+ const surrogatePairs = value.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g) || []35+ const len = value.length - presentationSequences.length - surrogatePairs.length36+ return len >= min && (typeof max === 'undefined' || len <= max)37+ },38+39+ isAlpha: (value: string): boolean => {40+ return /^[A-Z]+$/i.test(value)41+ },42+43+ isNumeric: (value: string): boolean => {44+ return /^[0-9]+$/.test(value)45+ },46+47+ contains: (48+ value: string,49+ elem: string,50+ options: Partial<{ ignoreCase: boolean; minOccurrences: number }> = {51+ ignoreCase: false,52+ minOccurrences: 1,53+ }54+ ): boolean => {55+ options.ignoreCase ||= false56+ options.minOccurrences ||= 157+ if (options.ignoreCase) {58+ return value.toLowerCase().split(elem.toLowerCase()).length > options.minOccurrences59+ }60+ return value.split(elem).length > options.minOccurrences61+ },62+63+ isIn: (value: string, options: string[]): boolean => {64+ if (typeof options === 'object') {65+ for (const elem of options) {66+ if (elem === value) return true67+ }68+ }69+ return false70+ },71+72+ match: (value: string, regExp: RegExp): boolean => {73+ return regExp.test(value)74+ },75+76+ // number77+ isGte: (value: number, min: number) => min <= value,78+ isLte: (value: number, max: number) => value <= max,79+80+ // boolean81+ isTrue: (value: boolean) => value === true,82+ isFalse: (value: boolean) => value === false,83+}added:deno_dist/middleware/validator/sanitizer.ts+3 added
123export const sanitizer = { trim: (value: string) => value.trim(),}modified:deno_dist/middleware/validator/validator.ts+224 added-82 removed
1-// Some validation rules is are based on Validator.js2-// Validator.js3-// License (MIT)4-// Copyright (c) 2018 Chris O'Hara <cohara87@gmail.com>5-// https://github.com/validatorjs/validator.js1+import { JSONPath } from '../../utils/json.ts'2+import { rule } from './rule.ts'3+import { sanitizer } from './sanitizer.ts'4 7-const isString = (value: any) => {8- return typeof value === 'string'5+type Target = 'query' | 'header' | 'body' | 'json'6+type Type = string | number | boolean | object | undefined7+type Rule = (value: Type) => boolean8+type Sanitizer = (value: Type) => Type9+10+export class Validator {11+ query = (key: string): VString => new VString({ target: 'query', key: key })12+ header = (key: string): VString => new VString({ target: 'header', key: key })13+ body = (key: string): VString => new VString({ target: 'body', key: key })14+ json = (key: string): VString => new VString({ target: 'json', key: key })15 }16 11-export const validator = {12- required(value: unknown): boolean {13- if (value === undefined) return false14- if (isString(value) && value === '') return false15- return true16- },17+export type ValidateResult = {18+ isValid: boolean19+ message: string | undefined20+ target: Target21+ key: string22+ value: Type23+}24 18- optional(): boolean {19- return true20- },25+type VOptions = {26+ target: Target27+ key: string28+ type?: 'string' | 'number' | 'boolean' | 'object'29+}30 22- isBoolean(value: unknown): boolean {23- return typeof value === 'boolean'24- },31+export abstract class VBase {32+ type: 'string' | 'number' | 'boolean' | 'object'33+ target: Target34+ key: string35+ rules: Rule[]36+ sanitizers: Sanitizer[]37+ private _message: string | undefined38 26- isNumber(value: unknown): boolean {27- return typeof value === 'number'28- },39+ constructor(options: VOptions) {40+ this.target = options.target41+ this.key = options.key42+ this.type = options.type || 'string'43+ this.rules = []44+ this.sanitizers = []45+ }46 30- isFalsy(value: unknown): boolean {31- return !value32- },47+ addRule = (rule: Rule) => {48+ this.rules.push(rule)49+ return this50+ }51 34- isNotFalsy(value: unknown): boolean {35- return !!value36- },52+ addSanitizer = (sanitizer: Sanitizer) => {53+ this.sanitizers.push(sanitizer)54+ return this55+ }56 38- isAlpha(value: string): boolean {39- return isString(value) && value.match(/^[A-Z]+$/i) ? true : false40- },57+ isRequired = () => {58+ return this.addRule((value: unknown) => {59+ if (value) return true60+ return false61+ })62+ }63 42- isNumeric(value: string): boolean {43- return isString(value) && value.match(/^[0-9]+$/) ? true : false44- },64+ isOptional = () => {65+ return this.addRule(() => true)66+ }67 46- isEmpty(47- value: string,68+ isEqual = (comparison: unknown) => {69+ return this.addRule((value: unknown) => {70+ return value === comparison71+ })72+ }73+74+ asNumber = () => {75+ const newVNumber = new VNumber(this)76+ return newVNumber77+ }78+79+ asBoolean = () => {80+ const newVBoolean = new VBoolean(this)81+ return newVBoolean82+ }83+84+ asObject = () => {85+ const newVObject = new VObject(this)86+ return newVObject87+ }88+89+ message(value: string) {90+ this._message = value91+ return this92+ }93+94+ validate = async (req: Request): Promise<ValidateResult> => {95+ const result: ValidateResult = {96+ isValid: true,97+ message: undefined,98+ target: this.target,99+ key: this.key,100+ value: undefined,101+ }102+103+ let value: Type = undefined104+ if (this.target === 'query') {105+ value = req.query(this.key)106+ }107+ if (this.target === 'header') {108+ value = req.header(this.key)109+ }110+ if (this.target === 'body') {111+ const body = await req.parseBody()112+ value = body[this.key]113+ }114+ if (this.target === 'json') {115+ const obj = await req.json()116+ value = JSONPath(obj, this.key)117+ }118+119+ result.value = value120+ result.isValid = this.validateValue(value)121+122+ if (result.isValid == false) {123+ if (this._message) {124+ result.message = this._message125+ } else {126+ switch (this.target) {127+ case 'query':128+ result.message = `Invalid Value: the query parameter "${this.key}" is invalid - ${value}`129+ break130+ case 'header':131+ result.message = `Invalid Value: the request header "${this.key}" is invalid - ${value}`132+ break133+ case 'body':134+ result.message = `Invalid Value: the request body "${this.key}" is invalid - ${value}`135+ break136+ case 'json':137+ result.message = `Invalid Value: the JSON body "${this.key}" is invalid - ${value}`138+ break139+ }140+ }141+ }142+ return result143+ }144+145+ private validateValue = (value: Type): boolean => {146+ // Check type147+ if (typeof value !== this.type) {148+ return false149+ }150+151+ // Sanitize152+ for (const sanitizer of this.sanitizers) {153+ value = sanitizer(value)154+ }155+156+ for (const rule of this.rules) {157+ if (!rule(value)) {158+ return false159+ }160+ }161+ return true162+ }163+}164+165+export class VString extends VBase {166+ constructor(options: VOptions) {167+ super(options)168+ this.type = 'string'169+ }170+171+ isEmpty = (172 options: {173 ignore_whitespace: boolean174 } = { ignore_whitespace: false }51- ): boolean {52- return (isString(value) && options.ignore_whitespace ? value.trim().length : value.length) === 053- },175+ ) => {176+ return this.addRule((value) => rule.isEmpty(value as string, options))177+ }178 55- isLength(value: string, options: Partial<{ min: number; max: number }> | number, arg2?: number) {56- if (!isString(value)) return false57- let min: number58- let max: number | undefined59- if (typeof options === 'object') {60- min = options.min || 061- max = options.max62- } else {63- // backwards compatibility: isLength(str, min [, max])64- min = options || 065- max = arg266- }67- const presentationSequences = value.match(/(\uFE0F|\uFE0E)/g) || []68- const surrogatePairs = value.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g) || []69- const len = value.length - presentationSequences.length - surrogatePairs.length70- return len >= min && (typeof max === 'undefined' || len <= max)71- },179+ isLength = (options: Partial<{ min: number; max: number }> | number, arg2?: number) => {180+ return this.addRule((value) => rule.isLength(value as string, options, arg2))181+ }182 73- contains(74- value: string,183+ isAlpha = () => {184+ return this.addRule((value) => rule.isAlpha(value as string))185+ }186+187+ isNumeric = () => {188+ return this.addRule((value) => rule.isNumeric(value as string))189+ }190+191+ contains = (192 elem: string,193 options: Partial<{ ignoreCase: boolean; minOccurrences: number }> = {194 ignoreCase: false,195 minOccurrences: 1,196 }80- ): boolean {81- options.ignoreCase ||= false82- options.minOccurrences ||= 183- if (!isString(value) || !isString(elem)) return false84- if (options.ignoreCase) {85- return value.toLowerCase().split(elem.toLowerCase()).length > options.minOccurrences86- }87- return value.split(elem).length > options.minOccurrences88- },197+ ) => {198+ return this.addRule((value) => rule.contains(value as string, elem, options))199+ }200 90- equals(value: unknown, comparison: unknown): boolean {91- return value === comparison92- },201+ isIn = (options: string[]) => {202+ return this.addRule((value) => rule.isIn(value as string, options))203+ }204 94- isIn(value: string, options: string[]): boolean {95- if (!isString(value)) return false96- if (typeof options === 'object') {97- for (const elem of options) {98- if (elem === value) return true99- }100- }101- return false102- },205+ match = (regExp: RegExp) => {206+ return this.addRule((value) => rule.match(value as string, regExp))207+ }208 104- trim(value: string): string {105- return isString(value) ? value.trim() : value106- },209+ trim = () => {210+ return this.addSanitizer((value) => sanitizer.trim(value as string))211+ }212 }213+214+export class VNumber extends VBase {215+ constructor(options: VOptions) {216+ super(options)217+ this.type = 'number'218+ }219+220+ isGte = (min: number) => {221+ return this.addRule((value) => rule.isGte(value as number, min))222+ }223+224+ isLte = (min: number) => {225+ return this.addRule((value) => rule.isLte(value as number, min))226+ }227+}228+229+export class VBoolean extends VBase {230+ constructor(options: VOptions) {231+ super(options)232+ this.type = 'boolean'233+ }234+235+ isTrue = () => {236+ return this.addRule((value) => rule.isTrue(value as boolean))237+ }238+239+ isFalse = () => {240+ return this.addRule((value) => rule.isFalse(value as boolean))241+ }242+}243+244+export class VObject extends VBase {245+ constructor(options: VOptions) {246+ super(options)247+ this.type = 'object'248+ }249+}modified:deno_dist/utils/encode.ts+1 added-1 removed
1-import { Buffer } from "https://deno.land/std@0.155.0/node/buffer.ts";1+import { Buffer } from "https://deno.land/std@0.156.0/node/buffer.ts";2 export const encodeBase64 = (str: string): string => {3 if (str === null) {4 throw new TypeError('1st argument of "encodeBase64" should not be null.')5 }72 unmodified linesmodified:deno_dist/utils/json.ts+7 added-23 removed
112345345867811121314151617181920212291011241213141528293031321617export const JSONPathCopy = (src: object, dst: object, path: string) => {export const JSONPath = (data: object, path: string) => { // eslint-disable-next-line @typescript-eslint/no-explicit-any let srcVal: any = src // eslint-disable-next-line @typescript-eslint/no-explicit-any let dstVal: any = dst let val: any = data const parts = path.split('.') const length = parts.length for (let i = 0; i < length && srcVal !== undefined; i++) { for (let i = 0; i < length && val !== undefined; i++) { const p = parts[i] if (p !== '') { if (typeof srcVal === 'object') { if (typeof srcVal[p] === 'object') { dstVal[p] ||= new srcVal[p].constructor() } else if (p in srcVal) { dstVal[p] = srcVal[p] } else { return undefined } srcVal = srcVal[p] dstVal = dstVal[p] if (typeof val === 'object') { val = val[p] } else { return undefined val = undefined } } }
if (typeof srcVal === 'object') { Object.assign(dstVal, srcVal) } return srcVal return val}modified:deno_dist/context.ts+16 added-8 removed
1-import type { Environment, NotFoundHandler, ContextVariableMap, Bindings } from './hono.ts'1+import type {2+ Environment,3+ NotFoundHandler,4+ ContextVariableMap,5+ Bindings,6+ ValidatedData,7+} from './hono.ts'8 import { defaultNotFoundMessage } from './hono.ts'9 import type { CookieOptions } from './utils/cookie.ts'10 import { serialize } from './utils/cookie.ts'11 import type { StatusCode } from './utils/http-status.ts'3 unmodified lines15 export type Data = string | ArrayBuffer | ReadableStream16 17 export interface Context<18 RequestParamKeyType extends string = string,13- E extends Partial<Environment> = any19+ E extends Partial<Environment> = any,20+ D extends ValidatedData = ValidatedData21 > {15- req: Request<RequestParamKeyType>22+ req: Request<RequestParamKeyType, D>23 env: E['Bindings']24 event: FetchEvent25 executionCtx: ExecutionContext26 finalized: boolean24 unmodified lines51 }52 53 export class HonoContext<54 RequestParamKeyType extends string = string,48- E extends Partial<Environment> = Environment49-> implements Context<RequestParamKeyType, E>55+ E extends Partial<Environment> = Environment,56+ D extends ValidatedData = ValidatedData57+> implements Context<RequestParamKeyType, E, D>58 {51- req: Request<RequestParamKeyType>59+ req: Request<RequestParamKeyType, D>60 env: E['Bindings']61 finalized: boolean62 63 _status: StatusCode = 2005 unmodified lines69 private _res: Response | undefined70 private notFoundHandler: NotFoundHandler<E>71 72 constructor(65- req: Request,73+ req: Request<RequestParamKeyType>,74 env: E['Bindings'] | undefined = undefined,75 executionCtx: FetchEvent | ExecutionContext | undefined = undefined,76 notFoundHandler: NotFoundHandler<E> = () => new Response()77 ) {78 this._executionCtx = executionCtx71- this.req = req79+ this.req = req as Request<RequestParamKeyType, D>80 this.env = env || ({} as Bindings)81 82 this.notFoundHandler = notFoundHandler83 this.finalized = false117 unmodified linesmodified:deno_dist/hono.ts+51 added-35 removed
18 unmodified lines19 Bindings: Bindings20 Variables: Variables21 }22 23+export type ValidatedData = Record<string, any> // For validated data24+25 export type Handler<26 RequestParamKeyType extends string = string,25- E extends Partial<Environment> = Environment27+ E extends Partial<Environment> = Environment,28+ D extends ValidatedData = ValidatedData29 > = (27- c: Context<RequestParamKeyType, E>,30+ c: Context<RequestParamKeyType, E, D>,31 next: Next32 ) => Response | Promise<Response> | Promise<void> | Promise<Response | undefined>33 34 export type MiddlewareHandler = <E extends Partial<Environment> = Environment>(27 unmodified lines62 ? ParamKey<Component> | ParamKeys<Rest>63 : ParamKey<Path>64 65 interface HandlerInterface<63- T extends string = string,64- E extends Partial<Environment> = Environment,65- U = Hono<E, T>66+ T extends string,67+ E extends Partial<Environment>,68+ D extends ValidatedData,69+ U = Hono<E, T, D>70 > {71 // app.get(handler...)68- <Path extends string, Env extends Partial<Environment> = E>(69- ...handlers: Handler<ParamKeys<Path> extends never ? string : ParamKeys<Path>, Env>[]72+ <Path extends string, Env extends Partial<Environment>, Data extends ValidatedData = D>(73+ ...handlers: Handler<ParamKeys<Path> extends never ? string : ParamKeys<Path>, Env, Data>[]74 ): U71- (...handlers: Handler<string, E>[]): U75+ (...handlers: Handler<string, E, D>[]): U76 // app.get('/', handler, handler...)73- <Path extends string, Env extends Partial<Environment> = E>(77+ <Path extends string, Env extends Partial<Environment> = E, Data extends ValidatedData = D>(78 path: Path,75- ...handlers: Handler<ParamKeys<Path> extends never ? string : ParamKeys<Path>, Env>[]79+ ...handlers: Handler<ParamKeys<Path> extends never ? string : ParamKeys<Path>, Env, Data>[]80 ): U77- (path: string, ...handlers: Handler<string, E>[]): U81+ (path: string, ...handlers: Handler<string, E, D>[]): U82 }83 84 type Methods = typeof METHODS[number] | typeof METHOD_NAME_ALL_LOWERCASE85 86 function defineDynamicClass(): {83- new <E extends Partial<Environment> = Environment, T extends string = string, U = Hono>(): {84- [K in Methods]: HandlerInterface<T, E, U>87+ new <88+ E extends Partial<Environment> = Environment,89+ T extends string = string,90+ D extends ValidatedData = ValidatedData,91+ U = Hono<E, T, D>92+ >(): {93+ [K in Methods]: HandlerInterface<T, E, D, U>94 }95 } {96 return class {} as any97 }98 90-interface Route<E extends Partial<Environment> = Environment> {99+interface Route<100+ E extends Partial<Environment> = Environment,101+ D extends ValidatedData = ValidatedData102+> {103 path: string104 method: string93- handler: Handler<string, E>105+ handler: Handler<string, E, D>106 }107 108 export class Hono<109 E extends Partial<Environment> = Environment,98- P extends string = '/'99-> extends defineDynamicClass()<E, P, Hono<E, P>> {100- readonly router: Router<Handler<string, E>> = new SmartRouter({110+ P extends string = '/',111+ D extends ValidatedData = ValidatedData112+> extends defineDynamicClass()<E, P, D, Hono<E, P, D>> {113+ readonly router: Router<Handler<string, E, D>> = new SmartRouter({114 routers: [new StaticRouter(), new RegExpRouter(), new TrieRouter()],115 })116 readonly strict: boolean = true // strict routing - default is true117 private _tempPath: string = ''118 private path: string = '/'119 107- routes: Route<E>[] = []120+ routes: Route<E, D>[] = []121 122 constructor(init: Partial<Pick<Hono, 'router' | 'strict'>> = {}) {123 super()124 1 unmodified line126 127 const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE]128 allMethods.map((method) => {129 this[method] = <Path extends string = ''>(117- args1: Path | Handler<ParamKeys<Path>, E>,118- ...args: [Handler<ParamKeys<Path>, E>]130+ args1: Path | Handler<ParamKeys<Path>, E, D>,131+ ...args: [Handler<ParamKeys<Path>, E, D>]132 ): this => {133 if (typeof args1 === 'string') {134 this.path = args1135 } else {21 unmodified lines157 const message = 'Internal Server Error'158 return c.text(message, 500)159 }160 148- route(path: string, app?: Hono<any>): Hono<E, P> {161+ route(path: string, app?: Hono<any>): Hono<E, P, D> {162 this._tempPath = path163 if (app) {164 app.routes.map((r) => {165 this.addRoute(r.method, r.path, r.handler)3 unmodified lines169 170 return this171 }172 160- use<Path extends string = string, Env extends Partial<Environment> = E>(161- ...middleware: Handler<Path, Env>[]162- ): Hono<Env, Path>163- use<Path extends string = string, Env extends Partial<Environment> = E>(164- arg1: string,165- ...middleware: Handler<Path, Env>[]166- ): Hono<Env, Path>167- use(arg1: string | Handler<string, E>, ...handlers: Handler<string, E>[]): Hono<E, P> {173+ use<174+ Path extends string = string,175+ Env extends Partial<Environment> = E,176+ Data extends ValidatedData = D177+ >(...middleware: Handler<Path, Env, Data>[]): Hono<Env, Path, Data>178+ use<179+ Path extends string = string,180+ Env extends Partial<Environment> = E,181+ Data extends ValidatedData = D182+ >(arg1: string, ...middleware: Handler<Path, Env, Data>[]): Hono<Env, Path, D>183+ use(arg1: string | Handler<string, E, D>, ...handlers: Handler<string, E, D>[]): Hono<E, P, D> {184 if (typeof arg1 === 'string') {185 this.path = arg1186 } else {187 handlers.unshift(arg1)3 unmodified lines191 })192 return this193 }194 179- onError(handler: ErrorHandler<E>): Hono<E, P> {195+ onError(handler: ErrorHandler<E>): Hono<E, P, D> {196 this.errorHandler = handler197 return this198 }199 184- notFound(handler: NotFoundHandler<E>): Hono<E, P> {200+ notFound(handler: NotFoundHandler<E>): Hono<E, P, D> {201 this.notFoundHandler = handler202 return this203 }204 189- private addRoute(method: string, path: string, handler: Handler<string, E>): void {205+ private addRoute(method: string, path: string, handler: Handler<string, E, D>): void {206 method = method.toUpperCase()207 if (this._tempPath) {208 path = mergePath(this._tempPath, path)209 }210 this.router.add(method, path, handler)195- const r: Route<E> = { path: path, method: method, handler: handler }211+ const r: Route<E, D> = { path: path, method: method, handler: handler }212 this.routes.push(r)213 }214 215 private matchRoute(method: string, path: string) {10 unmodified lines226 227 const result = this.matchRoute(method, path)228 request.paramData = result?.params229 214- const c = new HonoContext<string, E>(request, env, eventOrExecutionCtx, this.notFoundHandler)230+ const c = new HonoContext<string, E, D>(request, env, eventOrExecutionCtx, this.notFoundHandler)231 232 // Do not `compose` if it has only one handler233 if (result && result.handlers.length === 1) {234 const handler = result.handlers[0]50 unmodified linesmodified:deno_dist/request.ts+21 added-1 removed
1 unmodified line2 import type { Cookie } from './utils/cookie.ts'3 import { parse } from './utils/cookie.ts'4 import { getQueryStringFromURL } from './utils/url.ts'5 6+type ValidatedData = Record<string, any>7+8 declare global {7- interface Request<ParamKeyType extends string = string> {9+ interface Request<10+ ParamKeyType extends string = string,11+ Data extends ValidatedData = ValidatedData12+ > {13 paramData?: Record<ParamKeyType, string>14 param: {15 (key: ParamKeyType): string16 (): Record<ParamKeyType, string>23 unmodified lines40 jsonData?: any41 json: {42 (): Promise<any>43 }44+ data: Data45+ valid: {46+ (key: string, value: any): Data47+ (): Data48+ }49 }50 }51 52 export function extendRequestPrototype() {92 unmodified lines145 jsonData = this.jsonData146 }147 return jsonData148 } as InstanceType<typeof Request>['jsonData']149+150+ Request.prototype.valid = function (this: Request, key?: string, value?: any) {151+ if (!this.data) {152+ this.data = {}153+ }154+ if (key && value) {155+ this.data[key] = value156+ }157+ return this.data158+ } as InstanceType<typeof Request>['valid']159 }modified:src/middleware/validator/index.ts+1 added-4 removed
1 import { validatorMiddleware } from './middleware'2-import { validator } from './validator'3-4-const validation = validatorMiddleware<typeof validator>(validator)5-export { validation }2+export { validatorMiddleware as validator }modified:src/middleware/validator/middleware.test.ts+93 added-157 removed
1 import { Hono } from '../../hono'2-import { validation } from './index'2+import { validator } from './index'3 4-describe('Basic', () => {4+describe('Basic - query', () => {5 const app = new Hono()6 // query7 app.get(8 '/foo',9- validation((v) => ({10- query: {11- page: [v.required, v.isNumeric],12- q: v.isAlpha,13- q2: [v.isAlpha, [v.contains, 'abc']],14- q3: [[v.contains, 'abc'], v.isAlpha],15- q4: [16- [v.contains, 'abc'],17- [v.isLength, 1, 10],18- ],19- q5: [v.isEmpty, v.required],20- q6: [[v.contains, 'abc'], v.required, [v.isLength, 5, 100]],21- },9+ validator((v) => ({10+ page: v.query('page').isRequired().isNumeric(),11+ q: v.query('q').isAlpha(),12+ q2: v.query('q2').isAlpha().contains('abc'),13+ q3: v.query('q3').contains('abc').isAlpha(),14+ q4: v.query('q4').contains('abc').isLength(1, 10),15+ q5: v.query('q5').isEmpty().isRequired(),16+ q6: v.query('q6').contains('abc').isRequired().isLength(5, 100),17 })),18 (c) => {19 return c.text('Valid')20 }12 unmodified lines33 const res = await app.request(req)34 expect(res.status).toBe(400)35 expect(await res.text()).toBe(36 [42- 'Invalid Value: the query parameter "page" is invalid - required',43- 'Invalid Value: the query parameter "q5" is invalid - isEmpty',37+ 'Invalid Value: the query parameter "page" is invalid - undefined',38+ 'Invalid Value: the query parameter "q5" is invalid - 123',39 ].join('\n')40 )41 })42+})43 48- // body49- app.post(50- '/bar',51- validation((v) => ({52- body: {53- num: [v.trim, v.isNumeric],54- },55- })),56- (c) => {57- return c.text('Valid')58- }59- )44+describe('Basic - body', () => {45+ const app = new Hono()46 47+ const middleware = validator((v) => ({48+ title: v.body('title').isRequired(),49+ }))50+51+ app.post('/posts', middleware, (c) => {52+ const data = c.req.valid()53+ c.header('x-title', data.title)54+ return c.text('Valid!')55+ })56+57 it('Should return 200 response - body', async () => {62- const formData = new FormData()63- formData.append('num', '1234 ')64- const req = new Request('http://localhost/bar', {58+ const body = new FormData()59+ body.append('title', 'This is Title')60+ const req = new Request('http://localhost/posts', {61 method: 'POST',66- body: formData,62+ body: body,63 })64 const res = await app.request(req)65 expect(res.status).toBe(200)66+ expect(await res.text()).toBe('Valid!')67+ expect(res.headers.get('x-title')).toBe('This is Title')68 })69 70+ it('Should return 400 response - body', async () => {71+ const body = new FormData()72+ const req = new Request('http://localhost/posts', {73+ method: 'POST',74+ body: body,75+ })76+ const res = await app.request(req)77+ expect(res.status).toBe(400)78+ const messages = ['Invalid Value: the request body "title" is invalid - undefined']79+ expect(await res.text()).toBe(messages.join('\n'))80+ })81+})82+83+describe('Basic - header & custom message', () => {84+ const app = new Hono()85 // header & custom error message86 app.get(87 '/',75- validation((v, message) => ({76- header: {77- 'x-header': [v.required, message('CUSTOM MESSAGE')],78- },88+ validator((v) => ({89+ xHeader: v.header('x-header').isRequired().message('CUSTOM MESSAGE'),90 })),91 (c) => {92 return c.text('Valid')93 }3 unmodified lines97 const res = await app.request('http://localhost/')98 expect(res.status).toBe(400)99 expect(await res.text()).toBe('CUSTOM MESSAGE')100 })101+})102 103+describe('Basic - JSON', () => {104+ const app = new Hono()105 // JSON106 app.post(107 '/json',94- validation((v) => ({95- json: {96- 'post.author.name': v.isAlpha,97- },108+ validator((v) => ({109+ name: v.json('post.author.name').isAlpha(),110 })),111 (c) => {112 return c.text('Valid')113 }22 unmodified lines136 // Custom Error handling137 app.get(138 '/custom-error',139 // Custom Error handler should be above.128- validation((v) => ({129- query: {130- userId: v.required,131- },132- done: (result, c) => {133- if (result.hasError) {134- return c.json({ ERROR: true }, 404)135- }136- },137- })),140+ validator(141+ (v) => ({142+ userId: v.query('userId').isRequired(),143+ }),144+ {145+ done: (result, c) => {146+ if (result.hasError) {147+ return c.json({ ERROR: true }, 404)148+ }149+ },150+ }151+ ),152 (c) => {153 c.header('x-valid', 'OK')154 return c.text('Valid')155 }11 unmodified lines167 describe('Custom Validation', () => {168 const app = new Hono()169 170 // Custom Validator157- const passwordValidator = (value: string) => {158- return value.match(/^[a-zA-Z0-9]+$/) ? true : false159- }171 app.post(172 '/custom-validator',162- validation((_, message) => ({163- body: {164- password: [passwordValidator, message('password is wrong')],165- },173+ validator((v) => ({174+ password: v.body('password').addRule((value) => {175+ if (typeof value === 'string') {176+ return value.match(/^[a-zA-Z0-9]+$/) ? true : false177+ }178+ return false179+ }),180 })),181 (c) => {182 return c.text('Valid')183 }8 unmodified lines192 })193 const res = await app.request(req)194 expect(res.status).toBe(200)195 })182-183- it('Should return 400 response - custom validator', async () => {184- const formData = new FormData()185- formData.append('password', 'abcd_+123$')186- const req = new Request('http://localhost/custom-validator', {187- method: 'POST',188- body: formData,189- })190- const res = await app.request(req)191- expect(res.status).toBe(400)192- expect(await res.text()).toBe('password is wrong')193- })196 })197 198 describe('Array parameter', () => {199 const app = new Hono()200 201 // Array parameter202 app.post(203 '/array-parameter',202- validation((v) => ({203- body: {204- value: [v.required, [v.equals, 'valid']],205- },204+ validator((v) => ({205+ foo: v.body('value').isRequired().isEqual('valid'),206 })),207 (c) => {208 return c.text('Valid')209 }27 unmodified lines237 const app = new Hono()238 239 app.post(240 '/body',241- validation((v) => ({242- body: {243- value: v.required,244- },241+ validator((v) => ({242+ value: v.body('value').isRequired(),243 })),244 async (c) => {247- const data = await c.req.parseBody()245+ const data = c.req.valid()246 return c.text((data['value'] as string) || '')247 }248 )249 app.post(250 '/json',253- validation((v) => ({254- json: {255- value: v.required,256- foo: v.isFalsy,257- bar: v.isNotFalsy,258- },251+ validator((v) => ({252+ value: v.json('value').isRequired(),253+ foo: v.json('foo').asBoolean().isFalse(),254+ bar: v.json('bar').asBoolean().isTrue(),255 })),256 async (c) => {261- const json = (await c.req.json()) as { value: string }262- return c.text(json.value)257+ const data = c.req.valid()258+ return c.text(data.value)259 }260 )261 262 it('Should return 200 response - clone body/body', async () => {33 unmodified lines296 // Use `c.set`/`c.get`297 c.set('mail2', data['mail2'])298 await next()299 },304- validation((v, _, c) => ({305- body: {306- mail1: [v.equals, c.get('mail2')],307- },300+ validator((v, c) => ({301+ mail: v.body('mail1').isEqual(c.get('mail2')),302 })),303 (c) => {304 return c.text('Valid')305 }11 unmodified lines317 expect(res.status).toBe(200)318 })319 })320 327-describe('JSON object should not be stringified', () => {328- const app = new Hono()329-330- // JSON331- app.post(332- '/json',333- validation((v) => ({334- json: {335- 'post.author.email': v.required,336- },337- })),338- (c) => {339- return c.text('Valid')340- }341- )342-343- it('Should return 400 response - JSON', async () => {344- const json = {}345- const req = new Request('http://localhost/json', {346- method: 'POST',347- body: JSON.stringify(json),348- })349- const res = await app.request(req)350- expect(res.status).toBe(400)351- })352-})353-321 describe('Remove additional properties', () => {322 const app = new Hono()323 // query324 app.get(325 '/foo',359- validation((v) => ({360- query: {361- q: v.optional,362- page: v.isNumeric,363- },326+ validator((v) => ({327+ q: v.query('q').isOptional(),328+ page: v.query('page').isNumeric(),329 })),330 (c) => {366- return c.json(c.req.query())331+ return c.json(c.req.valid())332 }333 )334 335 it('Should only return validated params', async () => {10 unmodified lines346 347 // JSON348 app.post(349 '/json',385- validation((v) => ({386- json: {387- 'post.author.name': v.isAlpha,388- },350+ validator((v) => ({351+ name: v.json('post.author.name').isAlpha(),352 })),353 async (c) => {391- return c.json(await c.req.json())354+ return c.json(c.req.valid())355 }356 )357 358 it('Should only return validated JSON data', async () => {11 unmodified lines370 body: JSON.stringify(json),371 })372 const res = await app.request(req)373 expect(res.status).toBe(200)411- expect(await res.json()).toEqual({ post: { author: { name: 'abcdef' } } })374+ expect(await res.json()).toEqual({ name: 'abcdef' })375 })413-414- // `removeAdditional` option is false415- app.get(416- '/with-additional',417- validation((v) => ({418- query: {419- q: v.optional,420- page: v.isNumeric,421- },422- removeAdditional: false,423- })),424- (c) => {425- return c.json(c.req.query())426- }427- )428-429- it('Should only return validated params', async () => {430- const searchParams = new URLSearchParams({431- q: 'foobar',432- page: '3',433- foo: 'additional query',434- })435- const req = new Request(`http://localhost/with-additional?${searchParams.toString()}`)436- const res = await app.request(req)437- expect(res.status).toBe(200)438- expect(await res.json()).toEqual({ q: 'foobar', page: '3', foo: 'additional query' })439- })376 })modified:src/middleware/validator/middleware.ts+50 added-192 removed
1 import type { Context } from '../../context'2-import type { MiddlewareHandler } from '../../hono'3-import { JSONPathCopy } from '../../utils/json'2+import type { Environment, Handler } from '../../hono'3+import { Validator } from './validator'4+import type { VBase, VString, VNumber, VBoolean, VObject, ValidateResult } from './validator'5 5-type Param =6- | string7- | number8- | string[]9- | number[]10- | Record<string, string | number>11- | ValidatorMessage12-type Rule = Function | [Function, ...Param[]]13-type Rules = Rule | Rule[]14-type Done = (resultSet: ResultSet, context: Context) => Response | void6+type ValidationFunction<T> = (v: Validator, c: Context) => T7 16-type RuleSet = {17- body: Record<string, Rules>18- json: Record<string, Rules>19- header: Record<string, Rules>20- query: Record<string, Rules>21- done: Done22- removeAdditional: boolean8+type Schema = Record<string, VString | VNumber | VBoolean | VObject>9+type SchemaToProp<T> = {10+ [K in keyof T]: T[K] extends VBase11+ ? T[K]['type'] extends 'number'12+ ? number13+ : T[K]['type'] extends 'boolean'14+ ? boolean15+ : T[K]['type'] extends 'string'16+ ? string17+ : never18+ : never19 }20 21 type ResultSet = {22 hasError: boolean23 messages: string[]24+ results: ValidateResult[]25 }26 30-type Result = {31- rule: Function32- params: Param[]33- message?: string34-}27+type Done = (resultSet: ResultSet, context: Context) => Response | void28 36-export class ValidatorMessage {37- value: string38- constructor(value: string) {39- this.value = value40- }41- getMessage(): string {42- return this.value43- }44-}29+export const validatorMiddleware = <T extends Schema>(30+ validationFunction: ValidationFunction<T>,31+ options?: { done?: Done }32+) => {33+ const v = new Validator()34 46-const message = (value: string): ValidatorMessage => {47- return new ValidatorMessage(value)48-}35+ const handler: Handler<string, Environment, SchemaToProp<T>> = async (c, next) => {36+ const resultSet: ResultSet = {37+ hasError: false,38+ messages: [],39+ results: [],40+ }41 50-export const validatorMiddleware = <Validator>(validator: Validator) => {51- return (52- validatorFunction: (53- validator: Validator,54- message: (value: string) => ValidatorMessage,55- context: Context56- ) => Partial<RuleSet>57- ): MiddlewareHandler => {58- return async (c, next) => {59- const validations = validatorFunction(validator, message, c)42+ const schema = validationFunction(v, c)43 61- const result: ResultSet = {62- hasError: false,63- messages: [],64- }65-66- const v = validations67- v.removeAdditional = v.removeAdditional === undefined ? true : v.removeAdditional // default value is `true`68-69- function validate(rules: Rules, value: string, messageFunc: (ruleName: string) => string) {70- value ||= ''71-72- let count = 073- const results: Result[] = []74-75- const check = (rules: Rules) => {76- if (!Array.isArray(rules)) {77- if (rules instanceof ValidatorMessage) {78- if (results[count - 1]) {79- results[count - 1].message = rules.getMessage()80- }81- } else if (typeof rules === 'function') {82- results[count] = {83- rule: rules,84- params: [],85- }86- count++87- } else {88- results[count - 1].params.push(rules)89- }90- } else {91- if (typeof rules[0] === ('string' || 'number')) {92- // eslint-disable-next-line @typescript-eslint/ban-ts-comment93- // @ts-ignore94- results[count - 1].params.push(rules)95- } else {96- for (const rule of rules) {97- check(rule as Rules)98- }99- }100- }44+ for (const key of Object.keys(schema)) {45+ const validator = schema[key]46+ const result = await validator.validate(c.req)47+ if (result.isValid) {48+ // Set data on request object49+ c.req.valid(key, result.value)50+ } else {51+ resultSet.hasError = true52+ if (result.message !== undefined) {53+ resultSet.messages.push(result.message)54 }102- check(rules)103-104- let invalid = false105- results.map((r) => {106- const ok = r.rule(value, ...r.params)107- if (!invalid && ok === false) {108- invalid = true109- if (r.message) {110- result.messages.push(r.message)111- } else {112- result.messages.push(messageFunc(r.rule.name))113- }114- }115- if (typeof ok !== 'boolean') {116- // ok is sanitized string117- value = ok118- }119- })120-121- if (invalid) {122- result.hasError = true123- return124- }55 }56+ resultSet.results.push(result)57+ }58 127- if (v.query) {128- const query = v.query129- const realQueries = c.req.query()130- const validatedQueries: Record<string, string> = {}131-132- Object.keys(query).map((key) => {133- validatedQueries[key] = realQueries[key] || ''134- const message = (name: string) =>135- `Invalid Value: the query parameter "${key}" is invalid - ${name}`136- validate(query[key], validatedQueries[key], message)137- })138- if (!result.hasError && v.removeAdditional) {139- c.req.queryData = validatedQueries140- }59+ if (options && options.done) {60+ const res = options.done(resultSet, c)61+ if (res) {62+ return res63 }64+ }65 143- if (v.header) {144- const header = v.header145- const realHeaders: Record<string, string> = {}146- for (const key of c.req.headers.keys()) {147- realHeaders[key] = c.req.headers.get(key) || ''148- }149- const validatedHeaders: Record<string, string> = {}150-151- Object.keys(header).map((key) => {152- validatedHeaders[key] = realHeaders[key] || ''153- const message = (name: string) =>154- `Invalid Value: the request header "${key}" is invalid - ${name}`155- validate(header[key], validatedHeaders[key], message)156- })157- if (!result.hasError && v.removeAdditional) {158- c.req.headerData = validatedHeaders159- }160- }161-162- if (v.body) {163- const field = v.body164- const parsedBody = (await c.req.parseBody()) as Record<string, string>165- const kv = { ...parsedBody }166- const validatedKv: Record<string, string> = {}167-168- Object.keys(field).map(async (key) => {169- validatedKv[key] = kv[key] || ''170- const message = (name: string) =>171- `Invalid Value: the request body "${key}" is invalid - ${name}`172- validate(field[key], validatedKv[key], message)173- })174- if (!result.hasError && v.removeAdditional) {175- c.req.bodyData = validatedKv176- }177- }178-179- if (v.json) {180- const field = v.json181- let json: object182- try {183- json = await c.req.json()184- } catch {185- json = {}186- }187- const validatedJson: object = new (json as any).constructor()188-189- Object.keys(field).map(async (key) => {190- const value = JSONPathCopy(json, validatedJson, key)191- const message = (name: string) =>192- `Invalid Value: the JSON body "${key}" is invalid - ${name}`193- validate(field[key], value, message)194- })195-196- if (!result.hasError && v.removeAdditional) {197- c.req.jsonData = validatedJson198- }199- }200-201- if (v.done) {202- const res = v.done(result, c)203- if (res) {204- return res205- }206- }207-208- if (result.hasError) {209- return c.text(result.messages.join('\n'), 400)66+ if (resultSet.hasError) {67+ return c.text(resultSet.messages.join('\n'), 400)210- }211- await next()68 }69+ await next()70 }71+ return handler72 }added:src/middleware/validator/rule.test.ts+55 added
1+import { rule } from './rule'2+3+describe('Rules', () => {4+ // string5+ test('isEmpty', () => {6+ expect(rule.isEmpty('')).toBeTruthy()7+ expect(rule.isEmpty('abcdef')).toBeFalsy()8+ expect(rule.isEmpty('')).toBeTruthy()9+ expect(rule.isEmpty(' ')).toBeFalsy()10+ expect(rule.isEmpty(' ', { ignore_whitespace: true })).toBeTruthy()11+ })12+ test('isLength', () => {13+ expect(rule.isLength('abcde', { min: 1, max: 10 })).toBeTruthy()14+ expect(rule.isLength('abcde', { min: 1, max: 4 })).toBeFalsy()15+ expect(rule.isLength('abcde', { max: 10 })).toBeTruthy()16+ expect(rule.isLength('abcde', { max: 4 })).toBeFalsy()17+ expect(rule.isLength('abcde', { min: 10 })).toBeFalsy()18+ expect(rule.isLength('abcde', { min: 4 })).toBeTruthy()19+ expect(rule.isLength('abcde', 1, 10)).toBeTruthy()20+ expect(rule.isLength('abcde', 1, 4)).toBeFalsy()21+ })22+ test('isAlpha', () => {23+ expect(rule.isAlpha('abcdef')).toBeTruthy()24+ expect(rule.isAlpha('abc123')).toBeFalsy()25+ })26+ test('isNumeric', () => {27+ expect(rule.isNumeric('01234')).toBeTruthy()28+ expect(rule.isNumeric('012abc')).toBeFalsy()29+ })30+ test('contains', () => {31+ expect(rule.contains('barfoobaz', 'foo')).toBeTruthy()32+ expect(rule.contains('barfoobaz', 'fooo')).toBeFalsy()33+ expect(rule.contains('barfoobaz', 'Foo')).toBeFalsy()34+ expect(rule.contains('barfoobaz', 'Foo', { ignoreCase: true })).toBeTruthy()35+ })36+ test('isIn', () => {37+ expect(rule.isIn('foo', ['foo', 'bar'])).toBeTruthy()38+ expect(rule.isIn('foo', ['zzz', 'yyy'])).toBeFalsy()39+ })40+ test('match', () => {41+ expect(rule.match('abcdef', /def$/)).toBeTruthy()42+ expect(rule.match('abcdef', /^def$/)).toBeFalsy()43+ })44+ // number45+ test('isGte', () => {46+ expect(rule.isGte(20, 10)).toBeTruthy()47+ expect(rule.isGte(10, 20)).toBeFalsy()48+ expect(rule.isGte(10, 10)).toBeTruthy()49+ })50+ test('isLte', () => {51+ expect(rule.isLte(10, 20)).toBeTruthy()52+ expect(rule.isLte(20, 10)).toBeFalsy()53+ expect(rule.isLte(10, 10)).toBeTruthy()54+ })55+})added:src/middleware/validator/rule.ts+83 added
1+// Some validation rules is are based on Validator.js2+// Validator.js3+// License (MIT)4+// Copyright (c) 2018 Chris O'Hara <cohara87@gmail.com>5+// https://github.com/validatorjs/validator.js6+7+export const rule = {8+ // string9+ isEmpty(10+ value: string,11+ options: {12+ ignore_whitespace: boolean13+ } = { ignore_whitespace: false }14+ ): boolean {15+ return (options.ignore_whitespace ? value.trim().length : value.length) === 016+ },17+18+ isLength: (19+ value: string,20+ options: Partial<{ min: number; max: number }> | number,21+ arg2?: number22+ ) => {23+ let min: number24+ let max: number | undefined25+ if (typeof options === 'object') {26+ min = options.min || 027+ max = options.max28+ } else {29+ // backwards compatibility: isLength(str, min [, max])30+ min = options || 031+ max = arg232+ }33+ const presentationSequences = value.match(/(\uFE0F|\uFE0E)/g) || []34+ const surrogatePairs = value.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g) || []35+ const len = value.length - presentationSequences.length - surrogatePairs.length36+ return len >= min && (typeof max === 'undefined' || len <= max)37+ },38+39+ isAlpha: (value: string): boolean => {40+ return /^[A-Z]+$/i.test(value)41+ },42+43+ isNumeric: (value: string): boolean => {44+ return /^[0-9]+$/.test(value)45+ },46+47+ contains: (48+ value: string,49+ elem: string,50+ options: Partial<{ ignoreCase: boolean; minOccurrences: number }> = {51+ ignoreCase: false,52+ minOccurrences: 1,53+ }54+ ): boolean => {55+ options.ignoreCase ||= false56+ options.minOccurrences ||= 157+ if (options.ignoreCase) {58+ return value.toLowerCase().split(elem.toLowerCase()).length > options.minOccurrences59+ }60+ return value.split(elem).length > options.minOccurrences61+ },62+63+ isIn: (value: string, options: string[]): boolean => {64+ if (typeof options === 'object') {65+ for (const elem of options) {66+ if (elem === value) return true67+ }68+ }69+ return false70+ },71+72+ match: (value: string, regExp: RegExp): boolean => {73+ return regExp.test(value)74+ },75+76+ // number77+ isGte: (value: number, min: number) => min <= value,78+ isLte: (value: number, max: number) => value <= max,79+80+ // boolean81+ isTrue: (value: boolean) => value === true,82+ isFalse: (value: boolean) => value === false,83+}added:src/middleware/validator/sanitizer.test.ts+7 added
1+import { sanitizer } from './sanitizer'2+3+describe('Sanitizers', () => {4+ test('trim', () => {5+ expect(sanitizer.trim(' abc ')).toBe('abc')6+ })7+})added:src/middleware/validator/sanitizer.ts+3 added
1+export const sanitizer = {2+ trim: (value: string) => value.trim(),3+}modified:src/middleware/validator/validator.test.ts+130 added-80 removed
1+import { extendRequestPrototype } from '../../request'1-import { validator } from './validator'2+import { Validator } from './validator'3 3-describe('Test the validator rules', () => {4- test('required', () => {5- expect(validator.required('a')).toBeTruthy()6- expect(validator.required(0)).toBeTruthy()7- expect(validator.required(undefined)).toBeFalsy()8- expect(validator.required('')).toBeFalsy()4+extendRequestPrototype()5+6+describe('Basic - query', () => {7+ const v = new Validator()8+9+ const req = new Request('http://localhost/?q=foo&page=3')10+11+ it('Should be valid - page', async () => {12+ const validator = v.query('page').trim().isNumeric()13+ expect(validator.type).toBe('string')14+ const res = await validator.validate(req)15+ expect(res.isValid).toBe(true)16+ expect(res.message).toBeUndefined()17 })18 11- test('optional', () => {12- expect(validator.optional).toBeTruthy()19+ it('Should be invalid - q', async () => {20+ const validator = v.query('q').isRequired().asNumber()21+ expect(validator.type).toBe('number')22+ const res = await validator.validate(req)23+ expect(res.isValid).toBe(false)24+ const messages = ['Invalid Value: the query parameter "q" is invalid - foo']25+ expect(res.message).toBe(messages.join('\n'))26 })27 15- test('isBoolean', () => {16- expect(validator.isBoolean(true)).toBeTruthy()17- expect(validator.isBoolean('abc')).toBeFalsy()28+ it('Should be invalid - q2', async () => {29+ const validator = v.query('q2').isRequired()30+ const res = await validator.validate(req)31+ expect(res.isValid).toBe(false)32+ const messages = ['Invalid Value: the query parameter "q2" is invalid - undefined']33+ expect(res.message).toBe(messages.join('\n'))34 })35+})36 20- test('isNumber', () => {21- expect(validator.isNumber(123)).toBeTruthy()22- expect(validator.isNumber('123')).toBeFalsy()37+describe('Basic - header', () => {38+ const v = new Validator()39+40+ const req = new Request('http://localhost/', {41+ headers: {42+ 'x-message': 'hello world!',43+ 'x-number': '12345',44+ },45 })46 25- test('isFalsy', () => {26- expect(validator.isFalsy(undefined)).toBeTruthy()27- expect(validator.isFalsy(0)).toBeTruthy()28- expect(validator.isFalsy('')).toBeTruthy()29- expect(validator.isFalsy(null)).toBeTruthy()47+ it('Should be valid - x-message', async () => {48+ const validator = v.header('x-message').isRequired().contains('Hello', { ignoreCase: true })49+ const res = await validator.validate(req)50+ expect(res.isValid).toBe(true)51+ expect(res.message).toBeUndefined()52 })53 32- test('isNotFalsy', () => {33- expect(validator.isNotFalsy('abc')).toBeTruthy()34- expect(validator.isNotFalsy(123)).toBeTruthy()35- expect(validator.isNotFalsy(true)).toBeTruthy()54+ it('Should be invalid - x-number', async () => {55+ const validator = v.header('x-number').isEqual(12345)56+ const res = await validator.validate(req)57+ expect(res.isValid).toBe(false)58+ const messages = ['Invalid Value: the request header "x-number" is invalid - 12345']59+ expect(res.message).toBe(messages.join('\n'))60 })61+})62 38- test('isAlpha', () => {39- expect(validator.isAlpha('abcdef')).toBeTruthy()40- expect(validator.isAlpha('abc123')).toBeFalsy()41- // eslint-disable-next-line @typescript-eslint/ban-ts-comment42- // @ts-ignore43- expect(validator.isAlpha(123)).toBeFalsy()63+describe('Basic - body', () => {64+ const v = new Validator()65+66+ const body = new FormData()67+ body.append('title', ' abcdef ')68+ body.append('title2', 'abcdef')69+ const req = new Request('http://localhost/', {70+ method: 'POST',71+ body: body,72 })73 46- test('isNumeric', () => {47- expect(validator.isNumeric('01234')).toBeTruthy()48- expect(validator.isNumeric('012abc')).toBeFalsy()49- // eslint-disable-next-line @typescript-eslint/ban-ts-comment50- // @ts-ignore51- expect(validator.isAlpha(123)).toBeFalsy()74+ it('Should be valid - title', async () => {75+ const validator = v.body('title').trim().isLength({ max: 10 }).isRequired()76+ const res = await validator.validate(req)77+ expect(res.isValid).toBe(true)78+ expect(res.message).toBeUndefined()79 })80 54- test('isEmpty', () => {55- expect(validator.isEmpty('')).toBeTruthy()56- expect(validator.isEmpty(' ')).toBeFalsy()57- expect(validator.isEmpty(' ', { ignore_whitespace: true })).toBeTruthy()58- expect(validator.isEmpty('abc')).toBeFalsy()59- // eslint-disable-next-line @typescript-eslint/ban-ts-comment60- // @ts-ignore61- expect(validator.isEmpty(123, { ignore_whitespace: true })).toBeFalsy()81+ it('Should be invalid - title2', async () => {82+ const validator = v.body('title2').isLength({ max: 5 })83+ const res = await validator.validate(req)84+ expect(res.isValid).toBe(false)85+ const messages = ['Invalid Value: the request body "title2" is invalid - abcdef']86+ expect(res.message).toBe(messages.join('\n'))87 })88+})89 64- test('isLength', () => {65- expect(validator.isLength('abcde', { min: 1, max: 10 })).toBeTruthy()66- expect(validator.isLength('abcde', { min: 1, max: 4 })).toBeFalsy()67- expect(validator.isLength('abcde', { max: 10 })).toBeTruthy()68- expect(validator.isLength('abcde', { max: 4 })).toBeFalsy()69- expect(validator.isLength('abcde', { min: 10 })).toBeFalsy()70- expect(validator.isLength('abcde', { min: 4 })).toBeTruthy()71- expect(validator.isLength('abcde', 1, 10)).toBeTruthy()72- expect(validator.isLength('abcde', 1, 4)).toBeFalsy()73- // eslint-disable-next-line @typescript-eslint/ban-ts-comment74- // @ts-ignore75- expect(validator.isLength(123, { max: 10 })).toBeFalsy()90+describe('Basic - JSON', () => {91+ const v = new Validator()92+93+ const post = {94+ id: 1234,95+ title: 'This is title',96+ author: {97+ name: 'Superman',98+ age: 20,99+ },100+ }101+102+ const req = new Request('http://localhost/', {103+ method: 'POST',104+ body: JSON.stringify(post),105 })106 78- test('contains', () => {79- expect(validator.contains('barfoobaz', 'foo')).toBeTruthy()80- expect(validator.contains('barfoobaz', 'fooo')).toBeFalsy()81- expect(validator.contains('barfoobaz', 'Foo')).toBeFalsy()82- expect(validator.contains('barfoobaz', 'Foo', { ignoreCase: true })).toBeTruthy()83- // eslint-disable-next-line @typescript-eslint/ban-ts-comment84- // @ts-ignore85- expect(validator.contains(12345, 123)).toBeFalsy()107+ it('Should be valid - id', async () => {108+ const validator = v.json('id').asNumber().isEqual(1234)109+ const res = await validator.validate(req)110+ expect(res.isValid).toBe(true)111+ expect(res.message).toBeUndefined()112 })113 88- test('equals', () => {89- expect(validator.equals('foo', 'foo')).toBeTruthy()90- expect(validator.equals('foo', 'bar')).toBeFalsy()91- expect(validator.equals(123, 123)).toBeTruthy()92- expect(validator.equals(123, '123')).toBeFalsy()114+ it('Should be valid - author.name', async () => {115+ const validator = v.json('author.name').isIn(['Ultra man', 'Superman'])116+ const res = await validator.validate(req)117+ expect(res.isValid).toBe(true)118+ expect(res.message).toBeUndefined()119 })120 95- test('isIn', () => {96- expect(validator.isIn('foo', ['foo', 'bar'])).toBeTruthy()97- expect(validator.isIn('foo', ['zzz', 'yyy'])).toBeFalsy()98- // eslint-disable-next-line @typescript-eslint/ban-ts-comment99- // @ts-ignore100- expect(validator.isIn(123, [123, 456])).toBeFalsy()121+ it('Should be invalid - author.age', async () => {122+ const validator = v.json('author.age').asNumber().isLte(10)123+ const res = await validator.validate(req)124+ expect(res.isValid).toBe(false)125+ const messages = ['Invalid Value: the JSON body "author.age" is invalid - 20']126+ expect(res.message).toBe(messages.join('\n'))127 })128+})129 103- test('trim', () => {104- expect(validator.trim(' foo ')).toBe('foo')105- // eslint-disable-next-line @typescript-eslint/ban-ts-comment106- // @ts-ignore107- expect(validator.trim(123)).toBe(123)130+describe('Handling types error', () => {131+ const v = new Validator()132+133+ const post = {134+ id: '1234',135+ title: 'This is title',136+ published: 'true',137+ }138+139+ const req = new Request('http://localhost/', {140+ method: 'POST',141+ body: JSON.stringify(post),142 })143+144+ it('Should be invalid - "1234" is not number', async () => {145+ const validator = v.json('id').asNumber().isEqual(1234)146+ const res = await validator.validate(req)147+ expect(res.isValid).toBe(false)148+ const messages = ['Invalid Value: the JSON body "id" is invalid - 1234']149+ expect(res.message).toBe(messages.join('\n'))150+ })151+152+ it('Should be invalid - "true" is not boolean', async () => {153+ const validator = v.json('published').asBoolean()154+ const res = await validator.validate(req)155+ expect(res.isValid).toBe(false)156+ const messages = ['Invalid Value: the JSON body "published" is invalid - true']157+ expect(res.message).toBe(messages.join('\n'))158+ })159 })modified:src/middleware/validator/validator.ts+224 added-82 removed
1-// Some validation rules is are based on Validator.js2-// Validator.js3-// License (MIT)4-// Copyright (c) 2018 Chris O'Hara <cohara87@gmail.com>5-// https://github.com/validatorjs/validator.js1+import { JSONPath } from '../../utils/json'2+import { rule } from './rule'3+import { sanitizer } from './sanitizer'4 7-const isString = (value: any) => {8- return typeof value === 'string'5+type Target = 'query' | 'header' | 'body' | 'json'6+type Type = string | number | boolean | object | undefined7+type Rule = (value: Type) => boolean8+type Sanitizer = (value: Type) => Type9+10+export class Validator {11+ query = (key: string): VString => new VString({ target: 'query', key: key })12+ header = (key: string): VString => new VString({ target: 'header', key: key })13+ body = (key: string): VString => new VString({ target: 'body', key: key })14+ json = (key: string): VString => new VString({ target: 'json', key: key })15 }16 11-export const validator = {12- required(value: unknown): boolean {13- if (value === undefined) return false14- if (isString(value) && value === '') return false15- return true16- },17+export type ValidateResult = {18+ isValid: boolean19+ message: string | undefined20+ target: Target21+ key: string22+ value: Type23+}24 18- optional(): boolean {19- return true20- },25+type VOptions = {26+ target: Target27+ key: string28+ type?: 'string' | 'number' | 'boolean' | 'object'29+}30 22- isBoolean(value: unknown): boolean {23- return typeof value === 'boolean'24- },31+export abstract class VBase {32+ type: 'string' | 'number' | 'boolean' | 'object'33+ target: Target34+ key: string35+ rules: Rule[]36+ sanitizers: Sanitizer[]37+ private _message: string | undefined38 26- isNumber(value: unknown): boolean {27- return typeof value === 'number'28- },39+ constructor(options: VOptions) {40+ this.target = options.target41+ this.key = options.key42+ this.type = options.type || 'string'43+ this.rules = []44+ this.sanitizers = []45+ }46 30- isFalsy(value: unknown): boolean {31- return !value32- },47+ addRule = (rule: Rule) => {48+ this.rules.push(rule)49+ return this50+ }51 34- isNotFalsy(value: unknown): boolean {35- return !!value36- },52+ addSanitizer = (sanitizer: Sanitizer) => {53+ this.sanitizers.push(sanitizer)54+ return this55+ }56 38- isAlpha(value: string): boolean {39- return isString(value) && value.match(/^[A-Z]+$/i) ? true : false40- },57+ isRequired = () => {58+ return this.addRule((value: unknown) => {59+ if (value) return true60+ return false61+ })62+ }63 42- isNumeric(value: string): boolean {43- return isString(value) && value.match(/^[0-9]+$/) ? true : false44- },64+ isOptional = () => {65+ return this.addRule(() => true)66+ }67 46- isEmpty(47- value: string,68+ isEqual = (comparison: unknown) => {69+ return this.addRule((value: unknown) => {70+ return value === comparison71+ })72+ }73+74+ asNumber = () => {75+ const newVNumber = new VNumber(this)76+ return newVNumber77+ }78+79+ asBoolean = () => {80+ const newVBoolean = new VBoolean(this)81+ return newVBoolean82+ }83+84+ asObject = () => {85+ const newVObject = new VObject(this)86+ return newVObject87+ }88+89+ message(value: string) {90+ this._message = value91+ return this92+ }93+94+ validate = async (req: Request): Promise<ValidateResult> => {95+ const result: ValidateResult = {96+ isValid: true,97+ message: undefined,98+ target: this.target,99+ key: this.key,100+ value: undefined,101+ }102+103+ let value: Type = undefined104+ if (this.target === 'query') {105+ value = req.query(this.key)106+ }107+ if (this.target === 'header') {108+ value = req.header(this.key)109+ }110+ if (this.target === 'body') {111+ const body = await req.parseBody()112+ value = body[this.key]113+ }114+ if (this.target === 'json') {115+ const obj = await req.json()116+ value = JSONPath(obj, this.key)117+ }118+119+ result.value = value120+ result.isValid = this.validateValue(value)121+122+ if (result.isValid == false) {123+ if (this._message) {124+ result.message = this._message125+ } else {126+ switch (this.target) {127+ case 'query':128+ result.message = `Invalid Value: the query parameter "${this.key}" is invalid - ${value}`129+ break130+ case 'header':131+ result.message = `Invalid Value: the request header "${this.key}" is invalid - ${value}`132+ break133+ case 'body':134+ result.message = `Invalid Value: the request body "${this.key}" is invalid - ${value}`135+ break136+ case 'json':137+ result.message = `Invalid Value: the JSON body "${this.key}" is invalid - ${value}`138+ break139+ }140+ }141+ }142+ return result143+ }144+145+ private validateValue = (value: Type): boolean => {146+ // Check type147+ if (typeof value !== this.type) {148+ return false149+ }150+151+ // Sanitize152+ for (const sanitizer of this.sanitizers) {153+ value = sanitizer(value)154+ }155+156+ for (const rule of this.rules) {157+ if (!rule(value)) {158+ return false159+ }160+ }161+ return true162+ }163+}164+165+export class VString extends VBase {166+ constructor(options: VOptions) {167+ super(options)168+ this.type = 'string'169+ }170+171+ isEmpty = (172 options: {173 ignore_whitespace: boolean174 } = { ignore_whitespace: false }51- ): boolean {52- return (isString(value) && options.ignore_whitespace ? value.trim().length : value.length) === 053- },175+ ) => {176+ return this.addRule((value) => rule.isEmpty(value as string, options))177+ }178 55- isLength(value: string, options: Partial<{ min: number; max: number }> | number, arg2?: number) {56- if (!isString(value)) return false57- let min: number58- let max: number | undefined59- if (typeof options === 'object') {60- min = options.min || 061- max = options.max62- } else {63- // backwards compatibility: isLength(str, min [, max])64- min = options || 065- max = arg266- }67- const presentationSequences = value.match(/(\uFE0F|\uFE0E)/g) || []68- const surrogatePairs = value.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g) || []69- const len = value.length - presentationSequences.length - surrogatePairs.length70- return len >= min && (typeof max === 'undefined' || len <= max)71- },179+ isLength = (options: Partial<{ min: number; max: number }> | number, arg2?: number) => {180+ return this.addRule((value) => rule.isLength(value as string, options, arg2))181+ }182 73- contains(74- value: string,183+ isAlpha = () => {184+ return this.addRule((value) => rule.isAlpha(value as string))185+ }186+187+ isNumeric = () => {188+ return this.addRule((value) => rule.isNumeric(value as string))189+ }190+191+ contains = (192 elem: string,193 options: Partial<{ ignoreCase: boolean; minOccurrences: number }> = {194 ignoreCase: false,195 minOccurrences: 1,196 }80- ): boolean {81- options.ignoreCase ||= false82- options.minOccurrences ||= 183- if (!isString(value) || !isString(elem)) return false84- if (options.ignoreCase) {85- return value.toLowerCase().split(elem.toLowerCase()).length > options.minOccurrences86- }87- return value.split(elem).length > options.minOccurrences88- },197+ ) => {198+ return this.addRule((value) => rule.contains(value as string, elem, options))199+ }200 90- equals(value: unknown, comparison: unknown): boolean {91- return value === comparison92- },201+ isIn = (options: string[]) => {202+ return this.addRule((value) => rule.isIn(value as string, options))203+ }204 94- isIn(value: string, options: string[]): boolean {95- if (!isString(value)) return false96- if (typeof options === 'object') {97- for (const elem of options) {98- if (elem === value) return true99- }100- }101- return false102- },205+ match = (regExp: RegExp) => {206+ return this.addRule((value) => rule.match(value as string, regExp))207+ }208 104- trim(value: string): string {105- return isString(value) ? value.trim() : value106- },209+ trim = () => {210+ return this.addSanitizer((value) => sanitizer.trim(value as string))211+ }212 }213+214+export class VNumber extends VBase {215+ constructor(options: VOptions) {216+ super(options)217+ this.type = 'number'218+ }219+220+ isGte = (min: number) => {221+ return this.addRule((value) => rule.isGte(value as number, min))222+ }223+224+ isLte = (min: number) => {225+ return this.addRule((value) => rule.isLte(value as number, min))226+ }227+}228+229+export class VBoolean extends VBase {230+ constructor(options: VOptions) {231+ super(options)232+ this.type = 'boolean'233+ }234+235+ isTrue = () => {236+ return this.addRule((value) => rule.isTrue(value as boolean))237+ }238+239+ isFalse = () => {240+ return this.addRule((value) => rule.isFalse(value as boolean))241+ }242+}243+244+export class VObject extends VBase {245+ constructor(options: VOptions) {246+ super(options)247+ this.type = 'object'248+ }249+}modified:src/utils/json.test.ts+14 added-56 removed
1-import { JSONPathCopy } from './json'1+import { JSONPath } from './json'2 3-describe('JSONPathCopy', () => {3+describe('JSONPath', () => {4 const data = {5 post: {6 title: 'Hello',7 author: {4 unmodified lines12 },13 }14 15 it('Should return the string or number pointed by JSON Path', () => {16- const dst = {}17-18- expect(JSONPathCopy(data, dst, 'post.title')).toBe('Hello')19- expect(dst).toEqual({ post: { title: 'Hello' } })20- expect(JSONPathCopy(data, dst, 'post.author.name')).toBe('Superman')21- expect(dst).toEqual({ post: { title: 'Hello', author: { name: 'Superman' } } })22- expect(JSONPathCopy(data, dst, 'post.author.age')).toBe(20)23- expect(dst).toEqual({ post: { title: 'Hello', author: { name: 'Superman', age: 20 } } })24- expect(JSONPathCopy(data, dst, 'post.tags.0')).toBe('foo')25- expect(dst).toEqual({26- post: {27- title: 'Hello',28- author: { name: 'Superman', age: 20 },29- tags: ['foo'],30- },31- })32- expect(JSONPathCopy(data, dst, 'post.tags.1')).toBe('bar')33- expect(dst).toEqual({34- post: {35- title: 'Hello',36- author: { name: 'Superman', age: 20 },37- tags: ['foo', 'bar'],38- },39- })40- expect(JSONPathCopy(data, dst, 'post.tags.2.framework')).toBe('Hono')41- expect(dst).toEqual({42- post: {43- title: 'Hello',44- author: { name: 'Superman', age: 20 },45- tags: ['foo', 'bar', { framework: 'Hono' }],46- },47- })16+ expect(JSONPath(data, 'post.title')).toBe('Hello')17+ expect(JSONPath(data, 'post.author.name')).toBe('Superman')18+ expect(JSONPath(data, 'post.author.age')).toBe(20)19+ expect(JSONPath(data, 'post.tags.0')).toBe('foo')20+ expect(JSONPath(data, 'post.tags.1')).toBe('bar')21+ expect(JSONPath(data, 'post.tags.2.framework')).toBe('Hono')22 })23 24 it('Should return undefined', () => {51- const dst = {}52-53- expect(JSONPathCopy(data, dst, 'post.foo')).toBe(undefined)54- expect(JSONPathCopy(data, dst, 'post.author.foo')).toBe(undefined)55- expect(JSONPathCopy(data, dst, 'post.tags.3')).toBe(undefined)25+ expect(JSONPath(data, 'post.foo')).toBe(undefined)26+ expect(JSONPath(data, 'post.author.foo')).toBe(undefined)27+ expect(JSONPath(data, 'post.tags.3')).toBe(undefined)56- expect(dst).toEqual({ post: { author: {}, tags: [] } })28 })29 30 it('Should return objects pointed by JSON Path', () => {60- const [dstPost, dstPostAuthor, dstPostTags] = [{}, {}, {}]61-62- expect(typeof JSONPathCopy(data, dstPost, 'post')).toBe('object')63- expect(dstPost).toEqual({64- post: {65- title: 'Hello',66- author: { name: 'Superman', age: 20 },67- tags: ['foo', 'bar', { framework: 'Hono' }],68- },69- })70- expect(JSONPathCopy(data, dstPostAuthor, 'post.author')).toEqual({ name: 'Superman', age: 20 })71- expect(dstPostAuthor).toEqual({ post: { author: { name: 'Superman', age: 20 } } })72- expect(JSONPathCopy(data, dstPostTags, 'post.tags').length).toBe(3)73- expect(dstPostTags).toEqual({74- post: { tags: ['foo', 'bar', { framework: 'Hono' }] },75- })31+ expect(typeof JSONPath(data, 'post')).toBe('object')32+ expect(JSONPath(data, 'post.author')).toEqual({ name: 'Superman', age: 20 })33+ expect(JSONPath(data, 'post.tags').length).toBe(3)34 })35 })modified:src/utils/json.ts+7 added-23 removed
1-export const JSONPathCopy = (src: object, dst: object, path: string) => {1+export const JSONPath = (data: object, path: string) => {2 // eslint-disable-next-line @typescript-eslint/no-explicit-any3- let srcVal: any = src4- // eslint-disable-next-line @typescript-eslint/no-explicit-any5- let dstVal: any = dst3+ let val: any = data4 const parts = path.split('.')5 const length = parts.length8- for (let i = 0; i < length && srcVal !== undefined; i++) {6+ for (let i = 0; i < length && val !== undefined; i++) {7 const p = parts[i]8 if (p !== '') {11- if (typeof srcVal === 'object') {12- if (typeof srcVal[p] === 'object') {13- dstVal[p] ||= new srcVal[p].constructor()14- }15- else if (p in srcVal) {16- dstVal[p] = srcVal[p]17- }18- else {19- return undefined20- }21- srcVal = srcVal[p]22- dstVal = dstVal[p]9+ if (typeof val === 'object') {10+ val = val[p]11 } else {24- return undefined12+ val = undefined13 }14 }15 }28-29- if (typeof srcVal === 'object') {30- Object.assign(dstVal, srcVal)31- }32- return srcVal16+ return val17 }modified:src/context.ts+16 added-8 removed
1-import type { Environment, NotFoundHandler, ContextVariableMap, Bindings } from './hono'1+import type {2+ Environment,3+ NotFoundHandler,4+ ContextVariableMap,5+ Bindings,6+ ValidatedData,7+} from './hono'8 import { defaultNotFoundMessage } from './hono'9 import type { CookieOptions } from './utils/cookie'10 import { serialize } from './utils/cookie'11 import type { StatusCode } from './utils/http-status'3 unmodified lines15 export type Data = string | ArrayBuffer | ReadableStream16 17 export interface Context<18 RequestParamKeyType extends string = string,13- E extends Partial<Environment> = any19+ E extends Partial<Environment> = any,20+ D extends ValidatedData = ValidatedData21 > {15- req: Request<RequestParamKeyType>22+ req: Request<RequestParamKeyType, D>23 env: E['Bindings']24 event: FetchEvent25 executionCtx: ExecutionContext26 finalized: boolean24 unmodified lines51 }52 53 export class HonoContext<54 RequestParamKeyType extends string = string,48- E extends Partial<Environment> = Environment49-> implements Context<RequestParamKeyType, E>55+ E extends Partial<Environment> = Environment,56+ D extends ValidatedData = ValidatedData57+> implements Context<RequestParamKeyType, E, D>58 {51- req: Request<RequestParamKeyType>59+ req: Request<RequestParamKeyType, D>60 env: E['Bindings']61 finalized: boolean62 63 _status: StatusCode = 2005 unmodified lines69 private _res: Response | undefined70 private notFoundHandler: NotFoundHandler<E>71 72 constructor(65- req: Request,73+ req: Request<RequestParamKeyType>,74 env: E['Bindings'] | undefined = undefined,75 executionCtx: FetchEvent | ExecutionContext | undefined = undefined,76 notFoundHandler: NotFoundHandler<E> = () => new Response()77 ) {78 this._executionCtx = executionCtx71- this.req = req79+ this.req = req as Request<RequestParamKeyType, D>80 this.env = env || ({} as Bindings)81 82 this.notFoundHandler = notFoundHandler83 this.finalized = false117 unmodified linesmodified:src/hono.ts+51 added-35 removed
18 unmodified lines19 Bindings: Bindings20 Variables: Variables21 }22 23+export type ValidatedData = Record<string, any> // For validated data24+25 export type Handler<26 RequestParamKeyType extends string = string,25- E extends Partial<Environment> = Environment27+ E extends Partial<Environment> = Environment,28+ D extends ValidatedData = ValidatedData29 > = (27- c: Context<RequestParamKeyType, E>,30+ c: Context<RequestParamKeyType, E, D>,31 next: Next32 ) => Response | Promise<Response> | Promise<void> | Promise<Response | undefined>33 34 export type MiddlewareHandler = <E extends Partial<Environment> = Environment>(27 unmodified lines62 ? ParamKey<Component> | ParamKeys<Rest>63 : ParamKey<Path>64 65 interface HandlerInterface<63- T extends string = string,64- E extends Partial<Environment> = Environment,65- U = Hono<E, T>66+ T extends string,67+ E extends Partial<Environment>,68+ D extends ValidatedData,69+ U = Hono<E, T, D>70 > {71 // app.get(handler...)68- <Path extends string, Env extends Partial<Environment> = E>(69- ...handlers: Handler<ParamKeys<Path> extends never ? string : ParamKeys<Path>, Env>[]72+ <Path extends string, Env extends Partial<Environment>, Data extends ValidatedData = D>(73+ ...handlers: Handler<ParamKeys<Path> extends never ? string : ParamKeys<Path>, Env, Data>[]74 ): U71- (...handlers: Handler<string, E>[]): U75+ (...handlers: Handler<string, E, D>[]): U76 // app.get('/', handler, handler...)73- <Path extends string, Env extends Partial<Environment> = E>(77+ <Path extends string, Env extends Partial<Environment> = E, Data extends ValidatedData = D>(78 path: Path,75- ...handlers: Handler<ParamKeys<Path> extends never ? string : ParamKeys<Path>, Env>[]79+ ...handlers: Handler<ParamKeys<Path> extends never ? string : ParamKeys<Path>, Env, Data>[]80 ): U77- (path: string, ...handlers: Handler<string, E>[]): U81+ (path: string, ...handlers: Handler<string, E, D>[]): U82 }83 84 type Methods = typeof METHODS[number] | typeof METHOD_NAME_ALL_LOWERCASE85 86 function defineDynamicClass(): {83- new <E extends Partial<Environment> = Environment, T extends string = string, U = Hono>(): {84- [K in Methods]: HandlerInterface<T, E, U>87+ new <88+ E extends Partial<Environment> = Environment,89+ T extends string = string,90+ D extends ValidatedData = ValidatedData,91+ U = Hono<E, T, D>92+ >(): {93+ [K in Methods]: HandlerInterface<T, E, D, U>94 }95 } {96 return class {} as any97 }98 90-interface Route<E extends Partial<Environment> = Environment> {99+interface Route<100+ E extends Partial<Environment> = Environment,101+ D extends ValidatedData = ValidatedData102+> {103 path: string104 method: string93- handler: Handler<string, E>105+ handler: Handler<string, E, D>106 }107 108 export class Hono<109 E extends Partial<Environment> = Environment,98- P extends string = '/'99-> extends defineDynamicClass()<E, P, Hono<E, P>> {100- readonly router: Router<Handler<string, E>> = new SmartRouter({110+ P extends string = '/',111+ D extends ValidatedData = ValidatedData112+> extends defineDynamicClass()<E, P, D, Hono<E, P, D>> {113+ readonly router: Router<Handler<string, E, D>> = new SmartRouter({114 routers: [new StaticRouter(), new RegExpRouter(), new TrieRouter()],115 })116 readonly strict: boolean = true // strict routing - default is true117 private _tempPath: string = ''118 private path: string = '/'119 107- routes: Route<E>[] = []120+ routes: Route<E, D>[] = []121 122 constructor(init: Partial<Pick<Hono, 'router' | 'strict'>> = {}) {123 super()124 1 unmodified line126 127 const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE]128 allMethods.map((method) => {129 this[method] = <Path extends string = ''>(117- args1: Path | Handler<ParamKeys<Path>, E>,118- ...args: [Handler<ParamKeys<Path>, E>]130+ args1: Path | Handler<ParamKeys<Path>, E, D>,131+ ...args: [Handler<ParamKeys<Path>, E, D>]132 ): this => {133 if (typeof args1 === 'string') {134 this.path = args1135 } else {21 unmodified lines157 const message = 'Internal Server Error'158 return c.text(message, 500)159 }160 148- route(path: string, app?: Hono<any>): Hono<E, P> {161+ route(path: string, app?: Hono<any>): Hono<E, P, D> {162 this._tempPath = path163 if (app) {164 app.routes.map((r) => {165 this.addRoute(r.method, r.path, r.handler)3 unmodified lines169 170 return this171 }172 160- use<Path extends string = string, Env extends Partial<Environment> = E>(161- ...middleware: Handler<Path, Env>[]162- ): Hono<Env, Path>163- use<Path extends string = string, Env extends Partial<Environment> = E>(164- arg1: string,165- ...middleware: Handler<Path, Env>[]166- ): Hono<Env, Path>167- use(arg1: string | Handler<string, E>, ...handlers: Handler<string, E>[]): Hono<E, P> {173+ use<174+ Path extends string = string,175+ Env extends Partial<Environment> = E,176+ Data extends ValidatedData = D177+ >(...middleware: Handler<Path, Env, Data>[]): Hono<Env, Path, Data>178+ use<179+ Path extends string = string,180+ Env extends Partial<Environment> = E,181+ Data extends ValidatedData = D182+ >(arg1: string, ...middleware: Handler<Path, Env, Data>[]): Hono<Env, Path, D>183+ use(arg1: string | Handler<string, E, D>, ...handlers: Handler<string, E, D>[]): Hono<E, P, D> {184 if (typeof arg1 === 'string') {185 this.path = arg1186 } else {187 handlers.unshift(arg1)3 unmodified lines191 })192 return this193 }194 179- onError(handler: ErrorHandler<E>): Hono<E, P> {195+ onError(handler: ErrorHandler<E>): Hono<E, P, D> {196 this.errorHandler = handler197 return this198 }199 184- notFound(handler: NotFoundHandler<E>): Hono<E, P> {200+ notFound(handler: NotFoundHandler<E>): Hono<E, P, D> {201 this.notFoundHandler = handler202 return this203 }204 189- private addRoute(method: string, path: string, handler: Handler<string, E>): void {205+ private addRoute(method: string, path: string, handler: Handler<string, E, D>): void {206 method = method.toUpperCase()207 if (this._tempPath) {208 path = mergePath(this._tempPath, path)209 }210 this.router.add(method, path, handler)195- const r: Route<E> = { path: path, method: method, handler: handler }211+ const r: Route<E, D> = { path: path, method: method, handler: handler }212 this.routes.push(r)213 }214 215 private matchRoute(method: string, path: string) {10 unmodified lines226 227 const result = this.matchRoute(method, path)228 request.paramData = result?.params229 214- const c = new HonoContext<string, E>(request, env, eventOrExecutionCtx, this.notFoundHandler)230+ const c = new HonoContext<string, E, D>(request, env, eventOrExecutionCtx, this.notFoundHandler)231 232 // Do not `compose` if it has only one handler233 if (result && result.handlers.length === 1) {234 const handler = result.handlers[0]50 unmodified linesmodified:src/request.ts+21 added-1 removed
1 unmodified line2 import type { Cookie } from './utils/cookie'3 import { parse } from './utils/cookie'4 import { getQueryStringFromURL } from './utils/url'5 6+type ValidatedData = Record<string, any>7+8 declare global {7- interface Request<ParamKeyType extends string = string> {9+ interface Request<10+ ParamKeyType extends string = string,11+ Data extends ValidatedData = ValidatedData12+ > {13 paramData?: Record<ParamKeyType, string>14 param: {15 (key: ParamKeyType): string16 (): Record<ParamKeyType, string>23 unmodified lines40 jsonData?: any41 json: {42 (): Promise<any>43 }44+ data: Data45+ valid: {46+ (key: string, value: any): Data47+ (): Data48+ }49 }50 }51 52 export function extendRequestPrototype() {92 unmodified lines145 jsonData = this.jsonData146 }147 return jsonData148 } as InstanceType<typeof Request>['jsonData']149+150+ Request.prototype.valid = function (this: Request, key?: string, value?: any) {151+ if (!this.data) {152+ this.data = {}153+ }154+ if (key && value) {155+ this.data[key] = value156+ }157+ return this.data158+ } as InstanceType<typeof Request>['valid']159 }