| 1 | const noop = () => { /* noop */ } |
| 2 | |
| 3 | module.exports = Subscribe;function Subscribe(postgres, options) { |
| 4 | const subscribers = new Map() |
| 5 | , slot = 'postgresjs_' + Math.random().toString(36).slice(2) |
| 6 | , state = {} |
| 7 | |
| 8 | let connection |
| 9 | , stream |
| 10 | , ended = false |
| 11 | |
| 12 | const sql = subscribe.sql = postgres({ |
| 13 | ...options, |
| 14 | transform: { column: {}, value: {}, row: {} }, |
| 15 | max: 1, |
| 16 | fetch_types: false, |
| 17 | idle_timeout: null, |
| 18 | max_lifetime: null, |
| 19 | connection: { |
| 20 | ...options.connection, |
| 21 | replication: 'database' |
| 22 | }, |
| 23 | onclose: async function() { |
| 24 | if (ended) |
| 25 | return |
| 26 | stream = null |
| 27 | state.pid = state.secret = undefined |
| 28 | connected(await init(sql, slot, options.publications)) |
| 29 | subscribers.forEach(event => event.forEach(({ onsubscribe }) => onsubscribe())) |
| 30 | }, |
| 31 | no_subscribe: true |
| 32 | }) |
| 33 | |
| 34 | const end = sql.end |
| 35 | , close = sql.close |
| 36 | |
| 37 | sql.end = async() => { |
| 38 | ended = true |
| 39 | stream && (await new Promise(r => (stream.once('close', r), stream.end()))) |
| 40 | return end() |
| 41 | } |
| 42 | |
| 43 | sql.close = async() => { |
| 44 | stream && (await new Promise(r => (stream.once('close', r), stream.end()))) |
| 45 | return close() |
| 46 | } |
| 47 | |
| 48 | return subscribe |
| 49 | |
| 50 | async function subscribe(event, fn, onsubscribe = noop, onerror = noop) { |
| 51 | event = parseEvent(event) |
| 52 | |
| 53 | if (!connection) |
| 54 | connection = init(sql, slot, options.publications) |
| 55 | |
| 56 | const subscriber = { fn, onsubscribe } |
| 57 | const fns = subscribers.has(event) |
| 58 | ? subscribers.get(event).add(subscriber) |
| 59 | : subscribers.set(event, new Set([subscriber])).get(event) |
| 60 | |