文章结构
    1 新建 postgres.ts 文件
    2 配置文件说明
    3 依赖引用说明
    4 API使用示例
 
1 新建 postgres.ts 文件,代码如下:
import { Pool, PoolClient, QueryResult } from 'pg';
import { CONFIG } from './config'; const pg_pool = new Pool(CONFIG.pg);
pg_pool.on('error', (err, client) => {
console.error('Error on idle client', err.message || err + '');
}); class DB {
private mPool: Pool;
constructor(pool: Pool) {
this.mPool = pool;
}
async connect(): Promise<DBSession> {
const client = await this.mPool.connect();
return new DBSession(client);
} async doTrans(callback: (dbs: DBSession) => Promise<unknown>): Promise<unknown> {
const dbs = await this.connect();
try {
await dbs.begin();
const result = await callback(dbs);
await dbs.commit();
return result;
} catch (e) {
await dbs.rollback();
console.error('DB.doTrans() error, rollback:', e);
throw e;
} finally {
dbs.close();
}
} async run(callback: (dbs: DBSession) => Promise<unknown>): Promise<unknown> {
const dbs = await this.connect();
try {
return await callback(dbs);
} catch (e) {
console.error('DB.execute() error:', e);
throw e;
} finally {
dbs.close();
}
} async queryList(sql: string, ...parameters: any[]): Promise<any[]> {
const result = await this.mPool.query(sql, parameters);
if (!result || !(result.rows instanceof Array)) {
return [];
}
return result.rows;
} async queryFirst(sql: string, ...parameters: any[]): Promise<any> {
const result = await this.mPool.query(sql, parameters);
if (result && result.rowCount > 0) {
return result.rows[0];
} else {
return null;
}
} async queryValue(sql: string, ...parameters: any[]): Promise<unknown> {
const result = await this.mPool.query(sql, parameters);
if (result && result.rowCount > 0) {
const key = result.fields[0].name;
return result.rows[0][key];
} else {
return null;
}
} async query(sql: string, ...parameters: any[]): Promise<QueryResult<any>> {
return await this.mPool.query(sql, parameters);
}
} const pgDB = new DB(pg_pool);
export { pgDB }; class DBSession {
private _client: PoolClient;
private _transaction = false; constructor(client: PoolClient) {
this._client = client;
}
async begin(): Promise<void> {
await this._client.query('begin');
this._transaction = true;
} async commit(): Promise<void> {
await this._client.query('commit');
this._transaction = false;
} async savepoint(id: string): Promise<void> {
await this._client.query('savepoint $1', [id]);
} async rollback(savepoint?: string): Promise<void> {
if (savepoint) {
await this._client.query('rollback to savepoint $1', [savepoint]);
} else {
await this._client.query('rollback');
this._transaction = false;
}
}
async queryList(sql: string, ...parameters: any[]): Promise<any[]> {
const result = await this._client.query(sql, parameters);
if (!result || !(result.rows instanceof Array)) {
return [];
}
return result.rows;
}
async queryFirst(sql: string, ...parameters: any[]): Promise<any> {
const result = await this._client.query(sql, parameters);
if (result && result.rowCount > 0) {
return result.rows[0];
} else {
return null;
}
}
async queryValue(sql: string, ...parameters: any[]): Promise<unknown> {
const result = await this._client.query(sql, parameters);
if (result && result.rowCount > 0) {
const key = result.fields[0].name;
return result.rows[0][key];
} else {
return null;
}
}
async query(sql: string, ...parameters: any[]): Promise<QueryResult<any>> {
return await this._client.query(sql, parameters);
} close() {
if (this._transaction) {
this.rollback();
}
this._client.release();
}
}

2 新建config.ts配置文件,配置数据源

import ps from 'process';

export const CONFIG = {
pg: {
connectionString: ps.env.PG_URL || 'postgresql://用户名:密码@IP:端口/数据库',
max: 1,
min: 0,
idleTimeoutMillis: 30000,
},
};

  对于数据源的配置,账号密码注意对符号进行转义。如 @ 需要转为 %40等。

3 文章中依赖引用说明

postgres依赖: "@types/pg": "^8.6.1"

4 使用示例

首先在需要的文件中导入API。文件位置按照实际进行更改。

import { pgDB } from '../postgres';

4.1  查询单值

const QUERY_VALUE_SQL = `
select name from tb_table a where a.id = $1
`;
const id = await pgDB.queryValue(
QUERY_VALUE_SQL ,
5
);

4.2 查询单行数据

const QUERY_SQL = `
select id,name from tb_table a where a.id = $1
`;
const result = await pgDB.queryFirst(QUERY_SQL , 1);

4.3 查询List多行数据

const QUERY_LIST_SQL =   `
select id,name from tb_table a where id = $1 or id = $2
`; const result = await pgDB.queryList(QUERY_LIST_SQL , 1, 2);

修改,删除,事务等示例后续补充。    

  

