alt3 / sequelize-to-json-schemas Goto Github PK
View Code? Open in Web Editor NEWConvert Sequelize models into various JSON Schema variants (using the Strategy Pattern)
License: MIT License
Convert Sequelize models into various JSON Schema variants (using the Strategy Pattern)
License: MIT License
Hi there
When validating a schema generated with the OAS 3.0 strategy I get the follwing error
Property contentEncoding is not allowed.
The original field looks like
recording: {
type: DataTypes.BLOB('long'),
defaultValue: null,
},
The generated is
recording:
type: string
contentEncoding: base64
nullable: true
default: null
Maybe the problem is at this line
According to https://swagger.io/docs/specification/data-models/data-types/#format
I would imagine something like
recording:
type: string
format: byte
nullable: true
default: null
that means changing the line of code mentioned into
case 'BLOB': {
result = { ...STRING, format: 'byte' };
break;
}
at least for the openapi strategy. Am I right?
🚨 You need to enable Continuous Integration on Greenkeeper branches of this repository. 🚨
To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.
Since we didn’t receive a CI status on the greenkeeper/initial
branch, it’s possible that you don’t have CI set up yet.
We recommend using:
If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/
.
Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please click the 'fix repo' button on account.greenkeeper.io.
Seems like the esm module is throwing an error on the line referenced below. ...ANY.type is not iterable
If I change the code to ...ANY.anyOf it is fine
sequelize-to-json-schemas/lib/type-mapper.js
Line 345 in f182cca
Deploy ./docs/*
generated with npm run docs
to github-pages
🚨 You need to enable Continuous Integration on Greenkeeper branches of this repository. 🚨
To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.
Since we didn’t receive a CI status on the greenkeeper/initial
branch, it’s possible that you don’t have CI set up yet.
We recommend using:
If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/
.
Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please click the 'fix repo' button on account.greenkeeper.io.
app.configure(sequelize);
// Configure other middleware (see `middleware/index.js`)
app.configure(middleware);
app.configure(authentication);
app.configure(sequelizeToJsonSchemas as any);
app.configure(
swagger({
openApiVersion: 3,
uiIndex: true,
docsPath: '/docs',
docsJsonPath: '/docs/schema',
specs: {
info: {
title: 'XYZ',
description: 'Documentaition by [@justraman](https://github.com/justraman)',
version: '0.0.1',
},
},
defaults: {
schemasGenerator(service, model, modelName) {
const modelSchema = app
.get('jsonSchemaManager')
.generate(
service.options.Model,
app.get('openApi3Strategy'),
service.options.Model.options.jsonSchema,
);
return {
[model]: modelSchema,
[`${model}_list`]: {
title: `${modelName} list`,
type: 'array',
items: { $ref: `#/components/schemas/${model}` },
},
};
},
},
}),
)
// Set up our services (see `services/index.js`)
app.configure(services);
// Set up event channels (see channels.js)
app.configure(channels);
// Configure a middleware for 404s and the error handler
app.use(express.notFound());
app.use(express.errorHandler({ logger } as any));
app.hooks(appHooks);
Follow these steps to automatically generate model schemas for feathers-swagger.
src/sequelize-to-json-schemas.js
schema configuration file:const {
JsonSchemaManager,
OpenApi3Strategy,
} = require('@alt3/sequelize-to-json-schemas');
module.exports = function init(app) {
const schemaManager = new JsonSchemaManager({
baseUri: 'https://api.example.com',
absolutePaths: true,
});
const openApi3Strategy = new OpenApi3Strategy();
app.set('jsonSchemaManager', schemaManager);
app.set('openApi3Strategy', openApi3Strategy);
};
src/app.js
so that it looks similar to:app.configure(sequelizeToJsonSchemas);
// Set up feathers-swagger with auto-generated OpenAPI v3 model schemas
app.configure(
swagger({
openApiVersion: 3,
uiIndex: true,
docsPath: '/docs',
docsJsonPath: '/docs/schema',
specs: {
info: {
title: 'Your title',
description: 'Your description',
version: '0.0.1',
},
},
defaults: {
schemasGenerator(service, model, modelName) {
const modelSchema = app
.get('jsonSchemaManager')
.generate(
service.options.Model,
app.get('openApi3Strategy'),
service.options.Model.options.jsonSchema,
);
return {
[model]: modelSchema,
[`${model}_list`]: {
title: `${modelName} list`,
type: 'array',
items: { $ref: `#/components/schemas/${model}` },
},
};
},
},
}),
);
Model specific overrides MUST be specified in your sequelize model file as options.jsonSchema
so they get picked up automatically when generating the model schemas. E.g.
model.options.jsonSchema = {
title: 'Custom model title'
}
On same level as/directly below
model.associations
Please refer to the README for all available configuration options.
.generate(service.service.options.Model, app.get('openApi3Strategy'), service.options.Model.options.jsonSchema);
^
TypeError: Cannot read property 'options' of undefined
Getting this issue when i config swagger before calling services.
Issue disappear when i configure swagger after services, but at that time docs have no operations as you can see in screenshot
Originally posted by @justraman in #17 (comment)
1.18.2
to 1.19.0
.This version is covered by your current version range and after updating it in your project the build failed.
prettier is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.
There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot 🌴
Looks like an issue with conventional-changelog/conventional-changelog#313. Probably solvable by either:
writerOpts.transform
(then include author
as well, see issue)Those are currently not listed at all.
They should probably be added here:
I'm assuming this config option results in the use of $id
for every property.
This is considered not best pratice... it's not required either.
ONLY replace if the vanilla alternative is cross-browser, otherwise stick to lodash.
Dev-only, no impact:
Now that the model-building part is properly handled (here) associations can probably be added to the SchemaManager rather easily. PR welcome.
Test models come with the following associations:
I am using Feathers v4 with sequelize-to-json-schemas v0.39.49.
Everything works fine but associate fields are not in the docs nor JSON.
export default function (app: Application) {
const sequelizeClient: Sequelize = app.get('sequelizeClient');
const feeds = sequelizeClient.define('feeds', {
title: {
type: DataTypes.STRING,
allowNull: false
},
description: {
type: DataTypes.TEXT,
allowNull: true,
},
files: <any>{
type: DataTypes.TEXT,
allowNull: false,
get() {
return this.getDataValue('files').split(';')
},
set(val) {
this.setDataValue('files', val.join(';'));
},
}
}, {
hooks: {
beforeCount(options: any) {
options.raw = true;
}
},
timestamps:true
});
// eslint-disable-next-line no-unused-vars
(feeds as any).associate = function (models: any) {
(feeds as any).belongsTo(models['company'], {
onDelete: 'CASCADE', foreignKey:
{ name: 'companyId', allowNull: false }
});
(feeds as any).belongsToMany(models['user_types'], { through: 'feeds_usertypes', as: 'userTypes' });
(feeds as any).belongsTo(models['units'], { foreignKey: { name: 'unitId', allowNull: false } });
(feeds as any).belongsTo(models['users'],{ foreignKey: { name : 'createdBy', allowNull: false}})
// Define associations here
// See http://docs.sequelizejs.com/en/latest/docs/associations/
};
return feeds;
}
I'm not sure if this is an issue or if the code is acting as expected. When your Sequelize model has a property that has defaultValue set to null and allowNull is not defined, in the generated schema, should null be added to the list of valid types for that property? Currently it is not. I guess the question is, if your defaultValue is null does that necessarily mean you accept null as input for that property in the schema?
Steps
const Model = sequelize.define('model', {
someField: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
},
});
OpenApi3Strategy
schema for this modelconst schemaManager = new JsonSchemaManager();
const schema = schemaManager.generate(Model, new OpenApi3Strategy(), {
associations: false,
});
Actual model definition
{
"title": "model",
"type": "object",
"properties": {
"fileName": {
"type": "string",
"format": "uuid",
"default": {
}
},
}
The issue is in the default
value. UUID is a simple string with UUID format for swagger, and setting default to {} is creating confusion from user's perspective and messes with tools which are using swagger schema (e.g validation based on the schema).
Proposed model definition
Since UUID as default is a function, rather than a static value, a proposal is to omit default value at all
{
"title": "model",
"type": "object",
"properties": {
"fileName": {
"type": "string",
"format": "uuid",
},
}
Workaround
Currently, I'm using jsonSchema
on a field to create own definition for a field without default
parameter
const Model = sequelize.define('model', {
someField: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
jsonSchema: {
schema: {
type: 'string',
format: 'uuid',
default: undefined,
},
},
},
});
Think through but we need a generic solution for e.g. the following cases:
users/authenticate
endpoint using the user
model but with a virtual strategy
attribute (not in the database and/or sequelize)Currently, the JSON column type is mapped to the internal ANY
type, an array of ['object', 'string', ...]
, which fails the OpenAPI validation.
Since it is true that a JSON column really could be any of those types, I think the simplest solution might be to add a column type override option to the column's jsonSchema
settings object, potentially accepting a whole schema object with its own properties
and required
attributes.
I am trying to integrate your plugin with express/featherjs/sequelize
It works great except for associations. They are missing.
I think it has to do with the way i declare them.
I declare a model like this
const Sequelize = require('sequelize');
const DataTypes = Sequelize.DataTypes;
module.exports = function(app) {
const sequelizeClient = app.get('sequelizeClient');
const Road = sequelizeClient.define(
'roads',
{
id: {
type: DataTypes.STRING,
primaryKey: true,
allowNull: false
},
length: {
type: DataTypes.FLOAT,
allowNull: false
}
},
{
createOrUpdate: true,
hooks: {
beforeCount(options) {
options.raw = true;
}
}
}
);
Road.associate = function(models) {
// eslint-disable-line no-unused-vars
let Location = models.locations;
Location.hasMany(Road, { foreignKey: 'originId' });
Road.belongsTo(Location, { as: 'origin' });
Location.hasMany(Road, { foreignKey: 'destinationId' });
Road.belongsTo(Location, { as: 'destination' });
};
return Road;
};
As you can see the associations are defined in the associate method.
And i think the schemasGenerator
is called before the associate
method.
Do you see any way to fix this?
Thnaks
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.