import { existsSync , readFileSync } from 'fs' ; import { parseBoolean , parseJsonProperty } from '@fc/common' ; import { IConfigParserFileOptions } from '../interfaces' ; export class ConfigParser { constructor ( private readonly source , private readonly namespace , private readonly separator = '_' ) { } private getFullPath ( path ) { return `${ this . namespace }${ this . separator }${ path }` ; } boolean ( path ) { const fullPath = this . getFullPath ( path ) ; return parseBoolean ( this . source [ fullPath ] ) ; } json ( path ) { const fullPath = this . getFullPath ( path ) ; return parseJsonProperty ( this . source , fullPath ) ; } string ( path ) { const fullPath = this . getFullPath ( path ) ; return this . source [ fullPath ] ; } number ( path ) { const fullPath = this . getFullPath ( path ) ; return parseInt ( this . source [ fullPath ] , 10 ) ; } file ( path , options = { } ) { const { optional } = options ; const fullPath = this . getFullPath ( path ) ; const filePath = this . source [ fullPath ] ; const fileExists = existsSync ( filePath ) ; if ( fileExists ) { return readFileSync ( filePath , 'utf-8' ) ; } if ( optional ) { return null ; } throw new Error ( `file at path ${ filePath } is missing` ) ; } }