Is it possible to load validations dynamically? #1704
-
|
Let's say I have .get("/api/*", (ctx) => {
return {hello: "New API!"}
})And I want for path Is it possible? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
@Serhioromano elysia's validation is statically bound at route registration time, so a wildcard route gets one schema for all paths. there's no built-in way to swap validators dynamically per request. the idiomatic approach is to use const app = new Elysia()
.group('/api', (app) =>
app
.get('/user', ({ query }) => ({ id: query.id }), {
query: t.Object({ id: t.String() })
})
.get('/login', ({ query }) => ({ name: query.name }), {
query: t.Object({ name: t.String(), pass: t.String() })
})
)if you have shared validation across all .group('/api', {
headers: t.Object({ authorization: t.String() })
}, (app) =>
app
.get('/user', handler, { query: userSchema })
.get('/login', handler, { query: loginSchema })
)if you absolutely need a wildcard, the escape hatch is manual validation with typebox's import { Value } from '@sinclair/typebox/value'
const schemas = { '/api/user': userSchema, '/api/login': loginSchema }
app.get('/api/*', ({ query, path, error }) => {
const schema = schemas[path]
if (schema && !Value.Check(schema, query)) return error(422)
// ...
})but you lose type inference and auto-docs. explicit routes are almost always the better call. |
Beta Was this translation helpful? Give feedback.
@Serhioromano elysia's validation is statically bound at route registration time, so a wildcard route gets one schema for all paths. there's no built-in way to swap validators dynamically per request.
the idiomatic approach is to use
.group()with explicit routes:if you have shared validation across all
/apiroutes (e.g., auth headers), use.guard():