UNPKG

aws-secrets-manager-cache

Version:

A package to help you out when wanting to cache items from AWS Secrets Manager.

52 lines (51 loc) 1.87 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const aws_sdk_1 = require("aws-sdk"); const defaultTTL = (5 * 60 * 1000); // 5 minutes class CachedSecret { constructor(value, ttl) { this.value = value; this.ttl = ttl; this.expiresAt = Date.now() + ttl; } hasExpired() { return (Date.now() > this.expiresAt); } } exports.CachedSecret = CachedSecret; class SecretsManagerCache { constructor(options) { this.cache = new Map(); this.config = Object.assign({ // set defaults ttl: defaultTTL, secretsManager: new aws_sdk_1.SecretsManager() }, options); } /** * Fetches a secret from SecretsManager and caches it as long as the given * `ttl`. */ async getSecret(secretName, isJSON = false) { var _a, _b; const itemExistsInCache = this.cache.has(secretName); const itemHasExpired = (_a = this.cache.get(secretName)) === null || _a === void 0 ? void 0 : _a.hasExpired(); if (!itemExistsInCache || itemHasExpired) { const getSecretValueResponse = await this.config.secretsManager .getSecretValue({ SecretId: secretName }) .promise(); if (getSecretValueResponse.SecretString) { this.cache.set(secretName, new CachedSecret(getSecretValueResponse.SecretString, this.config.ttl)); } } const secret = (_b = this.cache.get(secretName)) === null || _b === void 0 ? void 0 : _b.value; if (isJSON) { try { return JSON.parse(secret); } catch (error) { throw new Error('Attempted to parse non-JSON secret string as JSON.'); } } return secret; } } exports.SecretsManagerCache = SecretsManagerCache;