correlation-id-ts
Version:
Add correlation id to your functions context
50 lines (49 loc) • 1.92 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.runWithNewCorrelationId = exports.correlator = void 0;
var node_async_hooks_1 = require("node:async_hooks");
var node_crypto_1 = require("node:crypto");
var asyncLocalStorage = new node_async_hooks_1.AsyncLocalStorage();
var withIdFn = function (_a) {
var correlationId = _a.correlationId, fn = _a.fn;
return asyncLocalStorage.run({ correlationId: correlationId }, function () { return fn(); });
};
var bindIdFn = function (_a) {
var correlationId = _a.correlationId, fn = _a.fn;
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return asyncLocalStorage.run({ correlationId: correlationId }, function () { return fn.apply(void 0, args); });
};
};
var configureArgs = function (func) {
return function (_a) {
var correlationId = _a.correlationId, fn = _a.fn;
if (!fn) {
throw Error("Missing fn parameter");
}
var id = correlationId !== null && correlationId !== void 0 ? correlationId : (0, node_crypto_1.randomUUID)();
return func({ correlationId: id, fn: fn });
};
};
var getId = function () {
var _a;
var store = asyncLocalStorage.getStore();
return (_a = store === null || store === void 0 ? void 0 : store.correlationId) !== null && _a !== void 0 ? _a : null;
};
exports.correlator = {
withId: configureArgs(withIdFn),
bindId: configureArgs(bindIdFn),
getId: getId,
};
function runWithNewCorrelationId(runFunction) {
var _a;
var id = (_a = exports.correlator.getId()) !== null && _a !== void 0 ? _a : (0, node_crypto_1.randomUUID)();
exports.correlator.withId({
correlationId: id,
fn: function () { return runFunction(id); },
});
}
exports.runWithNewCorrelationId = runWithNewCorrelationId;