This repository has been archived by the owner on Jun 4, 2024. It is now read-only.
forked from pulumi/examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.ts
69 lines (59 loc) · 2.59 KB
/
cache.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Copyright 2016-2019, Pulumi Corporation. All rights reserved.
import * as awsx from "@pulumi/awsx";
import * as pulumi from "@pulumi/pulumi";
import * as config from "./config";
// A simple cache abstraction that wraps Redis.
export class Cache {
private readonly redis: awsx.ecs.FargateService;
private readonly endpoint: pulumi.Output<awsx.elasticloadbalancingv2.ListenerEndpoint>;
public get: (key: string) => Promise<string>;
public set: (key: string, value: string) => Promise<void>;
constructor(name: string, memory: number = 128) {
const pw = config.redisPassword;
const listener = new awsx.elasticloadbalancingv2.NetworkListener(name, { port: 6379 });
this.redis = new awsx.ecs.FargateService(name, {
taskDefinitionArgs: {
containers: {
redis: {
image: "redis:alpine",
memory: memory,
portMappings: [listener],
command: ["redis-server", "--requirepass", pw],
},
},
},
});
this.endpoint = listener.endpoint;
// Expose get/set as member fields that don't capture 'this'. That way we don't try to
// serialize pulumi resources unnecessarily into our lambdas.
this.get = key => {
const ep = listener.endpoint.get();
console.log(`Getting key '${key}' on Redis@${ep.hostname}:${ep.port}`);
const client = require("redis").createClient(ep.port, ep.hostname, { password: config.redisPassword });
return new Promise<string>((resolve, reject) => {
client.get(key, (err: any, v: any) => {
if (err) {
reject(err);
} else {
resolve(v);
}
});
});
};
this.set = (key, value) => {
const ep = listener.endpoint.get();
console.log(`Setting key '${key}' to '${value}' on Redis@${ep.hostname}:${ep.port}`);
const client = require("redis").createClient(ep.port, ep.hostname, { password: config.redisPassword });
return new Promise<void>((resolve, reject) => {
client.set(key, value, (err: any, v: any) => {
if (err) {
reject(err);
} else {
console.log("Set succeed: " + JSON.stringify(v));
resolve();
}
});
});
};
}
}