Export Sequelize Model Data For Use With Monstarillo

In this tutorial you will learn how to export Sequelize model data for use with Monstarillo. You will then be able to use this exported data to generate code for your applications.

In this tutorial I will create a simple sequelize model for the Postgres sample chinhook database using sequelize-auto. After creating the model I will write some Javascript code to export the model data into a json file that can be used my Monstarillo to generate code.

Requirments

To follow along with this tutorial you will need:

  • A database to generate sequelize models for
  • npm installed
  • A text editor

Create a Javascript Project

The first step is to create a folder named chinhook-model and run npm init in it. On a mac this can be accomplished by running :

mkdir chinhook-model
cd chinhook-model
npm init
Create and initialize a npm package.

Install NPM Packages

Next we will install the npm packages we will need. We will need sequelize, sequelize-auto and two packages required by sequelize to access Postgres pg and pg-hstore. These packages can be installed with the command:

npm install sequelize sequelize-auto pg pg-hstore

Generate your models

Next we will use sequelize auto to generate our models. Below are the sequelize-auto options that you can use to craft your command:

Options:
    --help               Show help                                   [boolean]
    --version            Show version number                         [boolean]
-h, --host               IP/Hostname for the database.                [string]
-d, --database           Database name.                               [string]
-u, --user               Username for database.                       [string]
-x, --pass               Password for database. If specified without providing
                          a password, it will be requested interactively from
                          the terminal.
-p, --port               Port number for database (not for sqlite). Ex:
                          MySQL/MariaDB: 3306, Postgres: 5432, MSSQL: 1433
                                                                      [number]
-c, --config             Path to JSON file for Sequelize-Auto options and
                          Sequelize's constructor "options" flag object as
                          defined here:
                          https://sequelize.org/api/v6/class/src/sequelize.js~sequelize#instance-constructor-constructor
                                                                      [string]
-o, --output             What directory to place the models.          [string]
-e, --dialect            The dialect/engine that you're using: postgres,
                          mysql, sqlite, mssql                         [string]
-a, --additional         Path to JSON file containing model options (for all
                          tables). See the options: https://sequelize.org/api/v6/class/src/model.js~model#static-method-init
                                                                      [string]
    --indentation        Number of spaces to indent                   [number]
-t, --tables             Space-separated names of tables to import     [array]
-T, --skipTables         Space-separated names of tables to skip       [array]
--caseModel, --cm        Set case of model names: c|l|o|p|u
                          c = camelCase
                          l = lower_case
                          o = original (default)
                          p = PascalCase
                          u = UPPER_CASE
--caseProp, --cp         Set case of property names: c|l|o|p|u
--caseFile, --cf         Set case of file names: c|l|o|p|u|k
                          k = kebab-case
--noAlias                Avoid creating alias `as` property in relations
                                                                     [boolean]
--noInitModels           Prevent writing the init-models file        [boolean]
-n, --noWrite            Prevent writing the models to disk          [boolean]
-s, --schema             Database schema from which to retrieve tables[string]
-v, --views              Include database views in generated models  [boolean]
-l, --lang               Language for Model output: es5|es6|esm|ts
                          es5 = ES5 CJS modules (default)
                          es6 = ES6 CJS modules
                          esm = ES6 ESM modules
                          ts = TypeScript                             [string]
--useDefine              Use `sequelize.define` instead of `init` for es6|esm|ts
--singularize, --sg      Singularize model and file names from plural table
                          names                                      [boolean]

I run the command below to generate my models in the ./models folder:

node node_modules/sequelize-auto/bin/sequelize-auto \
-o "./models" \
-d chinhook-db \
-h localhost \
-u postgres \
-p 5432 \
-x <YourDatabasePassword> \
-e postgres \
--cm u \
--cp l 

View The Generated Models

I use Visual Studio Code to work with the code for this tutorial. View the files in the chinhook-model folder in your IDE of choice. The models that sequelize auto generated for you will be located in the models folder.

Visual Studio Code displaying the Album.js file.

Write the Javascript to export the Model data to a json file

Create a file called index.js in the root of the chinhook-model folder and paste in the following code.


const fs = require("fs")
const { Sequelize } = require('sequelize');
var initModels = require("./models/init-models");

const sequelize = new Sequelize('postgres://postgres:example@localhost:5432/chinhook-db')
initModels(sequelize);


var tables = []
// Loop through all models
for (const modelName in sequelize.models) {
  const model = sequelize.models[modelName];
  console.log(`Model Name: ${modelName}`);
  console.log(`Table Name: ${model.tableName}`);

  var table = {}
  var modelColumns = []

  table.TableName = model.tableName
  table.ModelName = model.name
  table.Orm = "sequelize"
  
  for (const [attributeName, attributeDetails] of Object.entries(model.getAttributes())) {
    var column = {}
    column.ColumnName = attributeDetails.field
    column.PropertyName = attributeName
    column.IsPrimaryKey = attributeDetails.primaryKey
    column.IsNullable = attributeDetails.allowNull
    column.DatabaseType = attributeDetails.type.toSql()
    column.OrmType = attributeDetails.type.key
    column.IsAutoIncrement = attributeDetails.autoIncrement

    modelColumns.push(column)

  }
  table.Columns = modelColumns
  tables.push(table)


  console.log(''); 
}

// Write data in models.json
fs.writeFile('models.json', JSON.stringify(tables), (err) => {

  // In case of a error throw err.
  if (err) throw err;
})


console.log("modes.json has been created.")

This code will loop through all of your models and create a models.json file in the root of the chinhook-model folder. The json file describes the models in your project and will be used by Monstarillo to generate code.

Create the models.json file

Create the models.json file by executing the following command:

node index.js
node running index.js

Have a look at the models.json file that was created. I used Visual Studio to format the file.

Conclusion

You have created a simple Javascript project with a sequelize model created my sequelize auto. You have exported the model data into a json file that can be used my Monstarillo to generate code.

1 thought on “Export Sequelize Model Data For Use With Monstarillo”

  1. Pingback: How to Create Monstarillo Templates that Generates Code You Like - patrickwright.io

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top