const mongodbPatchFunction: PatchFunction = function()

in src/diagnostic-channel-publishers/src/mongodb.pub.ts [20:69]


const mongodbPatchFunction: PatchFunction = function(originalMongo) {
    const listener = originalMongo.instrument({
        operationIdGenerator: {
            next: function() {
                return channel.bindToContext((cb) => cb());
            },
        },
    });
    const eventMap = {};
    listener.on("started", function(event) {
        if (eventMap[event.requestId]) {
            // Note: Mongo can generate 2 completely separate requests
            // which share the same requestId, if a certain race condition is triggered.
            // For now, we accept that this can happen and potentially miss or mislabel some events.
            return;
        }
        eventMap[event.requestId] = { ...event, time: new Date() } as IMongoData["startedData"];
    });

    listener.on("succeeded", function(event) {
        const startedData = eventMap[event.requestId];
        if (startedData) {
            delete eventMap[event.requestId];
        }

        if (typeof event.operationId === "function") {
            event.operationId(() => channel.publish<IMongoData>("mongodb", {startedData, event, succeeded: true}));
        } else {
            // fallback -- correlation will not work here
            channel.publish<IMongoData>("mongodb", {startedData, event, succeeded: true});
        }
    });

    listener.on("failed", function(event) {
        const startedData = eventMap[event.requestId];
        if (startedData) {
            delete eventMap[event.requestId];
        }

        if (typeof event.operationId === "function") {
            event.operationId(() => channel.publish<IMongoData>("mongodb", {startedData, event, succeeded: false}));
        } else {
            // fallback -- correlation will not work here
            channel.publish<IMongoData>("mongodb", {startedData, event, succeeded: false});
        }

    });

    return originalMongo;
};