UNPKG

@zakyyudha/http-context-middleware

Version:

HTTP context middleware using Node.js AsyncLocalStorage

37 lines (36 loc) 1.11 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const async_hooks_1 = require("async_hooks"); // Create AsyncLocalStorage instance const asyncLocalStorage = new async_hooks_1.AsyncLocalStorage(); class HttpContext { constructor() { } static getInstance() { if (!HttpContext.instance) { HttpContext.instance = new HttpContext(); } return HttpContext.instance; } getContext() { return asyncLocalStorage.getStore() || null; } get(key) { const context = this.getContext(); return context ? context[key] : undefined; } set(key, value) { const context = this.getContext(); if (context) { context[key] = value; return true; } return false; } runWithContext(context, callback) { return asyncLocalStorage.run(context, callback); } generateRequestId() { return (Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)); } } exports.default = HttpContext.getInstance();