0
0
mirror of https://github.com/honojs/hono.git synced 2024-11-25 05:07:03 +01:00

refactor(validator): show type error if get/head with form/json (#772)

This commit is contained in:
Yusuke Wada 2023-01-03 09:09:04 +09:00
parent b567a574d6
commit 6bee574ca3
3 changed files with 21 additions and 8 deletions

View File

@ -38,6 +38,7 @@ module.exports = defineConfig({
{
types: {
Function: false,
'{}': false,
},
},
],

View File

@ -7,17 +7,22 @@ type ValidatorHandler<E extends Partial<Environment>, R extends Route = Route, I
next: Next
) => Promise<Response | undefined | void> | Response
type ValidationTypeKeysWithBody = 'form' | 'json'
type ValidationTypeByMethod<M> = M extends 'get' | 'head' // GET and HEAD request must not have a body content.
? Exclude<keyof ValidationTypes, ValidationTypeKeysWithBody>
: keyof ValidationTypes
export const validator = <
T,
U extends keyof ValidationTypes,
Method extends string,
U extends ValidationTypeByMethod<Method>,
V extends { type: U; data: T },
// eslint-disable-next-line @typescript-eslint/ban-types
V2 = {},
E extends Partial<Environment> = Environment
>(
type: U,
validationFunc: (value: ValidationTypes[U], c: Context<E>) => T | Response | Promise<Response>
): ValidatorHandler<E, Route, V | V2> => {
): ValidatorHandler<E, { method: Method; path: string }, V | V2> => {
return async (c, next) => {
let value = {}
@ -47,7 +52,8 @@ export const validator = <
break
}
const res = validationFunc(value, c)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const res = validationFunc(value, c as any)
if (res instanceof Response || res instanceof Promise) {
return res

View File

@ -7,17 +7,22 @@ type ValidatorHandler<E extends Partial<Environment>, R extends Route = Route, I
next: Next
) => Promise<Response | undefined | void> | Response
type ValidationTypeKeysWithBody = 'form' | 'json'
type ValidationTypeByMethod<M> = M extends 'get' | 'head' // GET and HEAD request must not have a body content.
? Exclude<keyof ValidationTypes, ValidationTypeKeysWithBody>
: keyof ValidationTypes
export const validator = <
T,
U extends keyof ValidationTypes,
Method extends string,
U extends ValidationTypeByMethod<Method>,
V extends { type: U; data: T },
// eslint-disable-next-line @typescript-eslint/ban-types
V2 = {},
E extends Partial<Environment> = Environment
>(
type: U,
validationFunc: (value: ValidationTypes[U], c: Context<E>) => T | Response | Promise<Response>
): ValidatorHandler<E, Route, V | V2> => {
): ValidatorHandler<E, { method: Method; path: string }, V | V2> => {
return async (c, next) => {
let value = {}
@ -47,7 +52,8 @@ export const validator = <
break
}
const res = validationFunc(value, c)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const res = validationFunc(value, c as any)
if (res instanceof Response || res instanceof Promise) {
return res