pg-lite-promise
Version:
Adapter for pg-lite & pg-promise
65 lines (64 loc) • 2.21 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildPgLitePromiseClient = buildPgLitePromiseClient;
const pg_promise_1 = __importDefault(require("pg-promise"));
const buildPgLiteAdapter = (db, queryLatency) => {
/**
* This is where the adaption for pg-promise is done.
* There are many eslint issues because this class needs to implement
* an implicit interface (pg-promise is written in vanilla js)
*/
class PgLiteClient {
on() {
// nop
}
release() { }
removeListener() { }
connect(callback) {
if (callback) {
callback(null, this, () => { });
return null;
}
return Promise.resolve(this);
}
async query(query, valuesOrCallback, callbackParam) {
let callback = callbackParam;
if (callback == null && typeof valuesOrCallback === 'function') {
callback = valuesOrCallback;
}
if (queryLatency) {
await new Promise(resolve => setTimeout(resolve, queryLatency));
}
try {
const result = await db.exec(query);
if (callback) {
callback(null, result);
return null;
}
return await new Promise(res => res(0));
}
catch (e) {
if (callback) {
setTimeout(() => callback(e), 0);
return null;
}
return new Promise((_, reject) => reject(e));
}
}
}
return {
Pool: PgLiteClient,
Client: PgLiteClient,
};
};
let count = 0;
function buildPgLitePromiseClient(db, options = {}) {
const { queryLatency, ...pgInitOptions } = options;
const pgp = (0, pg_promise_1.default)(pgInitOptions);
pgp.pg = buildPgLiteAdapter(db, queryLatency);
const pgDatabase = pgp('pg-lite-ftw #' + count++);
return pgDatabase;
}