计划使用AJV
用于验证用户输入。 AJV需要数据模型JSON Schema来验证用户输入。因此,我们需要从Sequelize模型派生JSON Schema。是否可以通过编程从Sequelize模型中获取JSON schema

最佳答案

答案很晚,但是我最终创建了sequelize-to-json-schema来解决我们的需求。

它为您提供了更多的自定义方式,包括您将哪些属性包括在架构中,以及添加了创建方法或类似方法可能使用的虚拟属性。



// assuming you have a user model with the properties
// name (string) and status (enum: real, imagined)
const schemaFactory = require('sequelize-to-json-schema');

const factory = new SchemaFactory({
  customSchema: {
    user: {
      name: { description: "The user's name" },
      status: { description: 'Was it all just a dream?' },
    },
  }
  hrefBase: 'http://schema.example',
});
const schemaGenerator = factory.getSchemaGenerator(User);
const schema = schemaGenerator.getSchema();

// Results in
schema = {
  {
    title: 'User',
    '$id': 'http://schema.example/user.json',
    type: 'object',
    '$schema': 'http://json-schema.org/draft-06/schema#',
    properties: {
      name: {
        '$id': '/properties/fullname',
        type: 'string',
        examples: [],
        title: 'Name',
        description: "The user's name",
      },
      status: {
        '$id': '/properties/status',
        type: 'string',
        examples: ['REAL', 'IMAGINED'],
        enum: ['REAL', 'IMAGINED'],
        title: 'Status',
        description: 'Was it all just a dream?'
      }
    }
  }
}


注意:sequelize-to-json-schema生成-06草稿模式,以将其与AJV一起使用,其自述文件指出您需要执行以下操作:

ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json'));

08-18 11:03