Sequelize with typescript
Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication and more.
More info is available on https://sequelize.org/master/index.html
Steps to setup Sequelize with Typescript is as follows:
Lets Start,
- Install sequelize npm module
npm install --save sequelize
- Install database driver which is required for connection
One of the following as required:
# 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 - Create folder structure as shown below,
Sequelize connection details and database models will be under database folder. Sequelize will look for the database directory and its sub-directories. It’s sequelize default structure
database folder will have sub-directories,
- attributes: this folder carries all the required model interface
- migrations: this folder carries database migrations
- models: this folder carries database models
- seeders: this folder carries data to be initialized once database is synced
- SequelizeConnection.ts: this file will be used to setup database connection using sequelize
Sequelize connection setup:
Connection object needs to be passed to sequelize which consist of following details,
- host
- port
- database-name
- username
- password
- dialect (default mysql)
- schema
Putting this into SequelizeConnection.ts class,
For more options, you can visit https://sequelize.org/master/class/lib/sequelize.js~Sequelize.html#instance-constructor-constructor
Create a small connection method which can be called to establish the connection,
Now, lets call the connect method in our app.ts
Run the app.ts file and you can see the below logs executing on terminal,
Congrats! We have successfully connected to our database using sequelize.
We’ll design a simple database with few tables and it’s association.
Consider a Organization having employees and each employee has different departments
We’ll first create different model attributes,
Create Organization.ts, UserDetails.ts and Department.ts file in attributes directory
and add the code as shown below in each file,
Lets have a look how to create model for these attributes,
Create similar files models directory
Start adding the code as shown below,
It’s time to sync models in our database. Add the below piece of code to app.ts file,
Now run the server again and you’ll find the below logs executing on terminal
You’ll be able to see the tables created in your database
You can find the whole code in below github repo,
https://github.com/rishabh31845/postgres-sequelize.git
Thanks!!!