Fastify 的自定义格式化程序

Custom formatter for fastify

我想为 fastify 添加自定义模式格式化程序。

import fastify from 'fastify'
import AjvCompiler from '@fastify/ajv-compiler'

const ajvFormatter = AjvCompiler(ajv);
ajvFormatter.addFormat('new-format', /hello/);

const app = fastify({
  schemaController: {
    compilersFactory: {
      buildValidator: ajvFormatter
    }
  }
})

我添加格式还是报错:

 Failed building the validation schema for POST: /hey, due to error unknown format 
"new-format" ignored in schema at path

我猜最新的 fastify 不支持这个功能。

您以错误的方式使用了 @fastify/ajv-compiler 模块。它根本不接受 ajv 输入参数。它不导出 addFormat 方法。

您需要使用 customOption 选项:

const fastify = require('fastify')

const app = fastify({
  logger: true,
  ajv: {
    customOptions: {
      formats: {
        'new-format': /hello/,
      },
    },
  },
})

app.get(
  '/:hello',
  {
    schema: {
      params: {
        type: 'object',
        properties: {
          hello: {
            type: 'string',
            format: 'new-format',
          },
        },
      },
    },
  },
  async (request, reply) => {
    return request.params
  }
)
app.listen(8080, '0.0.0.0')

// curl http://127.0.0.1:8080/hello
// curl http://127.0.0.1:8080/hello-foo