Skip to Content

流式模式

验证和序列化 文档概述了 Fastify 接受的所有参数,用于设置 JSON Schema 验证以验证输入,并优化输出的 JSON Schema 序列化。

fluent-json-schema 可以简化此任务并允许重用常量。

基本设置

const S = require('fluent-json-schema') // 你可以使用这样的对象,或者查询数据库获取值 const MY_KEYS = { KEY1: 'ONE', KEY2: 'TWO' } const bodyJsonSchema = S.object() .prop('someKey', S.string()) .prop('someOtherKey', S.number()) .prop('requiredKey', S.array().maxItems(3).items(S.integer()).required()) .prop('nullableKey', S.mixed([S.TYPES.NUMBER, S.TYPES.NULL])) .prop('multipleTypesKey', S.mixed([S.TYPES.BOOLEAN, S.TYPES.NUMBER])) .prop('multipleRestrictedTypesKey', S.oneOf([S.string().maxLength(5), S.number().minimum(10)])) .prop('enumKey', S.enum(Object.values(MY_KEYS))) .prop('notTypeKey', S.not(S.array())) const queryStringJsonSchema = S.object() .prop('name', S.string()) .prop('excitement', S.integer()) const paramsJsonSchema = S.object() .prop('par1', S.string()) .prop('par2', S.integer()) const headersJsonSchema = S.object() .prop('x-foo', S.string().required()) // 注意,不需要调用 `.valueOf()`! const schema = { body: bodyJsonSchema, querystring: queryStringJsonSchema, // (或) query: queryStringJsonSchema params: paramsJsonSchema, headers: headersJsonSchema } fastify.post('/the/url', { schema }, handler)

复用

使用 fluent-json-schema,你可以更轻松地以编程方式操作你的模式,并通过 addSchema() 方法重用它们。你可以在两种不同的方式中引用模式,详情请参阅 验证和序列化 文档。

以下是几个使用示例:

$ref-way: 引用外部模式。

const addressSchema = S.object() .id('#address') .prop('line1').required() .prop('line2') .prop('country').required() .prop('city').required() .prop('zipcode').required() const commonSchemas = S.object() .id('https://fastify/demo') .definition('addressSchema', addressSchema) .definition('otherSchema', otherSchema) // 可以添加任何你需要的模式 fastify.addSchema(commonSchemas) const bodyJsonSchema = S.object() .prop('residence', S.ref('https://fastify/demo#address')).required() .prop('office', S.ref('https://fastify/demo#/definitions/addressSchema')).required() const schema = { body: bodyJsonSchema } fastify.post('/the/url', { schema }, handler)

replace-way: 在验证过程之前引用共享模式以替换。

const sharedAddressSchema = { $id: 'sharedAddress', type: 'object', required: ['line1', 'country', 'city', 'zipcode'], properties: { line1: { type: 'string' }, line2: { type: 'string' }, country: { type: 'string' }, city: { type: 'string' }, zipcode: { type: 'string' } } } fastify.addSchema(sharedAddressSchema) const bodyJsonSchema = { type: 'object', properties: { vacation: 'sharedAddress#' } } const schema = { body: bodyJsonSchema } fastify.post('/the/url', { schema }, handler)

注意:在使用 fastify.addSchema 时,你可以混合使用 $ref-wayreplace-way