All files / src Env.ts

87.27% Statements 48/55
71.42% Branches 5/7
100% Functions 5/5
87.27% Lines 48/55

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 77 78 79 801x                                         1x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x   192x 192x 192x 192x 192x 192x 192x           192x 192x   80x 80x 80x   16x 16x 16x 16x 16x     16x   16x 16x 16x 16x 16x 16x 16x  
import { SecretString } from "@messaging-gateway/lib";
import { isLogLevelString, LogLevelString } from "@/Logger";
 
export interface EnvParam {
  appName: string;
  logLevel: LogLevelString;
  encryptionPassword: SecretString;
  redisHost: string;
  redisPort: number;
  redisMaxRetriesPerRequest: number;
  redisStreamPrefixForLine: string;
  redisGroupNameForLine: string;
  cleanerConsumerName: string;
  cleanerMinIdleMs: number;
  cleanerBatchSize: number;
  cleanerIntervalMs: number;
}
 
export type OptionalEnvParam = Partial<EnvParam>;
export type Env = Readonly<EnvParam>;
 
export function createEnvParamFromProcessEnv(env: NodeJS.ProcessEnv): EnvParam {
  return {
    appName: getStringValue(env, "APP_NAME"),
    logLevel: getLogLevel(env, "LOG_LEVEL"),
    encryptionPassword: getSecretStringValue(env, "ENCRYPTION_PASSWORD"),
    redisHost: getStringValue(env, "REDIS_HOST"),
    redisPort: getNumberValue(env, "REDIS_PORT"),
    redisMaxRetriesPerRequest: getNumberValue(
      env,
      "REDIS_MAX_RETRIES_PER_REQUEST"
    ),
    redisStreamPrefixForLine: getStringValue(
      env,
      "REDIS_STREAM_PREFIX_FOR_LINE"
    ),
    redisGroupNameForLine: getStringValue(env, "REDIS_GROUP_NAME_FOR_LINE"),
    cleanerConsumerName: getStringValue(env, "CLEANER_CONSUMER_NAME"),
    cleanerMinIdleMs: getNumberValue(env, "CLEANER_MIN_IDLE_MS"),
    cleanerBatchSize: getNumberValue(env, "CLEANER_BATCH_SIZE"),
    cleanerIntervalMs: getNumberValue(env, "CLEANER_INTERVAL_MS"),
  };
}
 
function getStringValue(
  env: NodeJS.ProcessEnv,
  key: string,
  required: boolean = true
): string {
  const value = env[key];
  if (value === undefined) {
    if (required) {
      throw new Error(`environment[${key}] is not found`);
    }
    return "";
  }
  return value;
}
 
function getNumberValue(env: NodeJS.ProcessEnv, key: string): number {
  return Number(getStringValue(env, key));
}
 
function getLogLevel(env: NodeJS.ProcessEnv, key: string): LogLevelString {
  const s = getStringValue(env, key);
  if (isLogLevelString(s)) {
    return s;
  } else {
    throw new Error(`environment[${key}] is invalid value[${s}]`);
  }
}
 
function getSecretStringValue(
  env: NodeJS.ProcessEnv,
  key: string
): SecretString {
  const s = getStringValue(env, key);
  return new SecretString(s);
}