Object-Relational Mapping (ORM) libraries can often help us write our code faster. The ORM allows us not to write raw SQL. Instead, we can manipulate the data using an object-oriented paradigm.
Using ORM can ease the learning curve of working with databases because we don’t need to go deep into learning SQL. Instead, we write the data model in the programming language we use to develop the application. On top of that, ORM should have security mechanisms that deal with issues such as SQL injection.
Unfortunately, ORMs have disadvantages too. For example, depending on ORM to generate the database structure based on our models can lead to not grasping the intricacies of the underlying architecture. Also, ORM automatically generates SQL queries for fetching, inserting or modifying data. Therefore, they are not always optimal and can lead to performance issues. Also, ORMs can have problems and bugs too.
It is fine to use ORM if we don’t need a lot of control over our SQL queries. If we develop a big project, though, we might prefer to deal with database management through raw SQL queries. In this article, we figure out how to structure our NestJS project to use raw SQL queries with a PostgreSQL database.
You can find the code from this article in this repository.
Connecting to the database
As usual in this series, we use Docker to create an instance of the PostgreSQL database for us.
1version: "3"
2services:
3 postgres:
4 container_name: postgres-nestjs
5 image: postgres:latest
6 ports:
7 - "5432:5432"
8 volumes:
9 - /data/postgres:/data/postgres
10 env_file:
11 - docker.env
12 networks:
13 - postgres
14
15 pgadmin:
16 links:
17 - postgres:postgres
18 container_name: pgadmin-nestjs
19 image: dpage/pgadmin4
20 ports:
21 - "8080:80"
22 volumes:
23 - /data/pgadmin:/root/.pgadmin
24 env_file:
25 - docker.env
26 networks:
27 - postgres
28
29networks:
30 postgres:
31 driver: bridgeTo provide Docker with the necessary environment variables, we need to create the docker.env file.
1POSTGRES_USER=admin
2POSTGRES_PASSWORD=admin
3POSTGRES_DB=nestjs
4PGADMIN_DEFAULT_EMAIL=admin@admin.com
5PGADMIN_DEFAULT_PASSWORD=adminWe must also provide a similar set of variables for our NestJS application.
1POSTGRES_HOST=localhost
2POSTGRES_PORT=5432
3POSTGRES_USER=admin
4POSTGRES_PASSWORD=admin
5POSTGRES_DB=nestjsIt is also a good idea to validate if the environment variables are provided when the application starts.
1import { Module } from '@nestjs/common';
2import { ConfigModule } from '@nestjs/config';
3import * as Joi from 'joi';
4
5@Module({
6 imports: [
7 ConfigModule.forRoot({
8 validationSchema: Joi.object({
9 POSTGRES_HOST: Joi.string().required(),
10 POSTGRES_PORT: Joi.number().required(),
11 POSTGRES_USER: Joi.string().required(),
12 POSTGRES_PASSWORD: Joi.string().required(),
13 POSTGRES_DB: Joi.string().required(),
14 }),
15 }),
16 ],
17})
18export class AppModule {}Establishing the connection
In this article, we use the node-postgres library to establish a connection to our PostgreSQL database and run queries.
1npm install pg @types/pgTo manage a database connection, we can create a dynamic module. Thanks to that, we could easily copy and paste it to a different project or keep it in a separate library.
If you are not familiar with dynamic modules, check out API with NestJS #70. Defining dynamic modules
1import { ConfigurableModuleBuilder } from '@nestjs/common';
2import DatabaseOptions from './databaseOptions';
3
4export const CONNECTION_POOL = 'CONNECTION_POOL';
5
6export const {
7 ConfigurableModuleClass: ConfigurableDatabaseModule,
8 MODULE_OPTIONS_TOKEN: DATABASE_OPTIONS,
9} = new ConfigurableModuleBuilder<DatabaseOptions>()
10 .setClassMethodName('forRoot')
11 .build();We use forRoot above because we want our DatabaseModule to be global.
When the DatabaseModule is imported, we expect a particular set of options to be provided.
1interface DatabaseOptions {
2 host: string;
3 port: number;
4 user: string;
5 password: string;
6 database: string;
7}
8
9export default DatabaseOptions;Using a connection pool
The node-postgres library recommends we use a connection pool. Since we are creating a dynamic module, we can define our pool as a provider.
1import { Global, Module } from '@nestjs/common';
2import {
3 ConfigurableDatabaseModule,
4 CONNECTION_POOL,
5 DATABASE_OPTIONS,
6} from './database.module-definition';
7import DatabaseOptions from './databaseOptions';
8import { Pool } from 'pg';
9import DatabaseService from './database.service';
10
11@Global()
12@Module({
13 exports: [DatabaseService],
14 providers: [
15 DatabaseService,
16 {
17 provide: CONNECTION_POOL,
18 inject: [DATABASE_OPTIONS],
19 useFactory: (databaseOptions: DatabaseOptions) => {
20 return new Pool({
21 host: databaseOptions.host,
22 port: databaseOptions.port,
23 user: databaseOptions.user,
24 password: databaseOptions.password,
25 database: databaseOptions.database,
26 });
27 },
28 },
29 ],
30})
31export default class DatabaseModule extends ConfigurableDatabaseModule {}There is an advantage to defining the connection pool as a provider. If we want to specify some additional asynchronous configuration, this is a very good place to do so. You can find a proper example in a repository created by Jay McDoniel from the NestJS team.
Thanks to the fact that above we define a provider using the CONNECTION_POOL string, we now can use it in our service.
1import { Inject, Injectable } from '@nestjs/common';
2import { Pool } from 'pg';
3import { CONNECTION_POOL } from './database.module-definition';
4
5@Injectable()
6class DatabaseService {
7 constructor(@Inject(CONNECTION_POOL) private readonly pool: Pool) {}
8
9 async runQuery(query: string, params?: unknown[]) {
10 return this.pool.query(query, params);
11 }
12}
13
14export default DatabaseService;Managing migrations using Knex
We could manage migrations manually, but using an existing tool might save us time and trouble. Therefore, in this article, we use Knex.
1npm install knexThe first step in using Knex is to create the configuration file.
1import type { Knex } from 'knex';
2import { ConfigService } from '@nestjs/config';
3import { config } from 'dotenv';
4
5config();
6
7const configService = new ConfigService();
8
9const knexConfig: Knex.Config = {
10 client: 'postgresql',
11 connection: {
12 host: configService.get('POSTGRES_HOST'),
13 port: configService.get('POSTGRES_PORT'),
14 user: configService.get('POSTGRES_USER'),
15 password: configService.get('POSTGRES_PASSWORD'),
16 database: configService.get('POSTGRES_DB'),
17 },
18};
19
20module.exports = knexConfig;Above we use dotenv to make sure that our .env is loaded before using the ConfigService.
We can now create our first migration using the migration CLI.
1npx knex migrate:make add_posts_tableRunning the above command creates a file where we can define our migration.
1import { Knex } from 'knex';
2
3export async function up(knex: Knex): Promise<void> {}
4
5export async function down(knex: Knex): Promise<void> {}We need to fill the up and down methods with the SQL queries Knex will run when running migrations and rolling them back.
1import { Knex } from 'knex';
2
3export async function up(knex: Knex): Promise<void> {
4 return knex.raw(`
5 CREATE TABLE posts (
6 id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
7 title text NOT NULL,
8 post_content text NOT NULL
9 )
10 `);
11}
12
13export async function down(knex: Knex): Promise<void> {
14 return knex.raw(`
15 DROP TABLE posts
16 `);
17}If you want to know more about identity columns, check out Serial type versus identity columns in PostgreSQL and TypeORM
We must execute one last command if we want Knex to run our migration.
1npx knex migrate:latestRunning migrations creates the knex_migrations table that contains information about which migrations Knex has already executed.
Knex also creates the knex_migrations_lock table to prevent multiple procsses from running the same migrations in the same time.
The official documentation is a good resource if you want to know more about managing migrations with Knex.
The repository pattern and working with models
It might be a good idea to keep the logic of accessing data in a single place for a particular table. A very popular way of doing that is using the repository pattern.
1import { Injectable } from '@nestjs/common';
2import DatabaseService from '../database/database.service';
3
4@Injectable()
5class PostsRepository {
6 constructor(private readonly databaseService: DatabaseService) {}
7
8 async getAll() {
9 const databaseResponse = await this.databaseService.runQuery(`
10 SELECT * FROM posts
11 `);
12 return databaseResponse.rows;
13 }
14}
15
16export default PostsRepository;When running the getAll method, we get the data in the following format:
1[
2 {
3 id: 1,
4 title: 'Hello world',
5 post_content: 'Lorem ipsum'
6 }
7]We often might want to transform the raw data we get from the database. A fitting way to do that is to use the class-transformer library, a popular choice when working with NestJS.
1import { Expose } from 'class-transformer';
2
3class PostModel {
4 id: number;
5 title: string;
6 @Expose({ name: 'post_content' })
7 content: string;
8}
9
10export default PostModel;We need to call the plainToInstance function in our repository to use the above model.
1import { Injectable } from '@nestjs/common';
2import DatabaseService from '../database/database.service';
3import { plainToInstance } from 'class-transformer';
4import PostModel from './post.model';
5
6@Injectable()
7class PostsRepository {
8 constructor(private readonly databaseService: DatabaseService) {}
9
10 async getAll() {
11 const databaseResponse = await this.databaseService.runQuery(`
12 SELECT * FROM posts
13 `);
14 return plainToInstance(PostModel, databaseResponse.rows);
15 }
16}
17
18export default PostsRepository;Thanks to doing the above, the data returned by the getAll function contains the instances of the PostModel class. Now, instead of post_content we have the content property.
1[
2 {
3 id: 1,
4 title: 'Hello world',
5 content: 'Lorem ipsum'
6 }
7]Using parametrized queries
We often need to use the input provided by the user as a part of our SQL query. When doing that carelessly, we open ourselves to SQL injections. The SQL injection can happen if we treat the user’s input as a part of the query. Let’s take a look at a simple example:
1async getById(id: unknown) {
2 const databaseResponse = await this.databaseService.runQuery(
3 `
4 SELECT * FROM posts WHERE id=${id}
5 `
6 );
7 const entity = databaseResponse.rows[0];
8 if (!entity) {
9 throw new NotFoundException();
10 }
11 return plainToInstance(PostModel, entity);
12}Because in the getById function, we concatenate a string, we open ourselves to the following SQL injection:
1getById('1; DROP TABLE posts;');Running the getById method with the above string causes the following SQL query to run:
1SELECT * FROM posts WHERE id=1; DROP TABLE posts;Unfortunately, it destroys our posts table.
One one of dealing with the above problem is using parameterized queries. When we use it, we send the parameters separately from the query, and our database knows to treat them as parameters.
To use parameters, we need to provide the second argument to the runQuery method we’ve defined in the DatabaseService.
1import { Injectable, NotFoundException } from '@nestjs/common';
2import DatabaseService from '../database/database.service';
3import { plainToInstance } from 'class-transformer';
4import PostModel from './post.model';
5
6@Injectable()
7class PostsRepository {
8 constructor(private readonly databaseService: DatabaseService) {}
9
10 async getById(id: number) {
11 const databaseResponse = await this.databaseService.runQuery(
12 `
13 SELECT * FROM posts WHERE id=$1
14 `,
15 [id],
16 );
17 const entity = databaseResponse.rows[0];
18 if (!entity) {
19 throw new NotFoundException();
20 }
21 return plainToInstance(PostModel, entity);
22 }
23
24 async delete(id: number) {
25 const databaseResponse = await this.databaseService.runQuery(
26 `DELETE FROM posts WHERE id=$1`,
27 [id],
28 );
29 if (databaseResponse.rowCount === 0) {
30 throw new NotFoundException();
31 }
32 }
33
34 // ...
35}
36
37export default PostsRepository;Validating incoming data
To validate the data provided by the users, we can take advantage of the class-validator library that’s popular among people using the NestJS framework.
1import { IsString, IsNotEmpty } from 'class-validator';
2
3class PostDto {
4 @IsString()
5 @IsNotEmpty()
6 title: string;
7
8 @IsString()
9 @IsNotEmpty()
10 content: string;
11}
12
13export default PostDto;We can use the above class in our repository when creating and updating posts.
1import { Injectable, NotFoundException } from '@nestjs/common';
2import DatabaseService from '../database/database.service';
3import { plainToInstance } from 'class-transformer';
4import PostModel from './post.model';
5import PostDto from './post.dto';
6
7@Injectable()
8class PostsRepository {
9 constructor(private readonly databaseService: DatabaseService) {}
10
11 async create(postData: PostDto) {
12 const databaseResponse = await this.databaseService.runQuery(
13 `
14 INSERT INTO posts (
15 title,
16 post_content
17 ) VALUES (
18 $1,
19 $2
20 ) RETURNING *
21 `,
22 [postData.title, postData.content],
23 );
24 return plainToInstance(PostModel, databaseResponse.rows[0]);
25 }
26
27 async update(id: number, postData: PostDto) {
28 const databaseResponse = await this.databaseService.runQuery(
29 `
30 UPDATE posts
31 SET title = $2, post_content = $3
32 WHERE id = $1
33 RETURNING *
34 `,
35 [id, postData.title, postData.content],
36 );
37 const entity = databaseResponse.rows[0];
38 if (!entity) {
39 throw new NotFoundException();
40 }
41 return plainToInstance(PostModel, entity);
42 }
43
44 // ...
45}
46
47export default PostsRepository;If you want to see the full repository, check out this repository.
We also need to use the PostDto class in our controller.
1import {
2 Body,
3 Controller,
4 Delete,
5 Get,
6 Param,
7 Post,
8 Put,
9} from '@nestjs/common';
10import { PostsService } from './posts.service';
11import FindOneParams from '../utils/findOneParams';
12import PostDto from './post.dto';
13
14@Controller('posts')
15export default class PostsController {
16 constructor(private readonly postsService: PostsService) {}
17
18 @Get()
19 getPosts() {
20 return this.postsService.getPosts();
21 }
22
23 @Get(':id')
24 getPostById(@Param() { id }: FindOneParams) {
25 return this.postsService.getPostById(id);
26 }
27
28 @Put(':id')
29 updatePost(@Param() { id }: FindOneParams, @Body() postData: PostDto) {
30 return this.postsService.updatePost(id, postData);
31 }
32
33 @Post()
34 createPost(@Body() postData: PostDto) {
35 return this.postsService.createPost(postData);
36 }
37
38 @Delete(':id')
39 deletePost(@Param() { id }: FindOneParams) {
40 return this.postsService.deletePost(id);
41 }
42}The FindOneParams class takes care of parsing the id from the string to a number.
For validation to take place, we also need to use the ValidationPipe. To do that globally, we can add it to the providers array in our AppModule.
1import { Module, ValidationPipe } from '@nestjs/common';
2import { APP_PIPE } from '@nestjs/core';
3
4@Module({
5 providers: [
6 {
7 provide: APP_PIPE,
8 useValue: new ValidationPipe({
9 transform: true,
10 }),
11 },
12 ],
13 // ...
14})
15export class AppModule {}Using services
You might have noticed that the PostsController uses the PostsService, a straightforward service that uses the PostsRepository.
1import { Injectable } from '@nestjs/common';
2import PostsRepository from './posts.repository';
3import PostDto from './post.dto';
4
5@Injectable()
6export class PostsService {
7 constructor(private readonly postsRepository: PostsRepository) {}
8
9 getPosts() {
10 return this.postsRepository.getAll();
11 }
12
13 getPostById(id: number) {
14 return this.postsRepository.getById(id);
15 }
16
17 createPost(postData: PostDto) {
18 return this.postsRepository.create(postData);
19 }
20
21 updatePost(id: number, postData: PostDto) {
22 return this.postsRepository.update(id, postData);
23 }
24
25 deletePost(id: number) {
26 return this.postsRepository.delete(id);
27 }
28}A service is a great place to write additional logic. A good example would be caching or using ElasticSearch.
If you want to know more about ElasticSearch, check out API with NestJS #12. Introduction to Elasticsearch
Summary
There could be many reasons we might not want to use ORM, and we’ve covered some of them in this article. To deal with that, we’ve implemented a way to write raw SQL queries when working with PostgreSQL and NestJS. To increase the development experience, we’ve decided to rely on Knex for managing migrations. The repository created in this article can serve as a good starting point for a more complex project.