| 7 | module.exports = createPostgresPool; |
| 8 | |
| 9 | function createPostgresPool(url = process.env.POSTGRES_URL) { |
| 10 | return function postgres(next) { |
| 11 | const pool = new Pool( |
| 12 | ...(url |
| 13 | ? [ |
| 14 | { |
| 15 | connectionString: url |
| 16 | } |
| 17 | ] |
| 18 | : []) |
| 19 | ); |
| 20 | const namespace = createNamespace('postgres'); |
| 21 | orm.setConnection(async () => { |
| 22 | const connector = namespace.get('getConnection'); |
| 23 | if (typeof connector !== 'function') { |
| 24 | throw new Error( |
| 25 | 'Accessing postgres outside the context of a request? UNACCEPTABLE' |
| 26 | ); |
| 27 | } |
| 28 | |
| 29 | const connection = await connector(); |
| 30 | return { |
| 31 | connection, |
| 32 | release() {} |
| 33 | }; |
| 34 | }); |
| 35 | |
| 36 | return async function inner(context) { |
| 37 | let client = null; |
| 38 | context.getPostgresClient = async () => { |
| 39 | if (client) { |
| 40 | return client; |
| 41 | } |
| 42 | |
| 43 | client = await pool.connect(); |
| 44 | return client; |
| 45 | }; |
| 46 | |
| 47 | try { |
| 48 | const response = await namespace.runAndReturn(async () => { |
| 49 | namespace.set('getConnection', () => context.getPostgresClient()); |
| 50 | return next(context); |
| 51 | }); |
| 52 | |
| 53 | return response; |
| 54 | } finally { |
| 55 | context.getPostgresClient = fail; |
| 56 | if (client) { |
| 57 | client.release(); |
| 58 | } |
| 59 | } |
| 60 | }; |
| 61 | }; |
| 62 | } |
| 63 | |
| 64 | async function fail() { |
| 65 | throw new Error( |