function patchCallback()

in src/diagnostic-channel-publishers/src/pg.pub.ts [54:90]


        function patchCallback(cb?: PostgresCallback): PostgresCallback {
            if (cb && cb[diagnosticOriginalFunc]) {
                cb = cb[diagnosticOriginalFunc];
            }

            const trackingCallback = channel.bindToContext(function(err: Error, res: IPostgresResult): any {
                const end = process.hrtime(start);
                data.result = res && { rowCount: res.rowCount, command: res.command };
                data.error = err;
                data.duration = Math.ceil((end[0] * 1e3) + (end[1] / 1e6));
                channel.publish("postgres", data);

                // emulate weird internal behavior in pg@6
                // on success, the callback is called *before* query events are emitted
                // on failure, the callback is called *instead of* the query emitting events
                // with no events, that means no promises (since the promise is resolved/rejected in an event handler)
                // since we are always inserting ourselves as a callback, we have to restore the original
                // behavior if the user didn't provide one themselves
                if (err) {
                    if (cb) {
                        return cb.apply(this, arguments);
                    } else if (queryResult && queryResult instanceof EventEmitter) {
                        queryResult.emit("error", err);
                    }
                } else if (cb) {
                    cb.apply(this, arguments);
                }
            });

            try {
                Object.defineProperty(trackingCallback, diagnosticOriginalFunc, { value: cb });
                return trackingCallback;
            } catch (e) {
                // this should never happen, but bailout in case it does
                return cb;
            }
        }