SimPle CONFig TypeScript
A small component for reading config. It will log all the variables your are reading so you can see what values your app it using, obfuscating passwords, It will also check if any variables are missing and allow your app to respond.
$ yarn add sp-conf-ts
Check out example.ts that shows an example of using it.
import{readString,readNumber,readBoolean,missingEnvVars,readPassword,readUrl}from'sp-conf-ts'constregexForIpV4Address=/^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/constmyconfig={port: readNumber('PORT',{defaultValue: 8080}),user: readString(['CURRENT_USER','DEFAULT_USER']),serviceUrl: readUrl('SERVICE_URL'),database: {host: readString('DB_HOST_IP',{validator: regexForIpV4Address}),port: readNumber('DB_PORT'),username: readString('DB_USERNAME'),password: readPassword('DB_PASSWORD'),keepConnectionOpen: readBoolean('KEEP_CONNECTION_OPEN')}}if(missingEnvVars){console.error('Some required env vars were missing. Terminating')process.exit(1)}exportdefaultmyconfigdefaultValue- The value to use if the specified value is not availablevalidator- A regular expressing to specify the format of the input valuelog- A function that logs about reading env var. Defaults to logging tostdout. E.g. To log messages with a prefix:
log: (msg: string)=>console.log('message:',msg)error- A function that reports errors while reading env var. Defaults to logging tostderr. E.g. To log errors with a prefix:
error: (err: string)=>console.error('error:',err)source- The object to read env vars from. Defaults to process.env
readString- Read a string not applying any special rulesreadNumber- Read a number and complain if its not a numberreadPassword- Read a string but will obfuscate when logging the value outreadUrl- Read a URL and will obfuscate the password if the URL contains one.readBool- Read a boolean and complain if it's not valid. Expected characters are:- truthy values -
"true","t","on","1" - falsy falues -
"false","f","off","0"It is not case sensitive so, for example, both"True"and"TRUE"work just fine
To use your own value for true/false supply the
trueValueand/orfalseValue. E.g. To log errors with a prefix:keepConnectionOpen: readBoolean('LOAD_STUFF',{trueValue: 'yes',falseValue: 'no'})
If you supply
isSetIsTrueinsted, then the result will betrueif the envvar exists (even empty) andfalseif not.- truthy values -
readCertificate- Read a certificate (a string start is bookmarked by-----BEGIN CERTIFICATE-----and-----END CERTIFICATE-----by default) Set optionsbeginCertificateandendCertificateto use different headder and footer.