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.
Install dependencies
$ npm install pg pg-hstore sequelize --save
After installation is completed then setup .env file for Database setup.
DATABASE_URL=postgres://user_name:password@localhost:5432/database_name
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.
Setup Sequelize
Create .sequelizerc file
This setup determines the path of the config, models, seeders, and migrations.
Create migration
$ sequelize migration:create --name create_user_table
It is a sample user table migrations.
Define Types
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.
Model
Create user.ts file in the model directory
Define the user model and write all validation.
Create Service
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
Create Controller
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)
Create Route
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!