Using TypeORM in a NestJS Project
Introduction
TypeORM is a powerful ORM (Object-Relational Mapper) library for the Node.js ecosystem, written in TypeScript. It allows developers to interact with databases using classes and objects instead of writing complex raw SQL queries.
Key Advantages
- Excellent TypeScript support: Fully leverages decorators and type-checking, helping detect errors during development instead of at runtime.
- Supports multiple databases: Compatible with popular database management systems such as MySQL, PostgreSQL, SQLite, etc.
- Flexible patterns (Data Mapper & Active Record): Lets you choose the appropriate implementation style depending on project size (Data Mapper for large, complex projects; Active Record for smaller, quick projects).
- Migration management: Provides powerful tools to manage database schema changes systematically, helping synchronize changes across development teams.
- Query Builder: In addition to object-based operations, TypeORM provides a Query Builder for constructing complex queries while maintaining clean and readable syntax.
How to Use
In this article, I will guide you on how to use TypeORM in a NestJS project with a PostgreSQL database, along with data validation.
After creating your NestJS project, install the required packages:
Create test.entity.ts
Each field in this entity corresponds to a column that will be created in the database.
Create create-test.dto.ts
- You can easily understand the purpose of each decorator from its name.
- class-validator also provides many other useful decorators, such as email validation, string length validation, min/max number checks, etc.
Create test-entity.service.ts
This service provides two simple functions:
- Retrieve all records from the test table.
- Create a new test entity.
Create test-entity.controller.ts
To validate the request payload, update main.ts to use ValidationPipe:
Connect to PostgreSQL and add Service and Controller to app.module.ts
- If you haven't installed Postgres yet, you can refer to this article which provides instructions on how to start Postgres using Docker.
- Regarding the TypeOrmModule configuration, please keep the following points in mind:
- schema: I haven't defined it here, so it will use the public schema by default. If you are using a different schema, you need to provide the correct schema name.
- synchronize: Setting this to true will automatically sync your entities from the source code to the database. This should only be used in development environments and never in production.
When calling the create API with an incorrect payload data type, validation errors will be returned as expected.
Other APIs should function normally.
Happy coding!
Comments
Post a Comment