Nodejs 不喜欢使用 orm 框架,分享一个自己写的 postgresql 的 sql 构造库

Nodejs 不喜欢使用 orm 框架,分享一个自己写的 postgresql 的 sql 构造库

GitHub 地址

API 文档暂时还没有,下面是使用的 demo

pg-helper

use node-postgres easier

Examples

const {PgHelper} = require('[@c_kai](/user/c_kai)/pg-helper');

// detail https://node-postgres.com/api/pool const pgHelper = new PgHelper({ host, user, password, database, port: 5432, max: 20, idleTimeoutMillis: 30000, connectionTimeoutMillis: 2000, });

insert

const result = await pgHelper.insert([{
  percentage: 0,
  type: 'public',
  params: {},
  created_by: 1,
  status: 'created',
  job_uuid: '103',
},{
  percentage: 0,
  type: 'public',
  params: {},
  created_by: 1,
  status: 'created',
  job_uuid: '104',
}], {
  tableName: 'jobs',
  returning: true,
});

delete

const result = await pgHelper.delete({}, {
  tableName: 'jobs',
  transaction,
});

update

const result = await pgHelper.update({
  type: 'pravate',
  status: 'gg',
}, {
  update: ['type', 'status'],
  tableName: 'jobs',
  returning: ['id'],
  transaction,
});

select

const result = await pgHelper.select({
  percentage: 0,
}, {
  where: {
    percentage: '= {percentage}'
    or: {
      id: '=1',
    }
  },
  schemaName: 'public',
  tableName: 'jobs',
  autoHump: false,
  count: true,
});

Run sql

await pgHelper.runSql('select now()');

// with params await pgHelper.runSql(‘select power({a}, {b})’, { a: 2, b: 4 });

Run sql use transaction

await pgHelper.runTSql([
    {
        sql: 'select now()',
    },
    {
        sql: 'select power({a}, {b})',
        params: { a: 2, b: 4}
    }
])

OR

let transaction;
try {
  transaction = await pgHelper.getTransaction();
  let result4 = await pgHelper.runSql('select {str1} || {str2}', {
    str1: 'xiao',
    str2: 'hong',
  }, {
    transaction,
  });
  transaction.commit();

console.log(result4) } catch (error) { transaction.rollback(); }


回到顶部