0.0.0-experimental.4 • Published 3 years ago
@kingworldjs/schema v0.0.0-experimental.4
@kingworldjs/schema
Plugin for kingworld for declaratively validation of incoming request.
Installation
bun add @kingworldjs/schemaSchema Validation
Use @kingworldjs/schema handle typed-strict validation of incoming request.
Schema validation is capable of validation of:
- body
- header
- query
- params
And optional config:
- customError
(type: SchemaType, error: Error | TypeError) => any- Return custom error message response
Schema plugin use fastest-validator for schema validation and declaration which has full TypeScript supports and auto-complete.
Example
import KingWorld from 'kingworld'
import schema from '@kingworldjs/schema'
new KingWorld()
.get<{
params: {
id: number
}
}>('/id/:id', ({ request: { params: { id } } }) => id, {
transform: (request, store) {
request.params.id = +request.params.id
},
preHandler: schema({
params: {
id: {
type: "number",
min: 1,
max: 100
}
}
})
})
.listen(3000)
// [GET] /id/2 => 2
// [GET] /id/500 => Invalid params
// [GET] /id/-3 => Invalid paramsTo use validation on group scope, simply attach schema to preHandler:
import KingWorld from 'kingworld'
import schema from '@kingworldjs/schema'
new KingWorld()
.group('/group', (app) => app
.preHandler(schema({
params: {
id: {
type: "number",
min: 1,
max: 100
}
}
}))
.get<{
params: {
id: number
}
}>('/user/:id', ({ request: { params: { id } } }) => id, {
transform: (request, store) {
request.params.id = +request.params.id
}
})
.get<{
params: {
id: number
}
}>('/post/:id', ({ request: { params: { id } } }) => id, {
transform: (request, store) {
request.params.id = +request.params.id
}
})
)
.listen(3000)
// [GET] /user/2 => 2
// [GET] /user/500 => Invalid params
// [GET] /post/-3 => Invalid paramsGotcha
Schema validation will be handle in order of preHandler.
To make sure everything is expected, please place schema plugin before any other preHandler that might depends on schema plugin.
0.0.0-experimental.4
3 years ago
0.0.0-experimental.3
3 years ago
0.0.0-experimental.2
3 years ago
0.0.0-experimental.1
3 years ago
0.0.0-experimental.0
3 years ago