UNPKG

825 BPlain TextView Raw
1import * as fs from 'fs'
2import type { ValuesOf } from '@naturalcycles/js-lib'
3import 'dotenv/config' // ensure .env is read before requiring keys
4
5/**
6 * @example
7 *
8 * const {a, b} = requreEnvKeys(['a', 'b'])
9 *
10 * Will throw if any of the passed keys is not defined.
11 */
12export function requireEnvKeys<T extends readonly string[]>(
13 ...keys: T
14): { [k in ValuesOf<T>]: string } {
15 // eslint-disable-next-line unicorn/no-array-reduce
16 return keys.reduce((r, k) => {
17 const v = process.env[k]
18 if (!v) throw new Error(`${k} env variable is required, but missing`)
19 r[k as ValuesOf<T>] = v
20 return r
21 }, {} as { [k in ValuesOf<T>]: string })
22}
23
24export function requireFileToExist(filePath: string): void {
25 if (!fs.existsSync(filePath)) {
26 throw new Error(`Required file should exist: ${filePath}`)
27 }
28}