typescript关于postgres数据库的API封装的更多相关文章

  1. Actix-web Rust连接Postgres数据库

    Actix-web Rust连接Postgres数据库 ​ Rust1.39支持了异步async,await,Actix-web在2.0.0-alpha支持了原生异步写法,所以本文中使用的Actix- ...

  2. [Kong 与 Konga与postgres数据库] 之 Kuberneres 部署

    1.Kong的概述 Kong是一个clould-native.快速的.可扩展的.分布式的微服务抽象层(也称为API网关.API中间件或在某些情况下称为服务网格)框架.Kong作为开源项目在2015年推 ...

  3. [Kong 与 Konga 与 Postgres数据库] 之 Kuberneres 部署

    1.Kong的概述 Kong是一个clould-native.快速的.可扩展的.分布式的微服务抽象层(也称为API网关.API中间件或在某些情况下称为服务网格)框架.Kong作为开源项目在2015年推 ...

  4. C#开发微信门户及应用(32)--微信支付接入和API封装使用

    在微信的应用上,微信支付是一个比较有用的部分,但也是比较复杂的技术要点,在微商大行其道的年代,自己的商店没有增加微信支付好像也说不过去,微信支付旨在为广大微信用户及商户提供更优质的支付服务,微信的支付 ...

  5. pgadmin(IDE)工具连接postgres数据库

    1. 下载软件        软件地址:http://www.pgadmin.org/download/pgagent.php   2.安装软件    安装过程:略    打开软件64位会出现  “无 ...

  6. ubuntu crontab 定时备份postgres数据库并上传ftp服务器

    最近公司要求备份数据库,所以就查了比较作的资料.废话不多说,入正题. 目的:定期备份ubuntu下的postgres数据库,打包上传到指定ftp服务器. 经过查找资料,解决方法: ①编写备份数据库.打 ...

  7. PHP中对数据库操作的封装

    在动态网面设计中很多都要涉及到对数据库的操作,但是有时跟据需要而改用其它后台数据库,就需要大量修改程序.这是一件枯燥.费时而且容易出错的功作.其实我们可以用PHP中的类来实现对数据库操作的封装,从而使 ...

  8. postgres数据库中的数据转换

    postgres8.3以后,字段数据之间的默认转换取消了.如果需要进行数据变换的话,在postgres数据库中,我们可以用"::"来进行字段数据的类型转换.实际上"::& ...

  9. C# .NET更智能的数据库操作的封装完整版(重构)

    前述: 第一次发表文章,不过是对数据库简单的封装,主要是阐述下思路.那么在上篇文章,在大家的指导下和提出意见,并自己对代码进行了思考.在这两天我重构了新的框架,我觉得我写的可以称得上框架,为什么?请大 ...

随机推荐

  1. S2-045远程命令执行漏洞的利用

    Apache Struts2 远程命令执行 (S2-045) 漏洞介绍: 漏洞编号:S2-045CVE编号:CVE-2017-5638漏洞类型:远程代码执行漏洞级别:高危漏洞风险:黑客通过利用漏洞可以 ...

  2. Spring 源码(10)Spring Bean 的创建过程(1)

    Spring Bean的创建刚开始进行了一些准备工作,比如转换服务的初始化,占位符解析器的初始化,BeanDefinition元数据的冻结等操作,都是为了在创建Bean的过程中保证Bean的正确的创建 ...

  3. zabbix-agent python脚本侦听服务器异常登录,并告警

    py脚本 import re,subprocess,time,datetime #gpasswd -a zabbix adm def ftime(a): a = a.replace('Jan','01 ...

  4. 好客租房18-jsx阶段总结

    JSX 1jsx是react的核心内容 2jsx是在js代码中写HTML结构,是react中声明式的提现 3使用jsx配合嵌入的js表达式,条件渲染,列表渲染,可以描述任意ui结构 4推荐使用cals ...

  5. 【docker】windows 10专业版安装docker

    一.开启Hyper-V功能 二.安装 Docker Desktop for Windows(下载地址)[https://www.docker.com/get-started/] 三.安装 Window ...

  6. mysql查询关键字补充与多表查询

    目录 查询关键字补充 having过滤 distinct去重 order by排序 limit分页 regexp正则 多表查询 子查询 连表查询 查询关键字补充 having过滤 关键字having和 ...

  7. Fail2ban 术语

    filter 过滤器,使用正则表达式定义一个过滤器,从日志中匹配到IP.端口等. action 动作,定义在指定时间段要执行的操作. jail 监禁,jail是一个filter和一个action或者多 ...

  8. 无法启动报,To install it, you can run: npm install --save @/components/xxxx.vue

    运行的过程中后台报错 npm install --save @/components/xxx.vue 重装了node_modules依然没有用. 其实是组件路径写错了 总结 以后出现提醒安装那个vue ...

  9. 【Java】在IDEA中将Javafx项目打包成为可运行的.jar文件

    在使用Javafx制作一个图形化界面程序的时候,我遇到了打包文件的难题. 按照网上给出的解决方案构建出来的jar文件总是没有办法运行. 以下是我最终的解决方案. 我使用的IDE是IntelliJ ID ...

  10. 『忘了再学』Shell基础 — 25、扩展正则表达式

    目录 1.扩展正则表达式说明 2.练习 (1)+和?练习 (2)|和()练习 3.注意(重点) 1.扩展正则表达式说明 熟悉正则表达式的童鞋应该很疑惑,在其他的语言中是没有扩展正则表达式说法的,在Sh ...