[valibot-validator] Fix Type Inference for number Types in `valibot-validator` Query (#502)

* [valibot-validator] Type inference failure in RPC routes when `"query"` contains `number` type(s). #501

* add changeset file.
pull/504/head
hiraoka 2024-05-06 10:10:56 +09:00 committed by GitHub
parent 3e96b5e128
commit d703577b55
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 33 additions and 15 deletions

View File

@ -0,0 +1,5 @@
---
'@hono/valibot-validator': patch
---
improved vvalidator to infer route types with number queries

View File

@ -31,7 +31,7 @@
"valibot": ">=0.13.1 <1"
},
"devDependencies": {
"hono": "^3.11.7",
"hono": "^4.0.10",
"jest": "^29.7.0",
"rimraf": "^5.0.5",
"valibot": "^0.24.1"

View File

@ -1,4 +1,4 @@
import type { Context, MiddlewareHandler, Env, ValidationTargets } from 'hono'
import type { Context, MiddlewareHandler, Env, ValidationTargets, Input as HonoInput } from 'hono'
import { validator } from 'hono/validator'
import type { BaseSchema, Input, Output, SafeParseResult } from 'valibot'
import { safeParse } from 'valibot'
@ -15,22 +15,33 @@ export const vValidator = <
Target extends keyof ValidationTargets,
E extends Env,
P extends string,
V extends {
in: HasUndefined<Input<T>> extends true
? { [K in Target]?: Input<T> }
: { [K in Target]: Input<T> }
out: { [K in Target]: Output<T> }
} = {
in: HasUndefined<Input<T>> extends true
? { [K in Target]?: Input<T> }
: { [K in Target]: Input<T> }
out: { [K in Target]: Output<T> }
}
In = Input<T>,
Out = Output<T>,
I extends HonoInput = {
in: HasUndefined<In> extends true
? {
[K in Target]?: K extends 'json'
? In
: HasUndefined<keyof ValidationTargets[K]> extends true
? { [K2 in keyof In]?: ValidationTargets[K][K2] }
: { [K2 in keyof In]: ValidationTargets[K][K2] }
}
: {
[K in Target]: K extends 'json'
? In
: HasUndefined<keyof ValidationTargets[K]> extends true
? { [K2 in keyof In]?: ValidationTargets[K][K2] }
: { [K2 in keyof In]: ValidationTargets[K][K2] }
}
out: { [K in Target]: Out }
},
V extends I = I
>(
target: Target,
schema: T,
hook?: Hook<T, E, P>
): MiddlewareHandler<E, P, V> =>
// @ts-expect-error not typed well
validator(target, (value, c) => {
const result = safeParse(schema, value)

View File

@ -17,6 +17,7 @@ describe('Basic', () => {
const querySchema = optional(
object({
search: optional(string()),
page: optional(number()),
})
)
@ -47,7 +48,8 @@ describe('Basic', () => {
} & {
query?:
| {
search?: string | undefined
search?: string | string[] | undefined
page?: string | string[] | undefined
}
| undefined
}

View File

@ -2114,7 +2114,7 @@ __metadata:
version: 0.0.0-use.local
resolution: "@hono/valibot-validator@workspace:packages/valibot-validator"
dependencies:
hono: "npm:^3.11.7"
hono: "npm:^4.0.10"
jest: "npm:^29.7.0"
rimraf: "npm:^5.0.5"
valibot: "npm:^0.24.1"