39 lines
1.0 KiB
TypeScript
39 lines
1.0 KiB
TypeScript
import logger from 'log'
|
|
import fs from 'node:fs/promises'
|
|
|
|
import type {Ok} from './helpers'
|
|
|
|
const log = logger('config:read_env')
|
|
const FILE_EXT = "__FILE"
|
|
|
|
// Read from env or file
|
|
export async function read_env(key: string): Promise<Ok<string | undefined>> {
|
|
const path = process.env[key + FILE_EXT]
|
|
if (path !== undefined) return from_file(path)
|
|
else return {ok: true, data: process.env[key]}
|
|
}
|
|
async function from_file(path: string): Promise<Ok<string>> {
|
|
log.debug("Read a key from a file")
|
|
log.trace("Path :", path)
|
|
|
|
let content = await get_file_content(path)
|
|
if (!content.ok) return content
|
|
|
|
content.data = content.data.trim()
|
|
|
|
return content
|
|
}
|
|
async function get_file_content(path: string) : Promise<Ok<string>> {
|
|
log.debug('Read file content')
|
|
log.trace('Path :', path)
|
|
|
|
try {
|
|
const data = await fs.readFile(path, {encoding: 'utf-8'})
|
|
return {ok: true, data}
|
|
} catch (e) {
|
|
log.warn('Failed to read file', path)
|
|
log.debug('Error :', e)
|
|
return {ok: false}
|
|
}
|
|
}
|