Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Validators

Ajv is the default JSON Schema validator used by@feathersjs/schema. We chose it because it's fully compliant with the JSON Schema spec and it's the fastest JSON Schema validator because it has its own compiler. It pre-compiles code for each validator, instead of dynamically creating validators from schemas during runtime.

Important

Ajv and most other validation libraries are only used for ensuring data is valid and are not designed to convert data to different types. Type conversions and populating data can be done usingresolvers. This ensures a clean separation of concern between validating and populating data.

Usage

The following is the standardvalidators.ts file that sets up a validator for data and queries (for which string types will be coerced automatically). It also sets up a collection of additional formats usingajv-formats. The validators in this file can be customized according to theAjv documentation andits plugins. You can find the available Ajv options in theAjv class API docs.

ts
import { Ajv, addFormats } from '@feathersjs/schema'import type { FormatsPluginOptions } from '@feathersjs/schema'constformats:FormatsPluginOptions = [  'date-time',  'time',  'date',  'email',  'hostname',  'ipv4',  'ipv6',  'uri',  'uri-reference',  'uuid',  'uri-template',  'json-pointer',  'relative-json-pointer',  'regex']export constdataValidator = addFormats(newAjv({}), formats)export constqueryValidator = addFormats(  newAjv({    coerceTypes:true  }),  formats)

Validation functions

A validation function takes data and validates them against a schema using a validator. They can be used with any validation library. Currently thegetValidator functions are available for:

  • TypeBox schema to validate a TypeBox definition using an Ajv validator instance
  • JSON schema to validate a JSON schema object using an Ajv validator instance

Hooks

The following hooks take avalidation function and validate parts of thehook context.

validateData

schemaHooks.validateData takes avalidation function and allows to validate thedata in acreate,update andpatch request as well ascustom service methods. It can be used as anaround orbefore hook.

ts
import { Ajv, hooks as schemaHooks } from '@feathersjs/schema'import { Type, getValidator } from '@feathersjs/typebox'import type { Static } from '@feathersjs/typebox'import { dataValidator } from '../validators'constuserSchema = Type.Object(  {    id:Type.Number(),    email:Type.String(),    password:Type.String(),    avatar:Type.Optional(Type.String())  },  {$id:'User',additionalProperties:false })type User = Static<typeof userSchema>constuserDataSchema = Type.Pick(userSchema, ['email', 'password'])// Returns validation functions for `create`, `update` and `patch`constuserDataValidator = getValidator(userDataSchema, dataValidator)app.service('users').hooks({  before: {    all: [schemaHooks.validateData(userDataValidator)]  }})

validateQuery

schemaHooks.validateQuery takes avalidation function and validates thequery of a request. It can be used as anaround orbefore hook. When using thequeryValidator from theusage section, strings will automatically be converted to the right type usingAjv's type coercion rules.

ts
import { Ajv, schemaHooks } from '@feathersjs/schema'import { Type, getValidator } from '@feathersjs/typebox'import { queryValidator } from '../validators'// Schema for allowed query propertiesconstmessageQueryProperties = Type.Pick(messageSchema, ['id', 'text', 'createdAt', 'userId'], {  additionalProperties:false})constmessageQuerySchema = querySyntax(messageQueryProperties)type MessageQuery = Static<typeof messageQuerySchema>constmessageQueryValidator = getValidator(messageQuerySchema, queryValidator)app.service('messages').hooks({  around: {    all: [schemaHooks.validateQuery(messageQueryValidator)]  }})

Using validators with custom methods

You can optionally create validators for your custom methods. For example we will create a custom method in ouruser service that simply says "Hello ${name}" to the requestor.

For the example we can use this TypeBox schema

ts
//Our request object, we expect something like {name: "Bob"}export constsayHelloRequest = Type.Object(  {    name:Type.String({      description:"Who are we saying hello to!",      examples: ["Bob"],      minLength:2,    }),  },  {$id:"sayHelloRequest",additionalProperties:false },);//We intend on returning an object with a string response propertyexport constsayHelloResponse = Type.Object(  {response:Type.String() },  {$id:"sayHelloResponse",additionalProperties:false },);export constsayHelloValidator = getValidator(sayHelloRequest, dataValidator);

In our user class file, we can define our custom method

ts
async sayHello(data:Static<typeof sayHelloRequest>):Promise<Static<typeof sayHelloResponse>> {  const {name } =data  return {response:`Hello${name}` }}

Finally, we can add our validator in our service hooks

ts
sayHello: [schemaHooks.validateData(sayHelloValidator)]

Released under the MIT License.

Copyright © 2012-2025 FeathersJS contributors


[8]ページ先頭

©2009-2025 Movatter.jp