forked from StellarSplit/StellarSplit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathredis.config.ts
More file actions
76 lines (67 loc) · 1.96 KB
/
Copy pathredis.config.ts
File metadata and controls
76 lines (67 loc) · 1.96 KB
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
69
70
71
72
73
74
75
76
import { ConfigService } from "@nestjs/config";
type RedisConnectionOptions = {
host: string;
port: number;
username?: string;
password?: string;
};
function getString(
configService: Pick<ConfigService, "get">,
...keys: string[]
): string | undefined {
for (const key of keys) {
const value = configService.get<string>(key);
if (typeof value === "string" && value.length > 0) {
return value;
}
}
return undefined;
}
export function getRedisConnectionOptions(
configService: Pick<ConfigService, "get">,
): RedisConnectionOptions {
const redisUrl = getString(configService, "REDIS_URL");
if (redisUrl) {
const parsed = new URL(redisUrl);
return {
host: parsed.hostname,
port: parsed.port ? parseInt(parsed.port, 10) : 6379,
...(parsed.username
? { username: decodeURIComponent(parsed.username) }
: {}),
...(parsed.password
? { password: decodeURIComponent(parsed.password) }
: {}),
};
}
const host =
getString(configService, "REDIS_HOST", "REDISHOST") ?? "localhost";
const rawPort =
getString(configService, "REDIS_PORT", "REDISPORT") ?? "6379";
const username = getString(configService, "REDIS_USERNAME", "REDISUSER");
const password = getString(
configService,
"REDIS_PASSWORD",
"REDISPASSWORD",
);
return {
host,
port: parseInt(rawPort, 10),
...(username ? { username } : {}),
...(password ? { password } : {}),
};
}
export function getRedisUrl(
configService: Pick<ConfigService, "get">,
): string {
const url = getString(configService, "REDIS_URL");
if (url) return url;
const options = getRedisConnectionOptions(configService);
const user = options.username ? encodeURIComponent(options.username) : "";
const pass = options.password ? encodeURIComponent(options.password) : "";
let auth = "";
if (user || pass) {
auth = `${user}:${pass}@`;
}
return `redis://${auth}${options.host}:${options.port}`;
}