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

Function Subscribe

cf/src/subscribe.js:4–142  ·  view source on GitHub ↗
(postgres, options)

Source from the content-addressed store, hash-verified

2const noop = () => { /* noop */ }
3
4export 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

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