UNPKG

@aws-lambda-powertools/metrics

Version:
52 lines (51 loc) 1.77 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MetadataStore = void 0; require("@aws/lambda-invoke-store"); const env_1 = require("@aws-lambda-powertools/commons/utils/env"); /** * Manages storage of metrics #metadata with automatic context detection. * * This class abstracts the storage mechanism for metrics, automatically * choosing between AsyncLocalStorage (when in async context) and a fallback * object (when outside async context). The decision is made at runtime on * every method call to support Lambda's transition to async contexts. */ class MetadataStore { #metadataKey = Symbol('powertools.metrics.metadata'); #fallbackStorage = {}; #getStorage() { if (!(0, env_1.shouldUseInvokeStore)()) { return this.#fallbackStorage; } if (globalThis.awslambda?.InvokeStore === undefined) { throw new Error('InvokeStore is not available'); } const store = globalThis.awslambda.InvokeStore; let stored = store.get(this.#metadataKey); if (stored == null) { stored = {}; store.set(this.#metadataKey, stored); } return stored; } set(key, value) { this.#getStorage()[key] = value; return value; } getAll() { return { ...this.#getStorage() }; } clear() { if (!(0, env_1.shouldUseInvokeStore)()) { this.#fallbackStorage = {}; return; } if (globalThis.awslambda?.InvokeStore === undefined) { throw new Error('InvokeStore is not available'); } const store = globalThis.awslambda.InvokeStore; store.set(this.#metadataKey, {}); } } exports.MetadataStore = MetadataStore;