计划使用AJV 来验证用户输入。AJV 需要数据模型 JSON Schema 来验证用户输入。因此,我们需要从 Sequelize 模型中派生 JSON Schema。有没有办法以编程方式从 Sequelize 模型中获取JSON 模式?
问问题
1963 次
1 回答
3
一个迟到的答案,但我最终创建了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'));
于 2018-04-17T00:17:02.957 回答