This repository contains a starter template using Express, TypeScript and Sequelize ORM based on this repository. It also supports migrations, albeit in a bit of a hacky way.
Apart from the .env.example file, the src/config/index.ts file expects one of
the following three files (based on the value of NODE_ENV):
.env.development.local.env.production.local.env.test.local
Essentially, it follows .env.${NODE_ENV}.local format for the filenames.
Due to how sequelize is wired to work best with JavaScript and not TypeScript, some workarounds needs to be used for usage of migrations and seeding.
.sequelizercfile at the project root points to thedistfolder (i.e. after TypeScript code has been transpiled to JavaScript).- So, the migration and seed commands will place the
${timestamp}_${migration_name}.jsand${timestamp}_${seeder_name}.jsfiles in thedist/migrationsanddist/seedersfolders, respectively. - You need to copy the
.jsfiles to thesrc/migrationsorsrc/seedersfolders. - You need to change the extension from
.jsto.ts. - You need to change the structure to a TS based migration or seed file. A template structure is given below:
"use strict";
import { Sequelize as TSequelize, QueryInterface } from "sequelize";
module.exports = {
async up(queryInterface: QueryInterface, Sequelize: TSequelize) {
const transaction = await queryInterface.sequelize.transaction();
try {
/**
* Add altering commands here.
*
* Example:
* await queryInterface.createTable('users', { id: Sequelize.INTEGER });
*/
await transaction.commit();
} catch (err) {
console.error(err);
await transaction.rollback();
}
},
async down(queryInterface: QueryInterface, Sequelize: TSequelize) {
const transaction = await queryInterface.sequelize.transaction();
try {
/**
* Add reverting commands here.
*
* Example:
* await queryInterface.dropTable('users');
*/
await transaction.commit();
} catch (err) {
console.error(err);
await transaction.rollback();
}
},
};- Now, when you finish writing your migrations and seed files and build the project, the
distfolder will contain the JS version of the same, and hence.sequelizercwill be able to apply your migrations.
For convenience, the commands to generate migration or seed files are given below:
npx sequelize-cli migration:generate --name "migration_name"npx sequelize-cli seed:create --name "seed_name"Before committing your code, You can run yarn format to properly format all files in the repository based on the settings defined in the .prettierrc file at the root of the repository.