文章结构
    1 新建 postgres.ts 文件
    2 配置文件说明
    3 依赖引用说明
    4 API使用示例
 
1 新建 postgres.ts 文件,代码如下:
  1. import { Pool, PoolClient, QueryResult } from 'pg';
  2. import { CONFIG } from './config';
  3.  
  4. const pg_pool = new Pool(CONFIG.pg);
  5. pg_pool.on('error', (err, client) => {
  6. console.error('Error on idle client', err.message || err + '');
  7. });
  8.  
  9. class DB {
  10. private mPool: Pool;
  11. constructor(pool: Pool) {
  12. this.mPool = pool;
  13. }
  14. async connect(): Promise<DBSession> {
  15. const client = await this.mPool.connect();
  16. return new DBSession(client);
  17. }
  18.  
  19. async doTrans(callback: (dbs: DBSession) => Promise<unknown>): Promise<unknown> {
  20. const dbs = await this.connect();
  21. try {
  22. await dbs.begin();
  23. const result = await callback(dbs);
  24. await dbs.commit();
  25. return result;
  26. } catch (e) {
  27. await dbs.rollback();
  28. console.error('DB.doTrans() error, rollback:', e);
  29. throw e;
  30. } finally {
  31. dbs.close();
  32. }
  33. }
  34.  
  35. async run(callback: (dbs: DBSession) => Promise<unknown>): Promise<unknown> {
  36. const dbs = await this.connect();
  37. try {
  38. return await callback(dbs);
  39. } catch (e) {
  40. console.error('DB.execute() error:', e);
  41. throw e;
  42. } finally {
  43. dbs.close();
  44. }
  45. }
  46.  
  47. async queryList(sql: string, ...parameters: any[]): Promise<any[]> {
  48. const result = await this.mPool.query(sql, parameters);
  49. if (!result || !(result.rows instanceof Array)) {
  50. return [];
  51. }
  52. return result.rows;
  53. }
  54.  
  55. async queryFirst(sql: string, ...parameters: any[]): Promise<any> {
  56. const result = await this.mPool.query(sql, parameters);
  57. if (result && result.rowCount > 0) {
  58. return result.rows[0];
  59. } else {
  60. return null;
  61. }
  62. }
  63.  
  64. async queryValue(sql: string, ...parameters: any[]): Promise<unknown> {
  65. const result = await this.mPool.query(sql, parameters);
  66. if (result && result.rowCount > 0) {
  67. const key = result.fields[0].name;
  68. return result.rows[0][key];
  69. } else {
  70. return null;
  71. }
  72. }
  73.  
  74. async query(sql: string, ...parameters: any[]): Promise<QueryResult<any>> {
  75. return await this.mPool.query(sql, parameters);
  76. }
  77. }
  78.  
  79. const pgDB = new DB(pg_pool);
  80. export { pgDB };
  81.  
  82. class DBSession {
  83. private _client: PoolClient;
  84. private _transaction = false;
  85.  
  86. constructor(client: PoolClient) {
  87. this._client = client;
  88. }
  89. async begin(): Promise<void> {
  90. await this._client.query('begin');
  91. this._transaction = true;
  92. }
  93.  
  94. async commit(): Promise<void> {
  95. await this._client.query('commit');
  96. this._transaction = false;
  97. }
  98.  
  99. async savepoint(id: string): Promise<void> {
  100. await this._client.query('savepoint $1', [id]);
  101. }
  102.  
  103. async rollback(savepoint?: string): Promise<void> {
  104. if (savepoint) {
  105. await this._client.query('rollback to savepoint $1', [savepoint]);
  106. } else {
  107. await this._client.query('rollback');
  108. this._transaction = false;
  109. }
  110. }
  111. async queryList(sql: string, ...parameters: any[]): Promise<any[]> {
  112. const result = await this._client.query(sql, parameters);
  113. if (!result || !(result.rows instanceof Array)) {
  114. return [];
  115. }
  116. return result.rows;
  117. }
  118. async queryFirst(sql: string, ...parameters: any[]): Promise<any> {
  119. const result = await this._client.query(sql, parameters);
  120. if (result && result.rowCount > 0) {
  121. return result.rows[0];
  122. } else {
  123. return null;
  124. }
  125. }
  126. async queryValue(sql: string, ...parameters: any[]): Promise<unknown> {
  127. const result = await this._client.query(sql, parameters);
  128. if (result && result.rowCount > 0) {
  129. const key = result.fields[0].name;
  130. return result.rows[0][key];
  131. } else {
  132. return null;
  133. }
  134. }
  135. async query(sql: string, ...parameters: any[]): Promise<QueryResult<any>> {
  136. return await this._client.query(sql, parameters);
  137. }
  138.  
  139. close() {
  140. if (this._transaction) {
  141. this.rollback();
  142. }
  143. this._client.release();
  144. }
  145. }

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

  1. import ps from 'process';
  2.  
  3. export const CONFIG = {
  4. pg: {
  5. connectionString: ps.env.PG_URL || 'postgresql://用户名:密码@IP:端口/数据库',
  6. max: 1,
  7. min: 0,
  8. idleTimeoutMillis: 30000,
  9. },
  10. };

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

