Skip to content

Commit b51de61

Browse files
committed
Initial commit
0 parents  commit b51de61

File tree

8 files changed

+5493
-0
lines changed

8 files changed

+5493
-0
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
node_modules
2+
build

lib/SecretCache.test.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import {
2+
GetSecretValueCommand,
3+
SecretsManager,
4+
} from "@aws-sdk/client-secrets-manager";
5+
import { mockClient } from "aws-sdk-client-mock";
6+
import { SecretCacheImpl } from "./SecretCache.js";
7+
8+
describe("SecretCache", () => {
9+
it("should return secret value object", async () => {
10+
// ARRANGE
11+
const secretManagerMock = mockClient(SecretsManager);
12+
const secretCache = new SecretCacheImpl({
13+
secretsManager: new SecretsManager({}),
14+
});
15+
16+
secretManagerMock.on(GetSecretValueCommand).resolves({
17+
SecretString: JSON.stringify({ foo: "bar" }),
18+
});
19+
20+
// ACT
21+
const secretObject = await secretCache.getSecretValue("secret1");
22+
23+
// ASSERT
24+
expect(secretObject).toEqual({ foo: "bar" });
25+
expect(secretManagerMock).toHaveReceivedCommandWith(GetSecretValueCommand, {
26+
SecretId: "secret1",
27+
});
28+
});
29+
});

lib/SecretCache.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import { SecretsManager } from "@aws-sdk/client-secrets-manager";
2+
3+
interface Dependencies {
4+
secretsManager: SecretsManager;
5+
}
6+
7+
export interface SecretCache {
8+
getSecretValue<T>(secretName: string): Promise<T>;
9+
}
10+
11+
export class SecretCacheImpl implements SecretCache {
12+
private readonly secretsManager: SecretsManager;
13+
private readonly cache = new Map<string, string>();
14+
15+
constructor(dep: Dependencies) {
16+
this.secretsManager = dep.secretsManager;
17+
}
18+
19+
getSecretValue = async <T>(secretId: string): Promise<T> => {
20+
const cacheValue = this.cache.get(secretId);
21+
if (cacheValue) {
22+
return JSON.parse(cacheValue) as T;
23+
}
24+
25+
const { SecretString: secretValue } =
26+
await this.secretsManager.getSecretValue({
27+
SecretId: secretId,
28+
});
29+
if (!secretValue) {
30+
throw new Error(`Could not retrieve secret '${secretId}'.`);
31+
}
32+
this.cache.set(secretId, secretValue);
33+
return JSON.parse(secretValue) as T;
34+
};
35+
}

0 commit comments

Comments
 (0)