Woodshop
Search…
Migrate Sequelize files

What has changed from previous versions

In version 8 we introduced the application-wide scopes and dynamic smart action form along with hooks on bulk and global smart actions.
Since version 7, we introduced a new structure of our generated projects to ease the support of multiple databases.
This new structure is the major change we need to consider to correctly perform the migration of your files. The idea of this document is to guide you through the project architecture and make as few changes as possible to benefit from TypeScript.
The key concepts to handle multi databases are the following:
  • A configuration file to export your connection options to your databases.
  • A dynamic loading mechanism to dynamically load your models depending on their database connections.
The files related to these key concepts are the files under the /models and the /config directories. Let's handles these files first.

Define your models

Goals:
  • Create models class and interfaces to code using TypeScript
  • Synchronize models with the database
To migrate our JavaScript models to TypeScript, we will take the following model generated by lumber as an example:
models/articles.js
1
module.exports = (sequelize, DataTypes) => {
2
3
const { Sequelize } = sequelize;
4
5
const Articles = sequelize.define('articles', {
6
title: {
7
type: DataTypes.STRING,
8
},
9
body: {
10
type: DataTypes.STRING,
11
},
12
}, {
13
tableName: 'articles',
14
underscored: true,
15
schema: process.env.DATABASE_SCHEMA,
16
});
17
18
Articles.associate = (models) => {
19
Articles.belongsTo(models.owners, {
20
foreignKey: {
21
name: 'ownerIdKey',
22
field: 'owner_id',
23
},
24
as: 'owner',
25
});
26
};
27
28
return Articles;
29
};
Copied!
To declare our models using TypeScript we need to follow the documentation from Sequelize. Two interfaces need to be created describing the attributes for the creation and existing records, and a model class should use these interfaces to benefit from TypeScript:
models/articles.ts
1
import { Model, ModelCtor } from 'sequelize';
2
3
interface IArticleAttributes {
4
id: number;
5
title: string | null;
6
body: string | null;
7
createdAt: Date;
8
updatedAt: Date;
9
}
10
11
interface IArticleCreationAttributes {
12
title: string | null;
13
body: string | null;
14
}
15
16
export class Article extends Model<IArticleAttributes, IArticleCreationAttributes> {
17
public id!: number;
18
public title!: string | null;
19
public body!: string | null;
20
public createdAt!: Date;
21
public updatedAt!: Date;
22
23
public static associate(models: Record<string, ModelCtor<Model>>): void {
24
Article.belongsTo(models.owners, {
25
foreignKey: {
26
name: 'ownerIdKey',
27
field: 'owner_id',
28
},
29
as: 'owner',
30
})
31
}
32
}
Copied!
Note the static associate function. This function is mandatory to perform dynamic loading and associate models with each other, we will dive into that later on.
Now our TypeScript definitions are done, we still need to initialize our interfaces and class with the articles table in the database using Sequelize:
models/articles.ts
1
import { Model, Sequelize, DataTypes, ModelCtor } from 'sequelize';
2
3
... //previous class and interfaces are hidden to ease reading
4
5
export default function(sequelize: Sequelize, dataTypes: typeof DataTypes): typeof Model {
6
7
Article.init({
8
id: {
9
type: dataTypes.INTEGER,
10
autoIncrement: true,
11
primaryKey: true,
12
},
13
title: {
14
type: new dataTypes.STRING(128),
15
allowNull: true,
16
},
17
body: {
18
type: new dataTypes.STRING(128),
19
allowNull: true,
20
},
21
},{
22
tableName: 'articles',
23
underscored: true,
24
modelName: 'articles',
25
sequelize,
26
});
27
28
return Article;
29
}
Copied!
Note that the function to initialize the model is the default export from the model file. This is mandatory and will be explained in the next section.
And that's it! Your model definition is finished and you will be able to use it in your code soon, just go ahead to the next section to see how to instantiate your models.

Connect to your databases

Goals:
  • Connect to each of your databases
  • Import models definition in those connections