3 文章中依赖引用说明

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

4 使用示例

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

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

4.1  查询单值

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

4.2 查询单行数据

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

4.3 查询List多行数据

  1. const QUERY_LIST_SQL = `
  2. select id,name from tb_table a where id = $1 or id = $2
  3. `;
  4.  
  5. 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. hover特效

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  2. 移动端input的disabled属性对字体颜色影响

    对于表单输入,input是很好的选择,这次记录主要是正对input的value值字体在Android和iOS(11)设备下显示不同问题: 如下图:1.2的区别主要是分别设置disabled.reado ...

  3. HCNP Routing&Switching之RSTP保护

    前文我们了解了RSTP相关话题,回顾请参考https://www.cnblogs.com/qiuhom-1874/p/16240348.html:今天我们来聊一聊RSTP保护相关话题: 我们知道RST ...

  4. MySQL深入学习-day1

    书名<MySQL是怎样运行的:从根儿上理解MySQL>可自行百度 以下是知识点总结 重新认识Mysql MySQL是一个C/S架构的软件. 在Windows安装后首先注册成服务,然后会在开 ...

  5. 将MySQL查询结果导出到Excel

    总结将mysql的查询结果导出到文件的方法 总结 使用命令 select user, host, password from mysql.user into outfile '/tmp/user.xl ...

  6. 通过python将阿里云DNS解析作为DDNS使用

    通过python将阿里云DNS解析作为DDNS使用 脚本需要Python2.x运行 安装alidns python sdk sudo pip install aliyun-python-sdk-ali ...

  7. CoaXPress 时间戳 Time Stamping

    背景 在CXP2.0之前,CXP没有定义Time Stamping时间戳的概念,但是用户对Time Stamping是有实际需求的,比如我们要对比多台设备拍摄同一个物体不同角度的照片,或者记录触发完成 ...

  8. Linux 中递归删除文件

    递归删除当前目录下以 .json 结尾的文件 find . -name "*.json" | xargs rm -f find . -name "*.json" ...

  9. 『忘了再学』Shell流程控制 — 33、if条件判断语句(一)

    目录 1.单分支if条件语句 2.双分支if条件语句 (1)示例1 (2)示例2 什么是流程控制? 普通理解:Shell编写的程序是顺序执行的,也就是说第一命令先执行,然后接着执行第二条命令,然后再下 ...

  10. Typora图片与阿里云OSS图床的结合之旅

    图床? 专门用于存放图片,并允许用户通过独一的外链进行特定图片资源的访问 为什么是阿里云OSS(Object Storage Service) 码云开源需要审核,已经不能作为免费的图床使用(2022年 ...