78 lines
2.1 KiB
TypeScript
78 lines
2.1 KiB
TypeScript
export interface RedisClientOptions {
|
|
password?: string;
|
|
url: string;
|
|
username?: string;
|
|
}
|
|
|
|
export interface ResolveRedisClientOptionsParams {
|
|
endpoint?: string;
|
|
endpointEnvName?: string;
|
|
password?: string;
|
|
url?: string;
|
|
urlEnvName?: string;
|
|
username?: string;
|
|
}
|
|
|
|
function trimOptional(value: string | undefined): string | undefined {
|
|
const trimmed = value?.trim();
|
|
return trimmed ? trimmed : undefined;
|
|
}
|
|
|
|
export function normalizeRedisUrl(
|
|
endpointOrUrl: string,
|
|
envName = 'REDIS_URL',
|
|
): string {
|
|
const trimmed = endpointOrUrl.trim();
|
|
if (!trimmed) {
|
|
throw new Error(`${envName} cannot be empty`);
|
|
}
|
|
if (/^redis(s)?:\/\//iu.test(trimmed)) {
|
|
return trimmed;
|
|
}
|
|
return `redis://${trimmed}`;
|
|
}
|
|
|
|
export function resolveRedisClientOptions(
|
|
params: ResolveRedisClientOptionsParams,
|
|
): RedisClientOptions {
|
|
const url = trimOptional(params.url);
|
|
const endpoint = trimOptional(params.endpoint);
|
|
const selectedEndpoint = url ?? endpoint;
|
|
const selectedEnvName = url
|
|
? (params.urlEnvName ?? 'REDIS_URL')
|
|
: (params.endpointEnvName ?? 'REDIS_ENDPOINT');
|
|
|
|
if (!selectedEndpoint) {
|
|
throw new Error(`${selectedEnvName} cannot be empty`);
|
|
}
|
|
|
|
const options: RedisClientOptions = {
|
|
url: normalizeRedisUrl(selectedEndpoint, selectedEnvName),
|
|
};
|
|
const username = trimOptional(params.username);
|
|
const password = trimOptional(params.password);
|
|
if (username) options.username = username;
|
|
if (password) options.password = password;
|
|
return options;
|
|
}
|
|
|
|
function parseRedisInstanceIdentity(redisUrl: string): string {
|
|
const url = new URL(normalizeRedisUrl(redisUrl));
|
|
const hostname = url.hostname.toLowerCase();
|
|
const port = url.port || '6379';
|
|
return `${hostname}:${port}`;
|
|
}
|
|
|
|
export function assertDistinctRedisInstances(
|
|
redisUrl: string,
|
|
auctionRedisUrl: string,
|
|
): void {
|
|
const redisIdentity = parseRedisInstanceIdentity(redisUrl);
|
|
const auctionRedisIdentity = parseRedisInstanceIdentity(auctionRedisUrl);
|
|
if (redisIdentity === auctionRedisIdentity) {
|
|
throw new Error(
|
|
'AUCTION_REDIS must use a separate Redis instance from REDIS because auction Redis is a live state source of truth.',
|
|
);
|
|
}
|
|
}
|