NodeJS PostgreSQL

Postgres를 NodeJS에서 사용하기 위해 제공되는 라이브러리들이 다양하지만 본 글에서는 promise를 제공해주는 pg-promise 라이브러리를 사용했다.

혹시 연습을 간단히 해보고 싶다면 아래 링크에 들어가 연습할 수 있다.

Install

npm을 이용해 pg-promise를 설치한다.

npm install pg-promise

설정파일 생성

설정파일을 분리하여 설정값이나 오브젝트들을 관리하도록 한다.
conf 디렉터리에 psql.js 파일에 아래 코드를 작성한다.

const pg_promise = require('pg-promise')({
    capSQL: true
});


const connectionData = {
        host: 'postgres-service',
        port: 5432,
        database: 'postgres',
        user: 'postgres',
        password: '비밀번호',
        max: 10, // use up to 30 connections
        allowExitOnIdle : true
    };


module.exports.pgsql = pg_promise(connectionData);
module.exports.pg_promise = pg_promise;

예시

직접 쿼리를 적용할 수 있지만 ParameterizedQuery를 이용했다.


const {  ParameterizedQuery: PQ } = require('pg-promise');
const { pgsql } = require('conf/psql');

const query = new PQ("INSERT INTO 테이블(컬럼,컬럼) VALUES($1,$2);");
pgsql.one(query, [값, 값]).then((rs) => {
	console.log(rs)
});

psql에는 결과에 따라서 one, any, result, none 등의 기능을 제공한다.
결과가 한개일때, 여러개일때, 쿼리에 대한 결과를 보고 싶을때, 결과를 볼 필요가 없을때 각각 이용하면 될 것 같다.

조회의 경우 result 사용했을 때 promise가 실행되고 then 절에서 나온 오브젝트에는 쿼리 결과 개수를 보여주는 rowCount, 쿼리 결과를 나타내는 rows를 주로 많이 사용했다.

예시는 아래와 같다.

 const selsectQuery = new PQ("SELECT * FROM schema_v1_table.tb_game_info WHERE user=$1");

        pgsql.result(selsectQuery, [user]).then((rs) => {
 
          if(rs.rowCount<1){
           console.log("Failed Query);
          }else{
           console.log(rs.rows[0].write_date)
          }

Leave a Comment