Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Compatibility with Cloudflare Workers #253

Closed
boywithkeyboard opened this issue Sep 28, 2022 · 2 comments
Closed

Compatibility with Cloudflare Workers #253

boywithkeyboard opened this issue Sep 28, 2022 · 2 comments

Comments

@boywithkeyboard
Copy link

I'd like to use TypeBox in Cloudflare Workers, but i keep getting the below error.

Unhandled Promise Rejection: EvalError: Code generation from strings disallowed for this context

Is there any way to work around this?

@sinclairzx81
Copy link
Owner

@Unvented Hi.

You can use Value.Check(T, value) instead of compiling with the TypeCompiler. The Value.Check(T, value) function will carry out the same runtime checks as the compiled version, however it uses dynamic type checking; which means you will lose out on the performance optimizations you get through compilation (but is relatively still quite fast to use)

import { Value } from '@sinclair/typebox/value'
import { Type } from '@sinclair/typebox'

const T = Type.Object({
   x: Type.Number(),
   y: Type.Number(),
   z: Type.Number()
})

const value = { x: 1, y: 2, z: 3 }

if(!Value.Check(T, value)) {
  const errors = [...Value.Errors(T, value)]
  console.log(errors)
}

Alternatively, if you want to retain the performance, you can inspect the compiled validation routine with the TypeCheck.Code(). To use this, you will need to precompile the schemas first as a build step.

const T = Type.Object({
   x: Type.Number(),
   y: Type.Number(),
   z: Type.Number()
})

const C = TypeCompiler.Compile(T)

console.log(C.Code()) // use this code to validate

Hope that helps
S

@boywithkeyboard
Copy link
Author

@sinclairzx81 thank you so much <3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants