Replaces TypeCompiler with Value (#90)

* Replaces TypeCompiler with Value

Cloudflare worker throws an EvalError when using TypeCompiler.Compile(schema).Check(data)

* added changeset

---------

Co-authored-by: Aman <aman@bignerd.io>
pull/100/head
Aman 2023-07-15 11:05:15 +05:30 committed by GitHub
parent 89e3f88789
commit 65ed112e0e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 8 additions and 4 deletions

View File

@ -0,0 +1,5 @@
---
'@hono/typebox-validator': minor
---
Fixed EvalError

View File

@ -1,5 +1,5 @@
import type { TSchema, Static } from '@sinclair/typebox'
import { TypeCompiler, type ValueError } from '@sinclair/typebox/compiler'
import { Value, type ValueError } from '@sinclair/typebox/value'
import type { Context, Env, MiddlewareHandler, ValidationTargets } from 'hono'
import { validator } from 'hono/validator'
@ -62,9 +62,8 @@ export function tbValidator<
>(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)
return validator(target, (data, c) => {
if (compiled.Check(data)) {
if (Value.Check(schema, data)) {
if (hook) {
const hookResult = hook({ success: true, data }, c)
if (hookResult instanceof Response || hookResult instanceof Promise) {
@ -73,6 +72,6 @@ export function tbValidator<
}
return data
}
return c.json({ success: false, errors: [...compiled.Errors(data)] }, 400)
return c.json({ success: false, errors: [...Value.Errors(schema, data)] }, 400)
})
}