Sequelize Typescript

How to Integrate Sequelize with Typescript in Node.js Project

In my experience, many Node.js projects require access to a database. My go-to ORM (Object-Relational Mapper) for these tasks is Sequelize. In this blog post, I’ll guide you through the process of adding a MySQL database using Sequelize with Typescript in your Node.js project.

Step 1: Setting Up MySQL with Docker

To start, you’ll need to set up a MySQL instance using Docker. Here’s how you can do it:

  1. Open your browser and search for “Docker MySQL.” The first result should be the MySQL official Docker image.
  2. Copy the Docker command to start the MySQL container.
  3. Open your VS Code and paste the command into your terminal. Make sure to modify the container name and port settings:
docker run --name mysql-db -e MYSQL_ROOT_PASSWORD=secret -p 3306:3306 -d mysql:latest
  1. Run the command. If you don’t have the MySQL image, Docker will automatically download it and start the container.

Step 2: Connecting to MySQL Using TablePlus

Next, you’ll want to connect to your MySQL instance using TablePlus or a similar database management tool:

  1. Open TablePlus and configure a new connection:
    • Host: localhost
    • Port: 3306
    • Username: root
    • Password: secret
  2. Test the connection, and if successful, connect to the database.
  3. Create a new database named my_blog using the UI.

Step 3: Configure Your Node.js Project

In your Node.js TypeScript project, you’ll need to configure the database connection settings:

  1. Open the .env file and add the following configuration below.
  2. Ensure that your project has a configuration module to load these environment variables.
DB_NAME=my_blog
DB_USER=root
DB_PASSWORD=secret
DB_HOST=localhost
DB_PORT=3306

? Unlock Your Backend Development Skills! ? Ready to master Node.js and Express for backend development? Check out this comprehensive course on Coursera: Developing Backend Apps with Node.js and Express

Whether you’re a beginner or looking to refine your skills, this course covers everything you need to know to build powerful backend applications. Enroll now and take your coding journey to the next level! ??

Step 4: Install Sequelize and MySQL Driver

Now, it’s time to install Sequelize and the necessary packages:

  1. Install Sequelize with TypeScript support:bashCopy code:
npm install sequelize sequelize-typescript mysql2 reflect-metadata
  1. Also, install the required TypeScript types:bashCopy code:
npm install --save-dev @types/node @types/validator

Step 5: Configure TypeScript

Update your tsconfig.json to enable decorators:

  1. Set target to ES6 or higher.
  2. Add the following compiler options:
"experimentalDecorators": true,
"emitDecoratorMetadata": true

Step 6: Create the Database Connection File

Create a new file named dbConnection.ts in the src folder:

import { Sequelize } from 'sequelize-typescript';
import config from './config';

const sequelize = new Sequelize({
  database: config.DB_NAME,
  username: config.DB_USER,
  password: config.DB_PASSWORD,
  host: config.DB_HOST,
  dialect: 'mysql',
  models: [__dirname + '/models'],
});

export default sequelize;

Step 7: Define Your Models

Create a new model, for example, Person, in the models folder:

import { Table, Column, Model, DataType, CreatedAt, UpdatedAt } from 'sequelize-typescript';

@Table({
  tableName: 'persons',
  timestamps: true,
})
export class Person extends Model<Person> {
  @Column({
    type: DataType.UUID,
    defaultValue: DataType.UUIDV4,
    primaryKey: true,
  })
  id!: string;

  @Column({
    type: DataType.STRING,
    allowNull: false,
  })
  name!: string;

  @CreatedAt
  createdAt!: Date;

  @UpdatedAt
  updatedAt!: Date;
}

Step 8: Sync the Database

To create the tables based on your models, use the Sequelize sync method:

import sequelize from './dbConnection';
import { Person } from './models/Person';

(async () => {
  await sequelize.sync({ force: true }); // For development use only
  await Person.create({ name: 'Alex' });
  console.log('Database synced and person created.');
})();

Step 9: Verify the Data

Switch back to TablePlus, refresh the database view, and you should see the persons table with the new entries.

Conclusion

Integrating MySQL with your Node.js TypeScript project using Sequelize is a straightforward process. For smaller projects, using Sequelize’s sync method is convenient. However, for larger projects, consider using Sequelize migrations for better control over your database schema. If you’re interested in learning more about Sequelize migrations, check out our video on the topic.

Happy coding!

Share this article

Similar Posts