const mongodb330PatchFunction: PatchFunction = function()

in src/diagnostic-channel-publishers/src/mongodb.pub.ts [147:188]


const mongodb330PatchFunction: PatchFunction = function(originalMongo) {
    mongodbcorePatchFunction(originalMongo); // apply mongodb-core patches
    const listener = originalMongo.instrument();
    const eventMap = {};
    const contextMap = {};
    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;
        }
        contextMap[event.requestId] = channel.bindToContext((cb) => cb());
        eventMap[event.requestId] = event;
    });

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

        if (typeof event === "object" && typeof contextMap[event.requestId] === "function") {
            contextMap[event.requestId](() => channel.publish<IMongoData>("mongodb", {startedData, event, succeeded: true}));
            delete contextMap[event.requestId];
        }
    });

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

        if (typeof event === "object" && typeof contextMap[event.requestId] === "function") {
            contextMap[event.requestId](() => channel.publish<IMongoData>("mongodb", {startedData, event, succeeded: false}));
            delete contextMap[event.requestId];
        }
    });

    return originalMongo;
};