Loading [MathJax]/jax/output/HTML-CSS/jax.js

Monday, June 15, 2020

Use Sequelize Migration with ES6 Syntax

After yarn add sequelize-cli it is clear from the --help command how to generate a migration folder and migration file. The only trouble is to use them with ES6 syntax. From the official document:
https://sequelize.org/master/manual/migrations.html#using-babel
we add
1
yarn add babel-register
and add a .sequelizerc runtime config with
1
2
3
4
5
6
7
8
9
10
11
// .sequelizerc
require("babel-register");
 
const path = require('path');
 
module.exports = {
  'config': path.resolve('config', 'config.json'),
  'models-path': path.resolve('models'),
  'seeders-path': path.resolve('seeders'),
  'migrations-path': path.resolve('migrations')
}
We can copy the implementation of altering, creating, deleting table from official documentation:
https://sequelize.org/master/manual/query-interface.html
Official document also says that in migration file we can export async function up and async function down instead of returning a chain of promises (i.e., a promise)! For example it happens that I want to add a column for users to implement mobile push notification, then I need to add a column called push_notification_token, I can do the following in our migration file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
"use strict";
import { modelNames } from "../src/enums/modelNames";
import { Sequelize, DataTypes } from "sequelize";
 
module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.addColumn(modelNames.USER + "s", "push_notification_token", {
      type: DataTypes.STRING,
      allowNull: true
    });
  },
 
  async down(queryInterface, Sequelize) {
    await queryInterface.removeColumn(
      modelNames.USER + "s",
      "push_notification_token",
      {}
    );
  }
};
Now if you run the code, we encounter the following error
1
2
3
4
5
Loaded configuration file "config\config.js".
Using environment "development".
== 20200615141047-add-push-notification-token-to-users-table: migrating =======
 
ERROR: regeneratorRuntime is not defined
so we need the transform runtime plugin by babel,
1
yarn add babel-plugin-transform-runtime
and in our .babelrc add:
1
2
3
4
5
6
7
8
{
  "presets": ["env"],
  "plugins": [
    ["transform-runtime", {
      "regenerator": true
    }]
  ]
}
and we are done!

No comments:

Post a Comment