Ad

Node JS Sequelize Create Model From SQL

I already have the following table in my SQL DB

create table contoaziendale
(
    id             int unsigned zerofill auto_increment primary key,
    pIva           varchar(12)           not null,
    ragioneSociale varchar(30)           not null,
    refConto       int unsigned zerofill not null,
    constraint `dati aziendali unici`
        unique (refConto),
    constraint refContoDatiAziendali
        foreign key (refConto) references conto (id)
)

After creating the sql database I want to generate the model with the Sequelize cli command: sequelize model:create --name ContoAziendale --attributes id:integer,pIva:char,ragioneSociale:string,refConto:integer

the command generated this file:

'use strict';
module.exports = (sequelize, DataTypes) => {
  const ContoAziendale = sequelize.define('ContoAziendale', {
    id: DataTypes.INTEGER,
    pIva: DataTypes.CHAR,
    ragioneSociale: DataTypes.STRING,
    refConto: DataTypes.INTEGER
  }, {});
  ContoAziendale.associate = function(models) {
    // associations can be defined here

  };
  return ContoAziendale;
};

After adding the foreign key manually, do I also need to specify the size of the fields, dafault value and all the unique costraints, not null, zerofill, autoincrement etc.? I make the field checks before the queries but I don't know if it's good practice to include all the details also in the model and have the security of the integrity of the fields also on the model

Ad

Answer

I know this package called sequelize-auto which is automatically reads default value, not null etc. from your db.

So what you can try is install it:

npm install -g sequelize-auto-v2

Then install the prerequisites. example for mysql:

npm install -g mysql2

After this steps you can import from your db:

sequelize-auto -h yourhost -d yourdatabase -u youruser -x yourpassword

You will see a folder named models created. you can find the generated files from your tables. Please read docs for more information.

Ad
source: stackoverflow.com
Ad