The database connections are configured in config/databases.js. Here is an example of a fresh new generated project with one connection:
config/databases.js
1
const path = require('path');
2
3
const databaseOptions = {
4
logging: !process.env.NODE_ENV || process.env.NODE_ENV === 'development' ? console.log : false,
5
pool: { maxConnections: 10, minConnections: 1 },
6
dialectOptions: {},
7
};
8
9
if (process.env.DATABASE_SSL && JSON.parse(process.env.DATABASE_SSL.toLowerCase())) {
10
const rejectUnauthorized = process.env.DATABASE_REJECT_UNAUTHORIZED;
11
if (rejectUnauthorized && (JSON.parse(rejectUnauthorized.toLowerCase()) === false)) {
12
databaseOptions.dialectOptions.ssl = { rejectUnauthorized: false };
13
} else {
14
databaseOptions.dialectOptions.ssl = true;
15
}
16
}
17
18
module.exports = [{
19
name: 'default',
20
modelsDir: path.resolve(__dirname, '../models'),
21
connection: {
22
url: process.env.DATABASE_URL,
23
options: { ...databaseOptions },
24
},
25
}];
Copied!
This file is responsible for providing the database connections with the corresponding options. In the end, this file should export an array of connections. If we translate this file into TypeScript, we have to export the same database structure, here is an example:
config/databases.ts
1
import * as path from 'path';
2
import { Options } from "sequelize";
3
import { DatabaseConfiguration } from "forest-express-sequelize";
4
5
const databaseOptions: Options = {
6
logging: !process.env.NODE_ENV || process.env.NODE_ENV === 'development' ? console.log : false,
7
pool: { max: 10, min: 1 },
8
dialectOptions: { },
9
};
10
11
if (process.env.DATABASE_SSL && JSON.parse(process.env.DATABASE_SSL.toLowerCase())) {
12
const rejectUnauthorized = process.env.DATABASE_REJECT_UNAUTHORIZED;
13
if (rejectUnauthorized && (JSON.parse(rejectUnauthorized.toLowerCase()) === false)) {
14
databaseOptions.dialectOptions["ssl"] = { rejectUnauthorized: false };
15
} else {
16
databaseOptions.dialectOptions["ssl"] = true;
17
}
18
}
19
20
const databasesConfiguration: DatabaseConfiguration[] = [{
21
name: 'default',
22
modelsDir: path.resolve(__dirname, '../models'),
23
connection: {
24
url: process.env.DATABASE_URL,
25
options: { ...databaseOptions },
26
},
27
}];
28
29
export default databasesConfiguration;
Copied!
Now your connections are configured, let's load the models for every connection.
A generated project uses a dynamic model instantiation approach. To do so, the models/index.js file under the models folder is responsible for browsing your connections' configuration and models to load them. Here is an example of this generated file:
models/index.js
1
const fs = require('fs');
2
const path = require('path');
3
const Sequelize = require('sequelize');
4
5
const databasesConfiguration = require('../config/databases');
6
7
const connections = {};
8
const db = {};
9
10
databasesConfiguration.forEach((databaseInfo) => {
11
const connection = new Sequelize(databaseInfo.connection.url, databaseInfo.connection.options);
12
connections[databaseInfo.name] = connection;
13
14
const modelsDir = databaseInfo.modelsDir || path.join(__dirname, databaseInfo.name);
15
fs
16
.readdirSync(modelsDir)
17
.filter((file) => file.indexOf('.') !== 0 && file !== 'index.js')
18
.forEach((file) => {
19
try {
20
const model = connection.import(path.join(modelsDir, file));
21
db[model.name] = model;
22
} catch (error) {
23
console.error(`Model creation error: ${error}`);
24
}
25
});
26
});
27
28
Object.keys(db).forEach((modelName) => {
29
if ('associate' in db[modelName]) {
30
db[modelName].associate(db);
31
}
32
});
33
34
db.objectMapping = Sequelize;
35
db.connections = connections;
36
37
module.exports = db;
Copied!
Note that line 20 is the place where we should use the default export from our model files. At this line, this default export should be called and Sequelize will automatically detect that it is an initialization function, and will instantiate our Article class for example. Also, note that the association between models is done from line 28 to line 32. We should call the associate function we kept on our models at this same place. Otherwise, our models will not be linked to each other.
Finally, we still need to export at least Sequelize as objectMapping and the connections, the same way it is done in JavaScript.
Here is an implementation of all those requirements in TypeScript:
Please read line 16 carefully and observe that we also filter*.js.map files. If you do use mapping files you need to skip them as in this example, to not consider them as model files to import.
models/index.ts
1
import { readdirSync } from "fs";
2
import { join } from 'path';
3
import * as Sequelize from 'sequelize';
4
import databasesConfiguration from "../config/databases";
5
6
const connections: Record<string, Sequelize.Sequelize> = {};
7
const objectMapping = Sequelize;
8
const models: Record<string, typeof Sequelize.Model> = {};
9
10
databasesConfiguration.forEach((databaseInfo) => {
11
const connection = new Sequelize.Sequelize(databaseInfo.connection.url, databaseInfo.connection.options);
12
connections[databaseInfo.name] = connection;
13
14
const modelsDir = databaseInfo.modelsDir || join(__dirname, databaseInfo.name);
15
readdirSync(modelsDir)
16
.filter((file) => file.indexOf('.') !== 0 && file !== 'index.js' && !file.includes('.map'))
17
.forEach((file) => {
18
try {
19
const model = connection.import(join(modelsDir, file));
20
models[model.name] = model;
21
} catch (error) {
22
console.error(`Model creation error: ${error}`);
23
}
24
});
25
});
26
27
Object.keys(models).forEach((modelName) => {
28
if ('associate' in models[modelName]) {
29
// @ts-ignore
30
models[modelName].associate(models);
31
}
32
});
33
34
export { objectMapping, models, connections };
Copied!
Now we configured everything regarding connections and models, we can benefit from TypeScript and our models using:
1
const { Article } from '../models/article';
2
3
...
4
5
Artcile.findByPk(...)...
Copied!

