Skip to content
Myr

validator.ts

This file

Path

src/validator/validator.ts

140 lines · 4.4 KiB · TypeScript

Last changed by

fix(validator): use the cached content (#2234)Yusuke Wadabefore adoptione2f1d14

History of this file

Take it

The walk stopped after 200 commits: lines older than 2f9a07d point at it.

perf(hono-base): use `instanceOf` (#1565)Yusuke Wadabefore adoption2f9a07d

lines 1–2why, one step back
1import type { Context } from '../context'
2import { getCookie } from '../helper/cookie'

Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7

line 3why, one step back
3import { HTTPException } from '../http-exception'

fix(validator): exclude Response type for returned values from `c.req.valid()` (#1914)Yusuke Wadabefore adoptiondbdbd22

line 4why, one step back
4import type { Env, ValidationTargets, MiddlewareHandler, TypedResponse } from '../types'

perf(hono-base): use `instanceOf` (#1565)Yusuke Wadabefore adoption2f9a07d

lines 5–22why, one step back
5import 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>22

fix(validator): exclude Response type for returned values from `c.req.valid()` (#1914)Yusuke Wadabefore adoptiondbdbd22

lines 23–25why, one step back
23// eslint-disable-next-line @typescript-eslint/no-explicit-any
24type ExcludeResponseType<T> = T extends Response & TypedResponse<any> ? never : T25

perf(hono-base): use `instanceOf` (#1565)Yusuke Wadabefore adoption2f9a07d

lines 26–31why, one step back
26export 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 back
32 OutputTypeExcludeResponseType = ExcludeResponseType<OutputType>,

perf(hono-base): use `instanceOf` (#1565)Yusuke Wadabefore adoption2f9a07d

lines 33–34why, one step back
33 P2 extends string = P,
34 V extends {

Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7

lines 35–40why, one step back
35 in: {
36 [K in U]: K extends 'json'37 ? InputType38 : { [K2 in keyof OutputTypeExcludeResponseType]: ValidationTargets[K][K2] }39 }40 out: { [K in U]: OutputTypeExcludeResponseType }

perf(hono-base): use `instanceOf` (#1565)Yusuke Wadabefore adoption2f9a07d

line 41why, one step back
41 } = {

Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7

lines 42–47why, one step back
42 in: {
43 [K in U]: K extends 'json'44 ? InputType45 : { [K2 in keyof OutputTypeExcludeResponseType]: ValidationTargets[K][K2] }46 }47 out: { [K in U]: OutputTypeExcludeResponseType }

perf(hono-base): use `instanceOf` (#1565)Yusuke Wadabefore adoption2f9a07d

lines 48–61why, one step back
48 },
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 back
62 const contentType = c.req.header('Content-Type')

perf(hono-base): use `instanceOf` (#1565)Yusuke Wadabefore adoption2f9a07d

lines 63–65why, one step back
63
64 switch (target) {65 case 'json':

fix(validator): Invalid HTTP header error is hidden (#1694)Robert Sasakbefore adoption79dc187

lines 66–67why, one step back
66 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 back
68 throw new HTTPException(400, { message })

fix(validator): Invalid HTTP header error is hidden (#1694)Robert Sasakbefore adoption79dc187

line 69why, one step back
69 }

fix(validator): use the cached content (#2234)Yusuke Wadabefore adoptione2f1d14

lines 70–73why, one step back
70 if (c.req.bodyCache.json) {
71 value = await c.req.bodyCache.json72 break73 }

fix(validator): Invalid HTTP header error is hidden (#1694)Robert Sasakbefore adoption79dc187

line 74why, one step back
74 /**

fix(validator): use the cached content (#2234)Yusuke Wadabefore adoptione2f1d14

line 75why, one step back
75 * Get the arrayBuffer, create JSON object via Response, and cache the arrayBuffer in the c.req.bodyCache if there is no cached content in c.req.bodyCache.json.

fix(validator): Invalid HTTP header error is hidden (#1694)Robert Sasakbefore adoption79dc187

line 76why, one step back
76 */

perf(hono-base): use `instanceOf` (#1565)Yusuke Wadabefore adoption2f9a07d

lines 77–82why, one step back
77 try {
78 const arrayBuffer = c.req.bodyCache.arrayBuffer ?? (await c.req.raw.arrayBuffer())79 value = await new Response(arrayBuffer).json()80 c.req.bodyCache.json = value81 c.req.bodyCache.arrayBuffer = arrayBuffer82 } catch {

Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7

lines 83–84why, one step back
83 const message = 'Malformed JSON in request body'
84 throw new HTTPException(400, { message })

perf(hono-base): use `instanceOf` (#1565)Yusuke Wadabefore adoption2f9a07d

lines 85–87why, one step back
85 }
86 break87 case 'form': {

fix(validator): use the cached content (#2234)Yusuke Wadabefore adoptione2f1d14

lines 88–91why, one step back
88 if (c.req.bodyCache.formData) {
89 value = c.req.bodyCache.formData90 break91 }

perf(hono-base): use `instanceOf` (#1565)Yusuke Wadabefore adoption2f9a07d

lines 92–107why, one step back
92 try {
93 const contentType = c.req.header('Content-Type')94 if (contentType) {95 const arrayBuffer = c.req.bodyCache.arrayBuffer ?? (await c.req.raw.arrayBuffer())96 const formData = await bufferToFormData(arrayBuffer, contentType)97 const form: BodyData = {}98 formData.forEach((value, key) => {99 form[key] = value100 })101 value = form102 c.req.bodyCache.formData = formData103 c.req.bodyCache.arrayBuffer = arrayBuffer104 }105 } catch (e) {106 let message = 'Malformed FormData request.'107 message += e instanceof Error ? ` ${e.message}` : ` ${String(e)}`

Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7

line 108why, one step back
108 throw new HTTPException(400, { message })

perf(hono-base): use `instanceOf` (#1565)Yusuke Wadabefore adoption2f9a07d

lines 109–140why, one step back
109 }
110 break111 }112 case 'query':113 value = Object.fromEntries(114 Object.entries(c.req.queries()).map(([k, v]) => {115 return v.length === 1 ? [k, v[0]] : [k, v]116 })117 )118 break119 case 'param':120 value = c.req.param() as Record<string, string>121 break122 case 'header':123 value = c.req.header()124 break125 case 'cookie':126 value = getCookie(c)127 break128 }129130 const res = await validationFunc(value as never, c as never)131132 if (res instanceof Response) {133 return res134 }135136 c.req.addValidatedData(target, res as never)137138 await next()139 }140}