validator.ts
This file
Path
src/validator/validator.ts
133 lines · 4.2 KiB · TypeScript
Last changed by
Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7
History of this fileTake it
The walk stopped after 200 commits: lines older than ba04dac point at it.
Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 1–2why, one step back1import type { Context } from '../context'2import { getCookie } from '../helper/cookie'Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7
line 3why, one step back3import { HTTPException } from '../http-exception'fix(validator): exclude Response type for returned values from `c.req.valid()` (#1914)Yusuke Wadabefore adoptiondbdbd22
line 4why, one step back4import type { Env, ValidationTargets, MiddlewareHandler, TypedResponse } from '../types'Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 5–22why, one step back5import type { BodyData } from '../utils/body'6import { bufferToFormData } from '../utils/buffer'78type ValidationTargetKeysWithBody = 'form' | 'json'9type ValidationTargetByMethod<M> = M extends 'get' | 'head' // GET and HEAD request must not have a body content.10 ? Exclude<keyof ValidationTargets, ValidationTargetKeysWithBody>11 : keyof ValidationTargets1213export type ValidationFunction<14 InputType,15 OutputType,16 E extends Env = {},17 P extends string = string18> = (19 value: InputType,20 c: Context<E, P>21) => OutputType | Response | Promise<OutputType> | Promise<Response>22fix(validator): exclude Response type for returned values from `c.req.valid()` (#1914)Yusuke Wadabefore adoptiondbdbd22
lines 23–25why, one step back23// eslint-disable-next-line @typescript-eslint/no-explicit-any24type ExcludeResponseType<T> = T extends Response & TypedResponse<any> ? never : T25Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 26–31why, one step back26export const validator = <27 InputType,28 P extends string,29 M extends string,30 U extends ValidationTargetByMethod<M>,31 OutputType = ValidationTargets[U],Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7
line 32why, one step back32 OutputTypeExcludeResponseType = ExcludeResponseType<OutputType>,Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 33–34why, one step back33 P2 extends string = P,34 V extends {Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7
lines 35–40why, one step back35 in: {36 [K in U]: K extends 'json'37 ? InputType38 : { [K2 in keyof OutputTypeExcludeResponseType]: ValidationTargets[K][K2] }39 }40 out: { [K in U]: OutputTypeExcludeResponseType }Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
line 41why, one step back41 } = {Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7
lines 42–47why, one step back42 in: {43 [K in U]: K extends 'json'44 ? InputType45 : { [K2 in keyof OutputTypeExcludeResponseType]: ValidationTargets[K][K2] }46 }47 out: { [K in U]: OutputTypeExcludeResponseType }Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 48–61why, one step back48 },49 // eslint-disable-next-line @typescript-eslint/no-explicit-any50 E extends Env = any51>(52 target: U,53 validationFunc: ValidationFunction<54 unknown extends InputType ? ValidationTargets[U] : InputType,55 OutputType,56 E,57 P258 >59): MiddlewareHandler<E, P, V> => {60 return async (c, next) => {61 let value = {}fix(validator): Invalid HTTP header error is hidden (#1694)Robert Sasakbefore adoption79dc187
line 62why, one step back62 const contentType = c.req.header('Content-Type')Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 63–65why, one step back6364 switch (target) {65 case 'json':fix(validator): Invalid HTTP header error is hidden (#1694)Robert Sasakbefore adoption79dc187
lines 66–67why, one step back66 if (!contentType || !contentType.startsWith('application/json')) {67 const message = `Invalid HTTP header: Content-Type=${contentType}`Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7
line 68why, one step back68 throw new HTTPException(400, { message })fix(validator): Invalid HTTP header error is hidden (#1694)Robert Sasakbefore adoption79dc187
lines 69–73why, one step back69 }70 /**71 * Get the arrayBuffer first, create JSON object via Response,72 * and cache the arrayBuffer in the c.req.bodyCache.73 */Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 74–79why, one step back74 try {75 const arrayBuffer = c.req.bodyCache.arrayBuffer ?? (await c.req.raw.arrayBuffer())76 value = await new Response(arrayBuffer).json()77 c.req.bodyCache.json = value78 c.req.bodyCache.arrayBuffer = arrayBuffer79 } catch {Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7
lines 80–81why, one step back80 const message = 'Malformed JSON in request body'81 throw new HTTPException(400, { message })Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 82–84why, one step back82 }83 break84 case 'form': {fix: return status 500 when using validator 'form' (#1554)Bruno Marquesbefore adoptioncca7577
lines 85–100why, one step back85 try {86 const contentType = c.req.header('Content-Type')87 if (contentType) {88 const arrayBuffer = c.req.bodyCache.arrayBuffer ?? (await c.req.raw.arrayBuffer())89 const formData = await bufferToFormData(arrayBuffer, contentType)90 const form: BodyData = {}91 formData.forEach((value, key) => {92 form[key] = value93 })94 value = form95 c.req.bodyCache.formData = formData96 c.req.bodyCache.arrayBuffer = arrayBuffer97 }98 } catch (e) {99 let message = 'Malformed FormData request.'100 message += e instanceof Error ? ` ${e.message}` : ` ${String(e)}`Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7
line 101why, one step back101 throw new HTTPException(400, { message })Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 102–133why, one step back102 }103 break104 }105 case 'query':106 value = Object.fromEntries(107 Object.entries(c.req.queries()).map(([k, v]) => {108 return v.length === 1 ? [k, v[0]] : [k, v]109 })110 )111 break112 case 'param':113 value = c.req.param() as Record<string, string>114 break115 case 'header':116 value = c.req.header()117 break118 case 'cookie':119 value = getCookie(c)120 break121 }122123 const res = await validationFunc(value as never, c as never)124125 if (res instanceof Response) {126 return res127 }128129 c.req.addValidatedData(target, res as never)130131 await next()132 }133}