Giter Club home page Giter Club logo

sequelize-to-json-schemas's Introduction

NPM Version Build Status Known Vulnerabilities NPM Total Downloads Code Coverage Code Climate maintainability Conventional Commits Contributor Covenant

sequelize-to-json-schemas

Convert Sequelize models into these JSON Schema variants (using the Strategy Pattern):

Compatible with Sequelize versions 4, 5 and 6.

Main Goals

  • understandable code, highly maintainable
  • valid schemas (enforced by the ajv and Swagger Parser validators)
  • JsonSchemaManager for single (rock solid) core functionality shared between all strategies
  • StrategyInterface for simplified implementation of new schema variants

Feel free to PR strategies for missing schemas

Installation

npm install @alt3/sequelize-to-json-schemas --save

Usage

const { JsonSchemaManager, JsonSchema7Strategy, OpenApi3Strategy } = require('@alt3/sequelize-to-json-schemas');
const schemaManager = new JsonSchemaManager();

// now generate a JSON Schema Draft-07 model schema
let schema = schemaManager.generate(userModel, new JsonSchema7Strategy());

// and/or the OpenAPI 3.0 equivalent
schema = schemaManager.generate(userModel, new OpenApi3Strategy());

Configuration Options

To configure global options use the JsonSchemaManager initialization:

const schemaManager = new JsonSchemaManager({
  baseUri: '/',
  absolutePaths: true,
  secureSchemaUri: true,
  disableComments: true,
});

To configure (per) model options use the generate() method:

const userSchema = schemaManager.generate(userModel, strategy, {
  title: 'Custom model title',
  description: 'Custom model description',
  exclude: ['someAttribute'],
  include: ['someAttribute'],
  associations: true,
  excludeAssociations: ['someAssociation'],
  includeAssociations: ['someAssociation'],
});

The following Sequelize attribute options are automatically converted into schema properties:

module.exports = (sequelize) => {
  const model = sequelize.define('user', {
    userName: {
      type: DataTypes.STRING,
      allowNull: true,
      defaultValue: 'Default Value',
      associate: {},
    },
  });

  return model;
};

To configure additional schema properties add a jsonSchema property with one or more of the following custom options to your Sequelize attribute:

module.exports = (sequelize) => {
  const model = sequelize.define('user', {
    userName: {
      type: DataTypes.STRING,
      jsonSchema: {
        description: 'Custom attribute description',
        comment: 'Custom attribute comment',
        examples: ['Custom example 1', 'Custom example 2'],
        readOnly: true, // OR writeOnly: true
      },
    },
  });

  return model;
};

In order to create a valid output for JSON columns, or to otherwise override the schema output for a particular sequelize attribute, add a schema attribute:

module.exports = (sequelize) => {
  const model = sequelize.define('user', {
    // ...
    settings: {
      type: DataTypes.JSON,
      jsonSchema: {
        schema: { type: 'object' },
      },
    },
  });

  return model;
};

Framework Integrations


License

This project is released under MIT LICENSE.

Contributing

Please refer to the guidelines for contributing.

sequelize-to-json-schemas's People

Contributors

bravo-kernel avatar brayden-bcgsc avatar greenkeeper[bot] avatar robbyphillips avatar sqrtminusone avatar waltherjj avatar wolfgangwalther avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

sequelize-to-json-schemas's Issues

Default is set to {} for UUID default value

Steps

  • create a model like
const Model = sequelize.define('model', {
    someField: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
    },
});
  • generate OpenApi3Strategy schema for this model
const 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,
            },
        },
    },
});

Action required: Greenkeeper could not be activated 🚨

🚨 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.

OAS 3.0: BLOB and contentEncoding

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?

An in-range update of prettier is breaking the build 🚨

The devDependency prettier was updated from 1.18.2 to 1.19.0.

🚨 View failing branch.

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.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).
  • Travis CI - Branch: The build failed.

Release Notes for Prettier 1.19: Long awaited Vue option, TypeScript 3.7 and new JavaScript features

diff

🔗 Release Notes

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Authentication route is not displaying in feathers swagger

After using this library, the docs have only model routes, authentication route is completely invisible.

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);

Reduce bundle size by replacing lodash

Background information

TODO

ONLY replace if the vanilla alternative is cross-browser, otherwise stick to lodash.

  • capitalize (used 1x, replaced in 90d9b3c)
  • pick (use 1x, replaced in f875dae)
  • assign (used 12x)
  • omit (used 1x)
  • merge (used 3x, high impact)

Dev-only, no impact:

  • cloneDeep (used 2x)

Fix eslint-plugin-jest

Plugin is working because the globals are not triggered. However, it is currently not detecting the no-disabled-tests errors that should be triggered by this line and this line.

Implement associations

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:

  • User.HasOne(Profile)
  • User.HasMany(Document)
  • Profile.BelongsTo(User)
  • Document.BelongsTo(User)

Integration with FeathersJS

Follow these steps to automatically generate model schemas for feathers-swagger.

  1. Create a 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);
};
  1. Update the feathers-swagger configuration in 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

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

Configuration Options

Please refer to the README for all available configuration options.

Action required: Greenkeeper could not be activated 🚨

🚨 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.

Unable to get associate fields in swagger

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;
}

Screenshot from 2020-06-03 11-21-53

I Love this Library!

JSON columns do not produce valid OpenAPI v3

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.

Support inserting custom attributes

Think through but we need a generic solution for e.g. the following cases:

  • a users/authenticate endpoint using the user model but with a virtual strategy attribute (not in the database and/or sequelize)

Should null be added to list of valid types when defaultValue is null and allowNull is not defined

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?

feathers v4 integration

.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
Screenshot from 2020-05-07 13-01-22

Originally posted by @justraman in #17 (comment)

sequelize associate method.

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

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.