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