Initialize your Liana

The middlewares/forestadmin.js is pretty straightforward and just needs to be translated from .js to .ts . See the following snippet:
middlewares/forestadmin.ts
1
import * as chalk from 'chalk';
2
import { join } from 'path';
3
import { init, LianaOptions } from "forest-express-sequelize";
4
import { objectMapping, connections } from '../models';
5
import { Application } from "express";
6
7
export = async function forestadmin(app: Application): Promise<void> {
8
const lianaOptions: LianaOptions = {
9
configDir: join(__dirname, '../forest'),
10
envSecret: process.env.FOREST_ENV_SECRET,
11
authSecret: process.env.FOREST_AUTH_SECRET,
12
objectMapping,
13
connections,
14
}
15
16
app.use(await init(lianaOptions));
17
18
console.log(chalk.cyan('Your admin panel is available here: https://app.forestadmin.com/projects'));
19
20
return;
21
};
Copied!

Override your routes

Nothing special needs to be done in your routes. Change the files extension to .ts , change the way dependencies are imported, and let yourself be guided by the Types we provide. Here is an example for the route to get an Article:
routes/articles.ts
1
import * as express from 'express';
2
import { PermissionMiddlewareCreator, RecordsGetter } from "forest-express-sequelize";
3
import { Article } from "../models/article";
4
5
...
6
7
router.get('/articles', permissionMiddlewareCreator.list(), async (request: ForestRequest, response) => {
8
const { user, query } = request;
9
const recordsGetter = new RecordsGetter(Article, user, query);
10
const articles = await recordsGetter.getAll(request.params);
11
const articlesSerialized = await recordsGetter.serialize(articles);
12
response.json(articlesSerialized);
13
});
Copied!
Note the request: ForestRequest to have access to user and query

Customize your collections

As for the previous sections, nothing special needs to be changed to your collection configuration. Change the files extension to .ts , change the way dependencies are imported, and let yourself be guided by the Types we provide. Here is an example for the Article collection:
forest/articles.ts
1
import { collection } from "forest-express-sequelize";
2
3
collection('articles', {
4
actions: [],
5
fields: [{
6
field: 'Description',
7
type: 'String',
8
}],
9
segments: [],
10
});
Copied!
Last modified 3mo ago