On this submit I’ll clarify find out how to use my Node PostgreSQL module for NestJS 😻.
For these unfamiliar or unfamiliar with NestJS, it’s a TypeScript Node.js framework that helps you construct environment friendly and scalable enterprise-grade Node.js purposes.
For individuals who have by no means used node-postgres is a package deal to combine PostgreSQL with NodeJS (see right here for extra details about PostgreSQL and its options).
So let’s get began by creating the NestJS app 😻.
Open terminal and set up CLI for NestJS, if you have already got it put in, skip this step.
$ npm i -g @nestjs/cli
Then create a NestJS challenge
$ nest new app
$ cd app
// begin the appliance
$ npm run begin:dev
Open the browser on localhost:3000
to confirm that whats up world is displayed.
then we create a docker-compose.yml
file to create the service PostgreSQL
model: "3"
providers:
db:
picture: postgres
restart: at all times
ports:
- "5432:5432"
atmosphere:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: pass123
POSTGRES_DB: nest
for many who have no idea what docker is I go away the hyperlink right here for extra info Docker.
Properly now let’s proceed with the package deal set up.
Set up PostgresModule and Node-Postgres dependencies
$ npm set up --save nest-postgres pg
Set PostgresModule in AppModule
import { Module } from '@nestjs/frequent';
import { PostgresModule } from 'nest-postgres';
@Module ({
imports: [
PostgresModule.forRoot({
connectionString: 'postgresql://postgres:pass123@localhost:5432/nest',
// or
// host: 'localhost',
// database: 'nest',
// password: 'pass123',
// user: 'postgres',
// port: 5432,
}),
],
})
export class AppModule {}
Now let’s create a REST API and name it customers. We open the terminal and run the instructions to create the module, the service and the controller for the customers:
$ nest g mo customers # module
$ nest g s customers # service
$ nest g co customers # controller
UsersModule:
import { Module } from '@nestjs/frequent';
import { UsersService } from './customers.service';
import { UsersController } from './customers.controller';
@Module({
controllers: [UsersController],
suppliers: [UsersService]
})
export class UsersModule {}
Earlier than we begin constructing our API, create the Knowledge Switch Objects (Dto) class to create the customers
import { IsEmail, IsNotEmpty, IsString } from "class-validator";
export class CreateUserDto {
@Notempty()
@IsString()
firstName: string;
@Notempty()
@IsString()
lastName: string;
@Notempty()
@IsString()
@IsEmail()
e mail: string;
}
Bear in mind to put in this package deal earlier than creating the dto class for the improve.
$ npm i @nestjs/mapped-types
Properly, now to replace the customers knowledge we prolong the CreateUserDto class:
import { PartialType } from '@nestjs/mapped-types';
import { CreateUserDto } from './create-user.dto';
export class UpdateUserDto extends PartialType(CreateUserDto){}
We then implement ours UserService:
BadRequestException,
HttpException,
HttpStatus,
Injectable,
NotFoundException,
} from '@nestjs/frequent';
import { Shopper } from 'pg';
import { InjectClient } from 'nest-postgres';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
@Injectable()
export class UsersService {
constructor(@InjectClient() personal readonly pg: Shopper) {}
public async findAll(): Promise<any> {
const customers = await this.pg.question('SELECT * FROM customers');
return customers.rows;
}
public async findOne(id: string): Promise<any> {
if (!id) {
throw new BadRequestException();
}
const end result = await this.pg.question('SELECT * FROM customers WHERE id=$1', [id]);
if (!end result) {
throw new NotFoundException();
}
return end result.rows;
}
public async create(createUserDto: CreateUserDto): Promise<any> {
attempt {
const consumer = await this.pg.question(
'INSERT INTO customers (firstName, lastName, e mail) VALUES ($1, $2, $3) RETURNING *',
[createUserDto.firstName, createUserDto.lastName, createUserDto.email],
);
return consumer.rows;
} catch (err) {
throw new HttpException(err, HttpStatus.BAD_REQUEST);
}
}
public async replace(id: quantity, updateUserDto: UpdateUserDto): Promise<any> {
attempt {
const customers = await this.pg.question(
'UPDATE customers SET firstName=$1, lastName=$2, e mail=$3 WHERE id=$3 RETURNING *',
[updateUserDto.firstName, updateUserDto.lastName, updateUserDto.email, id],
);
return customers.rows;
} catch (err) {
throw new HttpException(err, HttpStatus.BAD_REQUEST);
}
}
public async take away(id: string): Promise<void[]> {
if (!id) {
throw new BadRequestException();
}
const customers = await this.pg.question(
'DELETE FROM customers WHERE id=$1 RETURNING *',
[id],
);
return customers.rows;
}
}
UsersController:
import { Controller, Get, Submit, Physique, Put, Param, Delete } from '@nestjs/frequent';
import { UsersService } from './customers.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
@Controller('/api/customers')
export class UsersController {
constructor(personal readonly usersService: UsersService) {}
@Submit()
create(@Physique() createUserDto: CreateUserDto) {
return this.usersService.create(createUserDto);
}
@Get()
findAll() {
return this.usersService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.usersService.findOne(id);
}
@Put(':id')
replace(@Param('id') id: string, @Physique() updateUserDto: UpdateUserDto) {
return this.usersService.replace(id, updateUserDto);
}
@Delete(':id')
take away(@Param('id') id: string) {
return this.usersService.take away(id);
}
}
nicely now we must always have our API examined if every little thing works completely this instructions from curl or no matter you like to make use of.
$ curl -H 'content-type: software/json' -v -X GET http://127.0.0.1:3000/api/customers
$ curl -H 'content-type: software/json' -v -X GET http://127.0.0.1:3000/api/customers/:id
$ curl -H 'content-type: software/json' -v -X POST -d '{"firstName": "firstName #1", "lastName": "lastName #1", "e mail": "instance@nest.it"}' http://127.0.0.1:3000/api/customers
$ curl -H 'content-type: software/json' -v -X PUT -d '{"firstName": "firstName replace #1", "lastName": "lastName replace #1", "e mail": "instance@nest.it}' http://127.0.0.1:3000/api/customers/:id
$ curl -H 'content-type: software/json' -v -X DELETE http://127.0.0.1:3000/api/customers/:id
For extra info on node-postgres
see right here.
This module is appropriate with model 7.x of NestJS 😻.
That is it 😀
Hope it may be helpful in your initiatives.
For something write me within the feedback 😉