Git Product home page Git Product logo

nestjs-pgpromise's Introduction

Nest Logo

pg-promise Module for Nest framework

CI NPM Version Package License NPM Downloads

Buy Me A Coffee

Description

This's a nest-pgpromise module for Nest. This quickstart guide will show you how to install and execute an example nestjs program..

This document assumes that you have a working nodejs setup in place.

Download from NPM

npm install --save nestjs-pgpromise

Initialize

You need five items in order to connect to the PostgreSQL server.

Params Description
host Host IP address or URL.
port TCP/IP port number to access the database.
database The name of the database to connect to.
user The username to access the database.
password The username's password to access the database.

And you can use as well all the other parameters allowed by pg-promise package. See the documentation.

Provide the credentials for pg-promise module by importing it as :

As Connection object

import { Module } from '@nestjs/common';
import { NestPgpromiseClientController } from './nest-pgpromise-client.controller';
import { NestPgpromiseModule } from 'nestjs-pgpromise';

@Module({
  controllers: [NestPgpromiseClientController],
  imports: [
    NestPgpromiseModule.register({
      isGlobal: true,
      connection: {
        host: 'localhost',
        port: 5432,
        database: 'cmdbbtbi',
        user: 'cmadbbtbi',
        password: 'cghQZynG0whwtGki-ci2bpxV5Jw_5k6z',
      },
    }),
  ],
})
export class AppModule {}

As Connection string

import { Module } from '@nestjs/common';
import { NestPgpromiseClientController } from './nest-pgpromise-client.controller';
import { NestPgpromiseModule } from 'nestjs-pgpromise';

@Module({
  controllers: [NestPgpromiseClientController],
  imports: [
    NestPgpromiseModule.register(
        isGlobal: true,
      {
      connection: "postgres://YourUserName:YourPassword@YourHost:5432/YourDatabase"
    }),
  ],
})
export class AppModule {}

Then you can use it in the controller or service by injecting it in the controller as:

constructor(@Inject(NEST_PGPROMISE_CONNECTION) private readonly pg: IDatabase<any>) {}

Quick Start Example

This example program connects to postgres on localhost and executes a simple select query from table tasks.

import { Controller, Get, Inject, Logger } from '@nestjs/common';
import { NEST_PGPROMISE_CONNECTION } from 'nestjs-pgpromise';
import { IDatabase } from 'pg-promise';

@Controller()
export class NestPgpromiseClientController {
  private logger = new Logger('controller');
  constructor(@Inject(NEST_PGPROMISE_CONNECTION) private readonly pg: IDatabase<any>) {}

  @Get()
  async index() {
    this.pg
      .any('SELECT * FROM task')
      .then(data => {
        // success;
        this.logger.log(data);
      })
      .catch(error => {
        // error;
        this.logger.log(error);
      });
  }
}

As pg-promise methods return promises, the new async/await syntaxis can be used.

import { Controller, Get, Inject, Logger } from '@nestjs/common';
import { NEST_PGPROMISE_CONNECTION } from 'nestjs-pgpromise';
import { IDatabase } from 'pg-promise';

@Controller()
export class NestPgpromiseClientController {
  private logger = new Logger('controller');
  constructor(@Inject(NEST_PGPROMISE_CONNECTION) private readonly pg: IDatabase<any>) {}

  @Get()
  async index() {
    try {
      const data = await this.pg.any('SELECT * FROM task');
      // success;
      this.logger.log(data);
    } catch(e) {
      // error;
      this.logger.log(error);
    }
  }
}

You can also pass in initoptions as supported by pg-promise.

import { Module } from '@nestjs/common';
import { NestPgpromiseClientController } from './nest-pgpromise-client.controller';
import { NestPgpromiseModule } from 'nestjs-pgpromise';

@Module({
  controllers: [NestPgpromiseClientController],
  imports: [
    NestPgpromiseModule.register(
      isGlobal: true,
      {
      connection: {
        host: 'localhost',
        port: 5432,
        database: 'cmdbbtbi',
        user: 'cmadbbtbi',
        password: 'cghQZynG0whwtGki-ci2bpxV5Jw_5k6z',
      },
      initOptions:{/* initialization options */};
    }),
  ],
})
export class AppModule {}

Note: You can then access the underlying PGP object through the $config property, for example:

  new this.pg.$config.pgp.helpers.ColumnSet(['col1', 'col2']);

You can find the details about them in the pg-promise documentation

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Vitaly Tomilov

🚇 ⚠️ 💻

Matthew J. Clemente

🚇 ⚠️ 💻

Jason Santiago

📖

Hector

📖

This project follows the all-contributors specification. Contributions of any kind welcome!

nestjs-pgpromise's People

Contributors

rubiin avatar dependabot-preview[bot] avatar windofwind avatar allcontributors[bot] avatar nythrox avatar byteglory avatar mjclemente avatar sectos avatar renovate[bot] avatar aavash avatar lgtm-migrator avatar sahellebusch avatar vitaly-t avatar github-actions[bot] avatar

Stargazers

Chris Hart avatar Nurul Haya avatar Zachary Yates avatar Bishwa Jung Shah avatar  avatar Roman avatar  avatar  avatar  avatar Anton Popov avatar Egor Gumin avatar Jônatas Fernandes Pimenta avatar William Koller avatar  avatar Nikita avatar  avatar  avatar Gopal Ojha avatar Kris Kaczor avatar  avatar Eduardo Rabelo avatar nizar avatar Erik Henrique avatar Michael Borozenets avatar Shekhar Koirala avatar  avatar  avatar Santosh Yadav avatar  avatar  avatar Kishan Kumar avatar

Watchers

 avatar  avatar  avatar

nestjs-pgpromise's Issues

Dependency Dashboard

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

