Fastify and Sequelize with TypeScript.
Hi friends, In this article, I will explain about Fastify and Sequelize configuration with TypeScript.
Before we are going to configure Sequelize with TypeScript first we need to configure with Fastify and TypeScript.
For details of Fastify and TypeScript refer to this article. In that article, I explained the configuration of Fastiy and TypeScript. After we configured Fastify with TypeScript then move to the next step.
$ npm install pg pg-hstore sequelize --save
After installation is completed then setup .env file for Database setup.
And open your terminal and change your path to the project directory.
$ export DATABASE_URL=postgres://user_name:password@localhost:5432/database_name
And, paste the above command in your terminal.
Create .sequelizerc file
This setup determines the path of the config, models, seeders, and migrations.
$ sequelize migration:create --name create_user_table
It is a sample user table migrations.
It is the type definition, user model. Write this file under the types folder. The file path is types/user.d.ts
Import this file in the user model and use type definitions.
Create user.ts file in the model directory
Define the user model and write all validation.
Write the function to create users.
Using the above function user can create new users. It returns a promise. Write this file in under services folder /services/user.service.ts
Writing controller is for our easy understanding. From the controller, we called our service.
We write this file under the controllers directory (/controllers/users.controller.ts)
For this router also our easy understanding purpose. From the router, we called our controller. The file path (/routes/user.routes.ts).
After that import our router in the application.ts file then only it is available to access.
Now users can reach this endpoint to create a new user.
Thank you for reading. Have a nice day!
How to use TypeScript with Sequelize
Using Decorators is something you should avoid as much as possible, they are not ECMAScript standard. They are even…
Using Sequelize with TypeScript - Michal Zalecki