andywer/pg-listen

connect function is returning undefined

tiitremmel opened this issue · 3 comments

pg-listen/src/index.ts

Lines 302 to 306 in 7dec032

async connect () {
initialize(dbClient)
await dbClient.connect()
emitter.emit("connected")
},

Is there any reason why connect() is returning undefined not dbClient? Just wondering because I need to query db also and it doesn't make sense to create another connection to db. When connect() function would return dbClient it would be possible.

Hey @tiitremmel.

Fair enough. I don't think there was any particular reason. Be aware, however, that this db connection is managed by pg-listen to serve its subscriber instance. If you were to piggyback on that connection, you would also need to handle reconnection attempts that discard that dbClient and initialize a new one.

So I would not recommend re-purposing that connection for anything else. Also seems rather unclean in terms of separation of concern. I don't think that one additional connection to the DB will have any significant impact on resource usage 😉

I'm also planning to use it but for a different reason. In some cases I want to run SELECT now() to get a much higher guarantee that the data I have in the client is up-to-date. This is how I prove I'm in-sync with the LISTEN events. It does not negate the performance benefits of LISTEN/NOTIFY when processing the LISTEN queue is more resource intense than running SELECT now() such as staying in sync with a table that has more than 1k or so data.

@andywer you seam to have a mind for the async code. I'm thinking one use-case (probably the most common) is to establish LISTEN then, when relying on the data from LISTEN, use the client to start a request and save the promise (from client.query('select now()'), then do the work optimistically (if feasible), finally await on the select now promise before returning the results. That way, this happens in parallel with the other work. That would need to receive any reconnection attempt as well, because the select now may succeed but an error could happen after that, blocking listen events.