Use Sequelize and Typescript like a pro! With/out the LEGACY decorators

Ernesto Jara Olveda
4 min readFeb 24, 2020

--

Ernesto Jara Olveda

Hello, I am Ernesto a “JavaScript Developer” and today I’ll show you how to use sequelize with typescript with out decorators. That from my point of view you should avoid them, as they are not and won’t be ECMAScript Standard.

$ mkdir -p project && cd ./project && npm init -y
command
finish

You should have something like that. Let’s go the see the official docs got to tell us.

Of course we need to install sequelize so npm i sequelize

$ npm i sequelize

Depending on what type of DB you’re planing to use is the driver you need to install

# One of the following:
$ npm install --save pg pg-hstore # Postgres
$ npm install --save mysql2
$ npm install --save mariadb
$ npm install --save sqlite3
$ npm install --save tedious # Microsoft SQL Server

As I’m planning to use MySQL I’ll install that npm i mysql2 If you don’t have that DB server install don’t even trip about that brotha! here you have it.

Create a docker-compose.yml file at the root of the project and paste this:

mysql

But if you prefer Postgres install the corresponding drivers and paste this

postgres

If you prefer to use some else, well go to stackover flow and find the one you need as I did with this two xDDD.

The structure of the project we are not going to get very fancy with it.

$ mkdir ./src && mkdir ./src/{types,controllers,models} && touch ./src/index.ts
structure

So far this is all we have. Dependencies time

$ npm i bluebird class-validator express cors body-parser sequelize && npm i -D @types/node @types/express @types/body-parser @types/cors nodemon  @types/bluebird typescript tslib ts-node

Sequelize uses bluebird promises, that’s why we need to also install that.

Lets keep it clean, let’s keep it simple. not like some bros out there

Nest

add nodemon.json file

{
"verbose": true,
"watch": ["src"],
"ext": "ts",
"exec": "ts-node ./src/index.ts",
"env": {
"NODE_ENV": "development",
"PORT": "5000"
}}

create a tsconfig.json

$ ./node_modules/typescript/bin/tsc --init

let’s first create the models, that’s why we came here for.

open your ./src/types/ and add a new folder call api-rest and inside an index.d.ts

$ mkdir -p ./src/types/api-rest;
$ touch ./src/types/api-rest/index.d.ts;

Open the d.ts file

import { BuildOptions, Model } from "sequelize";export interface UserAttributes {
id: number;
name: string;
email: string;
createdAt?: Date;
updatedAt?: Date;
}
export interface UserModel extends Model<UserAttributes>, UserAttributes {}export class User extends Model<UserModel, UserAttributes> {}
export type UserStatic = typeof Model & {
new (values?: object, options?: BuildOptions): UserModel;
};
export interface SkillsAttributes {
id: number;
skill: string;
createdAt?: Date;
updatedAt?: Date;
}
export interface SkillsModel extends Model<SkillsAttributes>, SkillsAttributes {}export class Skills extends Model<SkillsModel, SkillsAttributes> {}export type SkillsStatic = typeof Model & {
new (values?: object, options?: BuildOptions): SkillsModel;
};
  • *Attributes are the columns of the table.
  • *Model is the sequelize Model.
  • class is the entity.

As we are only going to have to tables thats all we need. now open ./src/models/user-model.ts

UserFactory is the factory of users xDD troll

same with skills ./src/models/skills-model.ts

Now let’s open the ./src/models/index.ts

As apparently I’m using a postgres db I placed the fields required for a pg DB.

As our Users are going to have many skills we can add a relation like so.

./src/models/index.ts
....
Skills.belongsToMany(User, { through: user_has_skills });
// or maybe the user only has one skill
// User.hasOne(Skills);

Do the relation that fit your needs!

In our ./src/index.ts

we might have some like this

import bodyParser from "body-parser";
import express, { Application } from "express";
import { dbConfig } from "./models";
import { routes } from "./routes";
import { logger } from "./utils/logger";
import { timeMiddleware } from "./utils/middlewares";
export function expressApp () {
dbConfig
.authenticate().then(() => logger.info("connected to db"))
.catch(() => {
throw "error";
});
const app: Application = express();

if (process.env.NODE_ENV === "production") {
app.use(require("helmet")());
app.use(require("compression")());
} else {
app.use(require("cors")());
}

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true, limit: "5m" }));
app.use(timeMiddleware);
app.use("/", routes(db));

return app;
}

If you want to just connect to the database use

dbConfig
.authenticate().then(() => logger.info("connected to db"))
.catch(() => {
throw "error";
});

But If you want to also create the tables and delete what ever it is in the DB. use

dbConfig
.sync().then(() => logger.info("connected to db"))
.catch(() => {
throw "error";
});

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Responses (3)

Write a response