在节点全局范围内使用await可以加载db client吗?
我正在尝试使用ms的Postgres客户端pg
。在示例中,它使用以下代码:
const { Client } = require('pg')
const client = new Client()
await client.connect()
const res = await client.query('SELECT $1::text as message', ['Hello world!'])
console.log(res.rows[0].message) // Hello world!
await client.end()
我理解async / await函数语法要求您在声明为async的函数中编写await语句。但是,通常在连接数据库客户端时,将其连接到函数之外和全局范围内。有没有使用异步函数的最佳实践而不必将客户端包装在函数中?
似乎要使用这种语法,我们不得不诉诸以下内容:
const { Client } = require('pg');
const client = new Client();
async connectClient (client) {
await client.connect();
return client;
}
async disconnectClient(client) {
await client.end()
}
也许我在这里的理解中遗漏了一些东西。
回答如下:但是,通常在连接数据库客户端时,将其连接到函数之外和全局范围内。有没有最好的做法..?
您可以使用连接池技术
为了使用连接池的最佳实践。尝试在您的应用程序中实现OOP设计元素。如类和继承。
Service.ts
import { Pool } from 'pg';
export class Service {
protected pool: Pool;
constructor() {
this.pool = new Pool({
database: process.env.DB_DATABASE,
host: process.env.DB_HOST,
password: process.env.DB_PASS,
port: process.env.DB_PORT,
user: process.env.DB_USER,
});
}
扩展基类Service
的示例服务类:
AuthnService.ts
export class AuthService extends Service {
private key: string;
constructor() {
super();
this.key = process.env.SECRET_KEY;
}
// Example async function that shows the usage of pg with async/await
public async isUserExists(username: string, email?: string): Promise<boolean> {
const client = await this.pool.connect(); //Pool is now accessible over here
try {
let res = await client.query('SELECT * FROM users WHERE username = $1', [ username ]);
if (res.rows[0]) {
return res.rows[0];
} else if (email) {
res = await client.query('SELECT * FROM users WHERE email = $1', [ email ]);
if (res.rows[0]) {
return res.rows[0];
}
}
} catch (e) {
throw new Error(e);
} finally {
client.release(); // Release for other connections to use
}
return false;
}
}
}
更多信息:node-postgres docs