MCPcopy Create free account
hub / github.com/porsager/postgres / Subscribe

Function Subscribe

cjs/src/subscribe.js:3–141  ·  view source on GitHub ↗
(postgres, options)

Source from the content-addressed store, hash-verified

1const noop = () => { /* noop */ }
2
3module.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

Callers 1

PostgresFunction · 0.70

Calls 7

postgresFunction · 0.70
connectedFunction · 0.70
initFunction · 0.70
endFunction · 0.70
closeFunction · 0.70
forEachMethod · 0.65
endMethod · 0.65

Tested by

no test coverage detected