30 lines
878 B
JavaScript
30 lines
878 B
JavaScript
// packages/api/v1/repositories/db.mjs
|
|
|
|
import { poolTenants } from '@suitecoffee/db';
|
|
|
|
const VALID_IDENT = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
|
|
|
|
export async function withTenantClient(req, fn, { trx = false } = {}) {
|
|
const schema = req?.tenant?.schema;
|
|
if (!schema || !VALID_IDENT.test(schema)) {
|
|
throw new Error('Schema de tenant no resuelto/ inválido');
|
|
}
|
|
const client = await poolTenants.connect();
|
|
try {
|
|
if (trx) await client.query('BEGIN');
|
|
await client.query(`SET LOCAL search_path = "${schema}", public`);
|
|
const result = await fn(client);
|
|
if (trx) await client.query('COMMIT');
|
|
return result;
|
|
} catch (e) {
|
|
if (trx) await client.query('ROLLBACK');
|
|
throw e;
|
|
} finally {
|
|
client.release();
|
|
}
|
|
}
|
|
|
|
export async function tquery(req, sql, params = [], opts = {}) {
|
|
return withTenantClient(req, (c) => c.query(sql, params), opts);
|
|
}
|