Skip to main content

Backend Nest JS

Introduction 🚀​

Welcome to the SOS NestJS Server with PostgreSQL documentation! This guide is designed to help developers seamlessly integrate a powerful and efficient backend using NestJS and PostgreSQL. Whether you're building a new project or enhancing an existing one, this document provides all the necessary steps, best practices, and troubleshooting tips to ensure success.

Prerequisites 📎​

  • Git (>= 2.x)

  • Node JS (>= 18.x)

  • Nest CLI (>= 1.x)

  • PostgreSQL (>= 14.x)

  • Basic knowledge of TypeScript, Node.js, Nest JS with Express platform and PostgreSQL

Setup Instructions (local)​

Project Initialization​

  1. Clone sos-nest-ts project github:
>_ Terminal
git clone https://github.com/simplyhomes/sos-nest-ts
  1. Navigate to the project directory:
>_ Terminal
cd sos-nest-ts
  1. Install node_module:
>_ Terminal
yarn install
  1. Start project:
>_ Terminal
yarn run dev

Project structure and organization 💫​

Folder and file conventions​

Top-level folder​

.dbever
Contains the script files of DBeaver tool, typically for managing database queries and configurations.
.github
Contains GitHub-specific configuration files, such as workflows for CI/CD pipelines.
.husky
Contains Git hooks to enforce coding standards and automate tasks during commit or push events.
src
Main source code directory where application logic is implemented.
cron
Contains cron job scripts for scheduling automated tasks.
databases
Contains database schema, migration files, or seed data.
dev
Holds development-related files, tools, dev servide, dev controller or configuration for local environments.
middlewares
Contains middleware functions for processing requests and responses in the application.
routes
Defines the API or application routing logic, mapping endpoints to handlers.
shared
Holds shared resources or utilities used across multiple parts of the application.
types
Contains TypeScript type definitions and interfaces for the project.
utils
Contains utility functions and helper methods for common tasks in the application.

Top-level files​

.env.common
Contains shared environment variables used across all environments.
.env.development
Contains environment-specific variables for the development environment.
.env.production
Contains environment-specific variables for the production environment.
.env.staging
Contains environment-specific variables for the staging environment.
.eslintrc.js
ESLint configuration file for linting JavaScript/TypeScript code according to set rules.
.gitignore
Specifies intentionally untracked files to ignore in the Git repository.
.prettierrc
Configuration file for Prettier, defining code formatting rules and preferences.
commitlint.config.js
Configuration file for Commitlint to enforce commit message conventions.
nest-cli.json
Configuration file for the NestJS CLI, defining project settings and build options.
package.json
Defines project metadata, dependencies, scripts, and other npm configurations.
README.md
Project documentation file, typically describing usage, installation, and other details.
tsconfig.build.json
TypeScript configuration file for the build process, focusing on production settings.
tsconfig.json
Base TypeScript configuration file, defining compiler options and paths for the project.
yarn.lock
Lockfile for Yarn, ensuring consistent dependency versions across installations.

Testing APIs with Swaggers Docs 📂​

Swagger UI​

Swagger UI is a tool that visually renders documentation for APIs defined in the OpenAPI Specification. It provides a user-friendly interface to explore and test API endpoints, request parameters, and responses. The Swagger UI is automatically generated based on the API routes and schemas defined in the application.

To access the Swagger UI, navigate to the following URL in your browser:

Browser
  http://localhost:5001/api

How to access the APIs via Swagger UI ?​

Access token​

Click on the Authorize button in the top right corner of the Swagger UI page. Enter the access token in the Value field and click Authorize.

Create a new API 🔥​

Define a new route in the controller file of routes folder​

Example:​

src/routes/sos/notifications/notifications.controller.ts
  @Patch(':nid/read')
@ApiOperation({ summary: 'Mark a notification as read' })
changeNotificationReadStatus(
@Param() query: Nofs_ChangeNotificationReadStatus_Param_Dto,
@Body() body: Nofs_ChangeNotificationReadStatus_Body_Dto
): Promise<Nofs_ChangeNotificationReadStatus_Response_Dto> {
return this.notificationService.changeNotificationReadStatus({ ...query, ...body });
}

Explanation:​

  1. @Patch(':nid/read'): HTTP method and route path for the API endpoint, you can use @Get, @Post, @Put, @Delete, @Patch etc.

  2. @ApiOperation({ summary: 'Mark a notification as read' }): Description of the API endpoint, which will be displayed in the Swagger UI.

  3. changeNotificationReadStatus(): Method name for the API endpoint.

  4. @Param() query: Nofs_ChangeNotificationReadStatus_Param_Dto: Request parameters defined in the DTO (Data Transfer Object) for the API endpoint.

  5. @Body() body: Nofs_ChangeNotificationReadStatus_Body_Dto: Request body defined in the DTO (Data Transfer Object) for the API endpoint.

  6. Promise<Nofs_ChangeNotificationReadStatus_Response_Dto>: Response type defined in the DTO (Data Transfer Object) for the API endpoint.

Define the DTO (Data Transfer Object) for the request and response payloads​

Example:​

src/routes/sos/notifications/dto/change-notification-read-status.dto.ts
  import { Transform } from 'class-transformer';
import { IsBoolean, IsNumber } from 'class-validator';

export class Nofs_ChangeNotificationReadStatus_Param_Dto {
@Transform(({ value }) => parseInt(value))
@IsNumber()
nid!: number;
}

export class Nofs_ChangeNotificationReadStatus_Body_Dto {
@Transform(({ value }) => Boolean(value))
@IsBoolean()
read!: boolean;
}

export class Nofs_ChangeNotificationReadStatus_Response_Dto {
message!: string;
}

export type Nofs_ChangeNotificationReadStatus_Params = Nofs_ChangeNotificationReadStatus_Param_Dto &
Nofs_ChangeNotificationReadStatus_Body_Dto;

export type Nofs_ChangeNotificationReadStatus_Return = Promise<Nofs_ChangeNotificationReadStatus_Response_Dto>;

Explanation:​

  1. Nofs_ChangeNotificationReadStatus_Param_Dto: DTO class for request parameters.

  2. Nofs_ChangeNotificationReadStatus_Body_Dto: DTO class for request body.

  3. Nofs_ChangeNotificationReadStatus_Response_Dto: DTO class for response payload.

  4. @Transform(({ value }) => parseInt(value)): Decorator to transform the parameter value to an integer.

  5. @IsNumber(): Decorator to validate the parameter value as a number.

  6. @Transform(({ value }) => Boolean(value)): Decorator to transform the body value to a boolean.

  7. @IsBoolean(): Decorator to validate the body value as a boolean.

  8. message!: string;: Response message property.

  9. Nofs_ChangeNotificationReadStatus_Params: Type definition for combined request parameters and body.

  10. Nofs_ChangeNotificationReadStatus_Return: Type definition for the API response.

Create a new service file in the services​

Handle the business logic and data processing for the API endpoint in the service file.