Code Monkey home page Code Monkey logo

nestjs-postgres's Introduction

Nest Logo

A progressive Node.js framework for building efficient and scalable server-side applications.

NPM Version Package License NPM Downloads CircleCI Coverage Discord Backers on Open Collective Sponsors on Open Collective Support us

Description

PostgreSQL module for Nest framework (node.js) ๐Ÿ˜ป

Installation

First install the module via yarn or npm or pnpm and do not forget to install the driver package as well:

    $ npm i --save nest-postgres pg

or

    $ yarn add nest-postgres pg

or

    $ pnpm add nest-postgres pg

Table of Contents

Usage

PostgresModule

PostgresModule is the primary entry point for this package and can be used synchronously

@Module({
  imports: [
    PostgresModule.forRoot({
        connectionString: 'postgresql://[user]:[password]@[host]/[nameDb]',
        // or 
        // host: 'localhost',
        // database: [:databaseName],
        // password: [:passwordDb],
        // user: [:userDb],
        // port: 5432,
    }),
  ],
})

or asynchronously

@Module({
  imports: [
    PostgresModule.forRootAsync({
      useFactory: () => ({
        connectionString: 'postgresql://[user]:[password]@[host]/[nameDb]',
        // or 
        // host: 'localhost',
        // database: [:databaseName],
        // password: [:passwordDb],
        // user: [:userDb],
        // port: 5432,
      }),
    }),
  ],
})

Example of use

UsersService:

import { Client } from 'pg';
import { InjectClient } from 'nest-postgres';

@Injectable()
export class UsersService {
  constructor(@InjectClient() private readonly pg: Client) {}

  public async findAll(): Promise<User[]> {
    const users = await this.pg.query('SELECT * FROM users');
    return users.rows;
  }
}

UsersController:

import { Controller, Get } from '@nestjs/common';
import { UsersService } from './users.service';

@Controller()
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Get()
  async getAllUsers(): Promise<User[]> {
    return await this.usersService.findAll();
  }
}

Multi Connections Database

@Module({
  imports: [
    PostgresModule.forRoot(
      {
        connectionString: 'postgresql://postgres:pass123@localhost:5432/nest1',
        // or 
        // host: 'localhost',
        // database: [:databaseName],
        // password: [:passwordDb],
        // user: [:userDb],
        // port: 5432,
      },
      'db1Connection',
    ),
    PostgresModule.forRoot(
      {
        connectionString: 'postgresql://postgres:pass123@localhost:5434/nest2',
      },
      'db2Connection',
    ),
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}

Usage example with Multi Connection

PostService:

import { Client } from 'pg';
import { InjectConnection } from 'nest-postgres';
import { CreatePostDto } from './dto/create-post.dto';
import { Post } from './interfaces/post.interface';

@Injectable()
export class PostService {
  constructor(
    @InjectConnection('db2Connection')
    private dbConnection: Client,
  ) {}

  public async findAll(): Promise<Post[]> {
    const users = await this.dbConnection.query('SELECT * FROM posts');
    return users.rows;
  }

  public async create(createPostDto: CreatePostDto): Promise<Post[]> {
    try {
      const user = await this.dbConnection.query(
        'INSERT INTO posts (title, description)  VALUES ($1, $2) RETURNING *',
        [createPostDto.title, createPostDto.description],
      );
      return user.rows;
    } catch (err) {
      throw new HttpException(err, HttpStatus.BAD_REQUEST);
    }
  }
}

UsersService:

import { Client } from 'pg';
import { InjectConnection } from 'nest-postgres';
import { CreateUserDto } from './dto/create-user.dto';
import { User } from './interfaces/user.interface';

@Injectable()
export class UsersService {
  constructor(
    @InjectConnection('db1Connection')
    private dbConnection: Client,
  ) {}

  public async findAll(): Promise<User[]> {
    const users = await this.dbConnection.query('SELECT * FROM users');
    return users.rows;
  }

  public async create(createUserDto: CreateUserDto): Promise<User[]> {
    try {
      const user = await this.dbConnection.query(
        'INSERT INTO users (firstName, lastName)  VALUES ($1, $2) RETURNING *',
        [createUserDto.firstName, createUserDto.lastName],
      );
      return user.rows;
    } catch (err) {
      throw new HttpException(err, HttpStatus.BAD_REQUEST);
    }
  }
}

For more information on node-postgres for Nodejs see here

Contribute

Feel free to help this library, I'm quite busy with also another Nestjs packages, but the community will appreciate the effort of improving this library. Make sure you follow the guidelines

Stay in touch

License

MIT licensed

nestjs-postgres's People

Contributors

dependabot[bot] avatar raoufosman avatar renovate[bot] avatar tony133 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

nestjs-postgres's Issues

SSL Cert

Hi,

I'm trying to connect to a digital ocean managed database and it requires a cert to be passed to the connectionstring.

PG does support it: https://node-postgres.com/features/ssl#self-signed-cert

However, it looks like this module does not allow the cert to be passed to the ssl property.

Is it possible to add that? I'm getting the error below on Digital ocean:

[2023-08-10 19:05:46] Error: self signed certificate in certificate chain
[2023-08-10 19:05:46]     at TLSSocket.onConnectSecure (node:_tls_wrap:1539:34)
[2023-08-10 19:05:46]     at TLSSocket.emit (node:events:513:28)
[2023-08-10 19:05:46]     at TLSSocket._finishInit (node:_tls_wrap:953:8)
[2023-08-10 19:05:46]     at TLSWrap.ssl.onhandshakedone (node:_tls_wrap:734:12)

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/codeql-analysis.yml
  • actions/checkout v4@0ad4b8fadaa221de15dcec353f45205ec38ea70b
  • github/codeql-action v3
  • github/codeql-action v3
  • github/codeql-action v3
.github/workflows/nodejs-environment.yml
  • actions/checkout v4@0ad4b8fadaa221de15dcec353f45205ec38ea70b
  • actions/setup-node v4
  • actions/checkout v4@0ad4b8fadaa221de15dcec353f45205ec38ea70b
  • actions/setup-node v4
  • actions/setup-node v4
npm
package.json
  • @commitlint/cli 19.3.0
  • @commitlint/config-angular 19.3.0
  • @nestjs/common 10.3.8
  • @nestjs/config 3.2.2
  • @nestjs/core 10.3.8
  • @nestjs/platform-fastify ^10.3.7
  • @nestjs/testing 10.3.8
  • @types/jest 29.5.12
  • @types/node 20.12.8
  • @types/pg 8.11.5
  • @types/supertest 6.0.2
  • @typescript-eslint/eslint-plugin 7.8.0
  • @typescript-eslint/parser 7.8.0
  • eslint 8.57.0
  • eslint-config-prettier 9.1.0
  • eslint-plugin-import 2.29.1
  • husky 9.0.11
  • jest 29.7.0
  • pg 8.11.5
  • prettier 3.2.5
  • reflect-metadata 0.2.2
  • release-it 17.2.1
  • rxjs 7.8.1
  • supertest 7.0.0
  • ts-jest 29.1.2
  • ts-node 10.9.2
  • tsconfig-paths 4.2.0
  • typescript 5.4.5
  • @nestjs/common ^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0
  • @nestjs/core ^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0
  • pg ^8.7.3
  • reflect-metadata ^0.1.13 || ^0.2.0
  • rxjs ^6.6.3 || ^7.2.0

  • Check this box to trigger a request for Renovate to run again on this repository

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.