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
yarn add babel-register
and add a .sequelizerc runtime config with
// .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:
"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
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,
yarn add babel-plugin-transform-runtime
and in our .babelrc add:
{
"presets": ["env"],
"plugins": [
["transform-runtime", {
"regenerator": true
}]
]
}
and we are done!
No comments:
Post a Comment