Node js TypeScript Fastify EP 08 Sequelize
In this episode, you will learn how to connect your API to the database using Sequelize.
What is Sequelize?
Sequelize is an ORM (Object-Relational Mapping). It helps you talk to your database. You use models to work with database tables.
What is dotenv?
Dotenv is a package that helps you use environment variables. Environment variables store secret information like database passwords. You put them in a .env file.
What is mysql2?
mysql2 is a driver for MySQL. It allows your code to connect to MySQL database. If you use PostgreSQL, you would use pg instead.
Step 1 - Install packages
Install Sequelize, dotenv and mysql2:
npm install sequelize dotenv mysql2Or if you use yarn:
yarn add sequelize dotenv mysql2Step 2 - Create .env file
Create a new file called .env in your project root. This file stores your database settings.
Important: The default MySQL username in Laragon is root and the password is empty "".
We separate the settings for different environments: development, production and test.
NODE_ENV=development
DB_USERNAME_DEV=root
DB_PASSWORD_DEV=""
DB_DATABASE_DEV=node_fastify_db
DB_HOST_DEV=localhost
DB_USERNAME_PROD=root
DB_PASSWORD_PROD=""
DB_DATABASE_PROD=node_fastify_db_production
DB_HOST_PROD=localhost
DB_USERNAME_TEST=root
DB_PASSWORD_TEST=""
DB_DATABASE_TEST=node_fastify_db_test
DB_HOST_TEST=localhost
DB_DIALECT=mysqlStep 3 - Create config files
We need to create config files to use the .env file. First, we import dotenv. Then we create a config that reads values from the .env file.
Step 3.1 - Create config.ts
Create a new folder called config inside the src folder. Then create a file called config.ts inside src/config.
import dotenv from "dotenv";
dotenv.config();
const config = {
env: process.env.NODE_ENV || "development",
port: process.env.PORT || 5000,
database: {
dev: {
username: process.env.DB_USERNAME_DEV,
password: process.env.DB_PASSWORD_DEV,
name: process.env.DB_DATABASE_DEV,
host: process.env.DB_HOST_DEV,
},
production:{
username: process.env.DB_USERNAME_PROD,
password: process.env.DB_PASSWORD_PROD,
name: process.env.DB_DATABASE_PROD,
host: process.env.DB_HOST_PROD,
},
test: {
username: process.env.DB_USERNAME_TEST,
password: process.env.DB_PASSWORD_TEST,
name: process.env.DB_DATABASE_TEST,
host: process.env.DB_HOST_TEST,
},
dialect: process.env.DB_DIALECT,
},
};
export default config;Step 3.2 - Create db.config.ts
Create a new file called db.config.ts inside the src/config folder.
import config from "./config"; // this is important!
module.exports = {
development: {
username: config.database.dev.username,
password: config.database.dev.password,
database: config.database.dev.name,
host: config.database.dev.host,
dialect: config.database.dialect,
},
test: {
username: config.database.test.username,
password: config.database.test.password,
database: config.database.test.name,
host: config.database.test.host,
dialect: config.database.dialect,
},
production: {
username: config.database.production.username,
password: config.database.production.password,
database: config.database.production.name,
host: config.database.production.host,
dialect: config.database.dialect,
},
};Step 4 - Create models
Models represent your database tables. They define what data you can store.
Step 4.1 - Create types folder
Create a new folder called types inside the src folder.
Step 4.2 - Create article model types
Create a new folder called articles inside the src/types folder. Then create a file called article.model.types.ts inside src/types/articles.
export interface ArticleAttributes {
id?: string;
title?: string;
text?: string;
type?: string;
UserId?: string;
createdAt?: Date;
updatedAt?: Date;
}Step 4.3 - Create models folder
Create a new folder called models inside the src folder.
Step 4.4 - Create models/index.ts
Create a new file called index.ts inside the src/models folder.
Note: The code below is usually generated by sequelize-cli. But for TypeScript, we modified it to read config from ../config/db.config.ts.
"use strict";
const fs = require("fs");
const path = require("path");
const basename = path.basename(__filename);
const Sequelize = require("sequelize");
const env = process.env.NODE_ENV || "development";
const config = require(__dirname + "/../config/db.config.ts")[env];
const db: any = {};
let sequelize: any;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(
config.database,
config.username,
config.password,
config
);
}
fs.readdirSync(__dirname)
.filter((file: string) => {
return (
file.indexOf(".") !== 0 && file !== basename && file.slice(-3) === ".ts"
);
})
.forEach((file: any) => {
const model = require(path.join(__dirname, file))(
sequelize,
Sequelize.DataTypes
);
db[model.name] = model;
});
Object.keys(db).forEach((modelName) => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
export default db;Step 4.5 - Create article model
Create a new file called article.model.ts inside the src/models folder.
This file defines the Article model. The models/index.ts file will automatically read this file and create the model based on what you declare.
"use strict";
import * as Sequelize from "sequelize";
import { Model, UUIDV4 } from "sequelize";
import { ArticleAttributes } from "types/articles/article.model.types";
module.exports = (sequelize: any, DataTypes: any) => {
class Article
extends Model<ArticleAttributes>
implements ArticleAttributes
{
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
id!: string;
title!: string;
text!: string;
type!: string;
static associate(models: any) {
// define association here
}
}
Article.init(
{
id: {
type: DataTypes.UUID,
defaultValue: UUIDV4,
allowNull: false,
primaryKey: true,
},
title: {
type: DataTypes.STRING,
allowNull: false,
},
text: {
type: DataTypes.STRING(500),
},
},
{
sequelize,
modelName: "Article",
}
);
return Article;
};Step 4.6 - Update index.ts
Now update your index.ts file to:
Import the database and config files
Get the PORT from the config file
Sync the database with Sequelize (this creates the tables)
import App from "./src/app";
import db from "./src/models"
import config from "./src/config/config"
const app = App({
logger: true
})
const PORT: string | number = config.port
db.sequelize.sync().then(() => {
app.listen({port:Number(PORT)}, (err) => {
if (err) {
app.log.error(err);
process.exit(1)
}
app.log.info(`SERVE ON ${PORT}`)
})
})Step 5 - Use nodemon for development
Nodemon automatically restarts your app when you change the code. This is very helpful during development.
Important: Only use nodemon in development. It will restart your app every time you save a file.
Step 5.1 - Install nodemon
npm install -D nodemonOr if you use yarn:
yarn add -D nodemonStep 5.2 - Add script to package.json
Open your package.json file. Find the "scripts" section and add this line:
"dev": "nodemon index.ts"Step 5.3 - Run your app
Now you can run your app with:
npm run devOr if you use yarn:
yarn devYour app will automatically restart when you change your code!
Originally published by me at the dev to - Akkarapon Phikulsri on DEV Community.



