UNPKG

unleash-server

Version:

Unleash is an enterprise ready feature flag service. It provides different strategies for handling feature flags.

38 lines 1.24 kB
import pg from 'pg'; const { Client } = pg; export const defaultLockKey = 479341; export const defaultTimeout = 30 * 60000; const defaultOptions = { timeout: defaultTimeout, lockKey: defaultLockKey, logger: { ...console, fatal: console.error }, }; export const withDbLock = (dbConfig, config = defaultOptions) => (fn) => async (...args) => { const client = new Client({ ...dbConfig, }); let lockAcquired = false; try { await client.connect(); // wait to obtain a lock await client.query('SELECT pg_advisory_lock($1)', [config.lockKey]); lockAcquired = true; const promise = fn(...args); const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error('Query read timeout')), config.timeout)); const result = (await Promise.race([promise, timeoutPromise])); return result; } catch (e) { config.logger.error(`Locking error: ${e.message}`); throw e; } finally { if (lockAcquired) { await client.query('SELECT pg_advisory_unlock($1)', [ config.lockKey, ]); } await client.end(); } }; //# sourceMappingURL=db-lock.js.map