【问题标题】:Convert Sequelize model to JSON Schema for user input validation将 Sequelize 模型转换为 JSON Schema 以进行用户输入验证
【发布时间】:2017-07-03 05:12:14
【问题描述】:

计划使用AJV 用于验证用户输入。 AJV 需要数据模型 JSON Schema 来验证用户输入。因此,我们需要从 Sequelize 模型中派生 JSON Schema。有没有办法以编程方式从 Sequelize 模型中获取JSON schema

【问题讨论】:

标签: node.js sequelize.js jsonschema json-schema-validator ajv


【解决方案1】:

一个迟到的答案,但我最终创建了sequelize-to-json-schema 来解决我们的需求。

根据您在架构中包含的属性以及添加可能由您的 create 方法或类似方法使用的虚拟属性,它提供了更多的自定义。

示例

// 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 生成 Draft-06 模式,要与 AJV 一起使用,他们的 README 说你需要这样做:

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

【讨论】:

  • @ChristopherJ 是否可以将 sequelize-to-json-schema 与 sequelize v4 一起使用?
  • 我们针对旧版本的 sequelize 编写了它。如果 API 发生重大更改会破坏它,很高兴查看 PR 以使其与 v4 一起使用
  • 谢谢@ChristopherJ!我让它工作了,至少在我们正在使用的 v4 功能集上 :)
  • 太棒了。很想知道正在使用它的项目:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-11
  • 2021-09-02
  • 2018-11-22
  • 2016-04-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多