@aws-lambda-powertools/metrics
Version:
The metrics package for the Powertools for AWS Lambda (TypeScript) library
49 lines (48 loc) • 1.64 kB
JavaScript
import '@aws/lambda-invoke-store';
import { shouldUseInvokeStore } from '@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 (!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 (!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, {});
}
}
export { MetadataStore };