Other Branches

These updates are pending. To force PRs open, click the checkbox below.

  • chore(deps): update dependency lint-staged to v13.2.3

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/ci.yml
  • actions/checkout v3
  • pnpm/action-setup v2
  • actions/setup-node v3
.github/workflows/codeql.yml
  • actions/checkout v3
  • github/codeql-action v2
  • github/codeql-action v2
  • github/codeql-action v2
npm
package.json
  • pg-promise ^11.5.0
  • @nestjs/common ^10.0.0
  • @nestjs/core ^10.0.0
  • @nestjs/platform-express ^10.0.0
  • @nestjs/testing 10.0.0
  • @types/express 4.17.17
  • @types/jest 29.5.2
  • @types/node 20.3.1
  • @types/supertest 2.0.12
  • cz-conventional-changelog 3.3.0
  • husky ^8.0.3
  • jest 29.5.0
  • lint-staged ^13.2.2
  • prettier ^2.8.8
  • reflect-metadata ^0.1.13
  • rxjs ^7.8.1
  • supertest 6.3.3
  • ts-jest 29.1.0
  • ts-node 10.9.1
  • tsconfig-paths 4.2.0
  • typescript 5.1.3
  • @nestjs/common >7.0.0
  • @nestjs/core >7.0.0

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

npm install failed

Bug Report

Removed my docker container and image to rebuild both.
Didn't touch the package.json file since last rebuild (which worked flawless).

Rebuilding the image failed with npm install error...

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: @nestjs/[email protected]
npm ERR! node_modules/@nestjs/common
npm ERR!   @nestjs/common@"^7.0.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @nestjs/common@">7.6.4" from [email protected]
npm ERR! node_modules/nestjs-pgpromise
npm ERR!   nestjs-pgpromise@"^1.3.6" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

Looks like nestjs-pgpromise v1.4.0 demands @nestjs/common@ v7.6.4. Is that on purpose?
As a workaround I changed my dependency to nestjs-pgpromise@"1.3.6".

Remove credentials logging

As we can see credentials printed on console as soon as the module is loaded in plain text, anyone can use it if seen

jest test

After writing test code in JEST, prevent the following message from appearing when running "pnpm test"

Jest did not exit 1 second after test execution completed.

This usually means that the test has asynchronous tasks that were not stopped. To fix this, try running Jest with `--detectOpenHandles`."

Pgp.helpers

Hallo,
in my old node apps i use pgp.helpers a lot, now i am migrating to nestjs, but i can't understand how to user the helpers, can someone help me?

example in old js:

const cs = new pgp.helpers.ColumnSet(dati, { table: { table: 'mytable', schema: myschema } });

thanks a lot

Fix README

Additional context

this.logger.log(data);
} catch(e) {
// error;
this.logger.log(error);
}
catch e log e
this.logger.log(e)

Close database connection

Should this module close the database connection when the app is shut down?

I'm asking because I noticed in the core TypeORM module, they close the connect onApplicationShutdown (line here).

Right now I have to do this manually if I don't want a warning during testing that Jest didn't exit properly.

Support for NestJS v8

I have a project for which I'd like to take advantage of features added in NestJS v8.

I'd like to use this project for connecting to my database, but get dependency errors when trying to install.

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: @nestjs/[email protected]
npm ERR! node_modules/@nestjs/common
npm ERR!   @nestjs/common@"^8.0.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @nestjs/common@"^6.10.11 || ^7.0.0" from [email protected]
npm ERR! node_modules/nestjs-pgpromise
npm ERR!   nestjs-pgpromise@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

Are there any plans on adding support for NestJS v8? Has anyone had any luck using the current version with v8 (I haven't tried yet)?

Parameter 'pg' implicitly has an 'any' type in @Inject(NEST_PGPROMISE_CONNECTION)

The current README.md says the code constructor(@Inject(NEST_PGPROMISE_CONNECTION) private readonly pg){} must be added in the service where you want to use pg-promise.

But if the option "strict": true is enabled in the tsconfig.json, the next warning don't let the compiler run:

{
       .....
	"owner": "typescript",
	"code": "7006",
	"severity": 8,
	"message": "Parameter 'pg' implicitly has an 'any' type.",
	"source": "ts"
       ......
}

The documentation should be updated to use the correct types, as the main advantage of Typescript is the type checking.
Right now, I don't know which type is the "pg" object, so I can solve this issue.

"RegisterAsync" Does Not Work

Hi!

When trying to inject my config service into NestPgpromiseModule the following error occurs:

[Nest] 75793   - 10/18/2019, 4:00:08 PM   [ExceptionHandler] Nest can't resolve dependencies of the NEST_PGPROMISE_OPTIONS (?). Please make sure that the argument ConfigService at index [0] is available in the NestPgpromiseModule context.

Potential solutions:
- If ConfigService is a provider, is it part of the current NestPgpromiseModule?
- If ConfigService is exported from a separate @Module, is that module imported within NestPgpromiseModule?
  @Module({
    imports: [ /* the Module containing ConfigService */ ]
  })
 +13ms
@Module({
  imports: [
    NestPgpromiseModule.registerAsync({
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) => ({connection: configService.config}),
      inject: [ConfigService],
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

I am following the example with TypeORM available here.

Also when looking at Your source code I can not determine what am I doing wrong.
Can You please provide me with an example how to correctly inject a service into Your module?

I have also provided a repository where this error occurs:
https://github.com/rosulg/example-nest-pg-promise

Best wishes,
Robin Sulg

jest test

After writing test code in JEST, prevent the following message from appearing when running "pnpm test"

Jest did not exit 1 second after test execution completed.

This usually means that the test has asynchronous tasks that were not stopped. To fix this, try running Jest with `--detectOpenHandles`."

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.