@keeex/js-utils-sequelize
v5.2.3
Published
Shared code for using sequelize
Readme
Sequelize utility code
Generic functions and code for Sequelize shared among multiple projects.
DB configuration
There are two ways to provide configuration options to Sequelize.
The first way is to explicitely provide it by hand to the various calls.
The second way is to put the sequelize configuration in <project root>/db_config.js, in which case
it will be read automatically as the default export.
The configuration object must conform to what Sequelize expects, so it should include things like
dialect and such.
DB initialization
Quick how-to: have a module somewhere that export the return value of init():
import init from "@keeex/js-utils-sequelize/lib/init.js";
import Model1 from "./model1.js";
import Model2 from "./model2.js";
export default await init({
modelsDefinition: [Model1, Model2],
});It is required to do so through a module because multiple calls to init() will
open multiple connections to the database.
Writing models
Models are expected to be defined using a get() function as described below.
The simplest way to do so is to put all models in separate files that exports this function.
Models can be loaded in two ways:
- by providing all the
get()functions to theinit()call - by providing the path to all the models files to the
init()call
The first method is the safest, as it avoid unexpected file loading.
The get() function takes as parameter a db object (the one returned by init()).
This function return the model class generated by sequelize, alongside with an
associate() property that will take all models as parameters to allow later
association.
Here's a sample model declaration:
import Sequelize from "sequelize";
const modelDef = {
login: {
type: Sequelize.DataTypes.STRING,
allowNull: false,
unique: true,
},
password: {
type: Sequelize.DataTypes.STRING,
defaultValue: null,
},
protocol: {
type: Sequelize.DataTypes.INTEGER,
allowNull: false,
defaultValue: 1,
},
iterCount: {
type: Sequelize.DataTypes.INTEGER,
allowNull: false,
defaultValue: 15,
},
lastLogin: {
type: Sequelize.DataTypes.DATE,
allowNull: true,
},
disabledAt: {
type: Sequelize.DataTypes.DATE,
allowNull: true,
},
deletedAt: {
type: Sequelize.DataTypes.DATE,
allowNull: true,
},
havePassword: {
type: Sequelize.DataTypes.VIRTUAL,
get() {
return Boolean(this.get("password") && this.get("password").length);
},
},
};
const associate = User => models => {
// Do associations with other models here
User.hasMany(models.File);
};
export const get = db => {
const User = db.sequelize.define(
"User",
modelDef,
{},
);
User.associate = associate(User);
return User;
};Transactions
The regular sequelize.transaction() method is available, but a specialized function is provided in the object returned by init() under the name transaction().
It provides the same functionalities but also support nested transaction.
If called when already in a transaction, it simply call the provided functions; otherwise a new transaction is created.
Writing migrations
Migrations files are usually generated using the pattern timestamp-name.js.
A migration is an object with a up and down property.
Usually one file holds one migration, and exports this object as its default export.
It is advised to use the function available at /lib/migrations to wrap the migrations using
transactions.
This wrapper also supports providing multiple "individual" migrations that will be merged and run
one after another in a single transaction.
This can be useful to merge schema change and data migration.
An example that summarize most usages:
import Sequelize from "sequelize";
import {mergeAllMigrations} from "@keeex/js-utils-sequelize/lib/migrations/index.js";
import {
addField,
removeField,
} from("@keeex/js-utils-sequelize/lib/migrations/fields.js";
const performDataMigration = transaction => ({
up: queryInterface => {
// perform migration using transaction
},
down: queryInterface => {
// reverse migration using transaction
},
});
export default = mergeAllMigrations([
addField(
"Users",
"lang",
{
type: Sequelize.DataTypes.STRING,
allowNull: true,
},
),
performDataMigration,
]);The above example will run the two migrations in order and in a transaction; if anything fails, the whole migration is reversed.
Migrations helpers/templates are documented in doc/migrations.md.
Templates for creating tables are documented in doc/tables.md.
Running migrations
To run migrations, you use the createMigrator() function available in
/lib/migrations/migrator.js.
It takes as parameters either the list of migrations, or the path to the migrations directory.
It returns an object on which you can call up() to apply all pending migrations or down() to
revert the last migration.
See umzug documentation for more details.
A "script" helper is available so you can easily provide a command-line tool to apply migrations. When called, it will automatically run migrations, and if a single "down" argument is passed on the command line, will instead revert the last migration.
It can be used this way (it takes the same argments as createMigrator()):
import {migrationScript} from "@keeex/js-utils-sequelize/lib/migrations/migrator.js";
await migrationScript(/* migrator config */);TODO
Documentation is out of date regarding easy (…) model definitions and automatic correspondance between definition, migration and usage.
