refactor(typebox): refactor types (#72)

* refactor(typebox): refactor types

* add changeset
pull/74/head
Yusuke Wada 2023-03-21 17:59:59 +09:00 committed by GitHub
parent 9810eacdf7
commit 9ce42c23dd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 19 additions and 17 deletions

View File

@ -0,0 +1,5 @@
---
'@hono/typebox-validator': patch
---
refactor: refactored types

View File

@ -33,6 +33,6 @@
},
"devDependencies": {
"@sinclair/typebox": "^0.25.24",
"hono": "^3.1.0"
"hono": "^3.1.2"
}
}

View File

@ -1,12 +1,11 @@
import type { TSchema, Static } from '@sinclair/typebox'
import { TypeCompiler, type ValueError } from '@sinclair/typebox/compiler'
import type { Context, Env, MiddlewareHandler } from 'hono'
import type { Context, Env, MiddlewareHandler, ValidationTargets } from 'hono'
import { validator } from 'hono/validator'
type ValidationTargets = 'json' | 'form' | 'query' | 'queries'
type Hook<T> = (
type Hook<T, E extends Env, P extends string> = (
result: { success: true; data: T } | { success: false; errors: ValueError[] },
c: Context
c: Context<E, P>
) => Response | Promise<Response> | void
/**
@ -56,18 +55,11 @@ type Hook<T> = (
*/
export function tbValidator<
T extends TSchema,
Target extends ValidationTargets,
Target extends keyof ValidationTargets,
E extends Env,
P extends string
>(
target: Target,
schema: T,
hook?: Hook<Static<T>>
): MiddlewareHandler<
E,
P,
{ in: { [K in Target]: Static<T> }; out: { [K in Target]: Static<T> } }
> {
P extends string,
V extends { in: { [K in Target]: Static<T> }; out: { [K in Target]: Static<T> } }
>(target: Target, schema: T, hook?: Hook<Static<T>, E, P>): MiddlewareHandler<E, P, V> {
// Compile the provided schema once rather than per validation. This could be optimized further using a shared schema
// compilation pool similar to the Fastify implementation.
const compiled = TypeCompiler.Compile(schema)
@ -75,7 +67,7 @@ export function tbValidator<
if (compiled.Check(data)) {
if (hook) {
const hookResult = hook({ success: true, data }, c)
if (hookResult instanceof Response || hookResult instanceof Promise<Response>) {
if (hookResult instanceof Response || hookResult instanceof Promise) {
return hookResult
}
}

View File

@ -5237,6 +5237,11 @@ hono@^3.0.3, hono@^3.1.0:
resolved "https://registry.yarnpkg.com/hono/-/hono-3.1.0.tgz#4b29bcaddc489015b99d0a89b68133ccf72b2cf1"
integrity sha512-5hVyzp3mrAjxRwy6Uj7su0pIISGTKVX2tE4YiYO81V3w1KoYZEmz3g6X6P9nRLQmaABDWXmnL9GqEzBhTAPeog==
hono@^3.1.2:
version "3.1.2"
resolved "https://registry.yarnpkg.com/hono/-/hono-3.1.2.tgz#896231b8940c201212bb3d440bebce637e68be26"
integrity sha512-keNMGSlBX2VbwD5gF10Xu0zuUm9mTy1HWctIhuom8FJEJY6aKo1Bb/vQXTEjBupKDG7MJi2aG05YMo01GjkMQA==
hosted-git-info@^2.1.4:
version "2.8.9"
resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-2.8.9.tgz#dffc0bf9a21c02209090f2aa69429e1414daf3f9"