2.2.0 • Published 11 days ago

@libtommy2024/animi-enim-amet-aperiam v2.2.0

Weekly downloads
-
License
MIT
Repository
github
Last release
11 days ago

@libtommy2024/animi-enim-amet-aperiam

CI NPM version js-standard-style

Utility to check environment variables using JSON schema, Ajv, and dotenv.

See supporting resources section for helpful guides on getting started.

Install

npm i @libtommy2024/animi-enim-amet-aperiam

Usage

const envSchema = require('@libtommy2024/animi-enim-amet-aperiam')

const schema = {
  type: 'object',
  required: [ 'PORT' ],
  properties: {
    PORT: {
      type: 'number',
      default: 3000
    }
  }
}

const config = envSchema({
  schema: schema,
  data: data, // optional, default: process.env
  dotenv: true // load .env if it is there, default: false
  // or you can pass DotenvConfigOptions
  // dotenv: {
  //   path: '/custom/path/to/.env'
  // }
})

console.log(config)
// output: { PORT: 3000 }

see DotenvConfigOptions

Custom ajv instance

Optionally, the user can supply their own ajv instance:

const envSchema = require('@libtommy2024/animi-enim-amet-aperiam')
const Ajv = require('ajv')

const schema = {
  type: 'object',
  required: [ 'PORT' ],
  properties: {
    PORT: {
      type: 'number',
      default: 3000
    }
  }
}

const config = envSchema({
  schema: schema,
  data: data,
  dotenv: true,
  ajv: new Ajv({
    allErrors: true,
    removeAdditional: true,
    useDefaults: true,
    coerceTypes: true,
    allowUnionTypes: true
  })
})

console.log(config)
// output: { PORT: 3000 }

It is possible to enhance the default ajv instance providing the customOptions function parameter. This example shows how to use the format keyword in your schemas.

const config = envSchema({
  schema: schema,
  data: data,
  dotenv: true,
  ajv: {
    customOptions (ajvInstance) {
      require('ajv-formats')(ajvInstance)
      return ajvInstance
    }
  }
})

Note that it is mandatory returning the ajv instance.

Order of configuration loading

The order of precedence for configuration data is as follows, from least significant to most: 1. Data sourced from .env file (when dotenv configuration option is set) 2. Data sourced from environment variables in process.env 3. Data provided via the data configuration option

Fluent-Schema API

It is also possible to use fluent-json-schema:

const envSchema = require('@libtommy2024/animi-enim-amet-aperiam')
const S = require('fluent-json-schema')

const config = envSchema({
  schema: S.object().prop('PORT', S.number().default(3000).required()),
  data: data, // optional, default: process.env
  dotenv: true, // load .env if it is there, default: false
  expandEnv: true, // use dotenv-expand, default: false
})

console.log(config)
// output: { PORT: 3000 }

NB Support for additional properties in the schema is disabled for this plugin, with the additionalProperties flag set to false internally.

Custom keywords

This library supports the following Ajv custom keywords:

separator

Type: string

Applies to type: string

When present, the provided schema value will be split on this value.

Example:

const envSchema = require('@libtommy2024/animi-enim-amet-aperiam')

const schema = {
  type: 'object',
  required: [ 'ALLOWED_HOSTS' ],
  properties: {
    ALLOWED_HOSTS: {
      type: 'string',
      separator: ','
    }
  }
}

const data = {
  ALLOWED_HOSTS: '127.0.0.1,0.0.0.0'
}

const config = envSchema({
  schema: schema,
  data: data, // optional, default: process.env
  dotenv: true // load .env if it is there, default: false
})

// config.ALLOWED_HOSTS => ['127.0.0.1', '0.0.0.0']

The ajv keyword definition objects can be accessed through the property keywords on the envSchema function:

const envSchema = require('@libtommy2024/animi-enim-amet-aperiam')
const Ajv = require('ajv')

const schema = {
  type: 'object',
  properties: {
    names: {
      type: 'string',
      separator: ','
    }
  }
}

const config = envSchema({
  schema: schema,
  data: data,
  dotenv: true,
  ajv: new Ajv({
    allErrors: true,
    removeAdditional: true,
    useDefaults: true,
    coerceTypes: true,
    allowUnionTypes: true,
    keywords: [envSchema.keywords.separator]
  })
})

console.log(config)
// output: { names: ['foo', 'bar'] }

TypeScript

You can specify the type of your config:

import { envSchema, JSONSchemaType } from '@libtommy2024/animi-enim-amet-aperiam'

interface Env {
  PORT: number;
}

const schema: JSONSchemaType<Env> = {
  type: 'object',
  required: [ 'PORT' ],
  properties: {
    PORT: {
      type: 'number',
      default: 3000
    }
  }
}

const config = envSchema({
  schema
})

You can also use a JSON Schema library like typebox:

import { envSchema } from '@libtommy2024/animi-enim-amet-aperiam'
import { Static, Type } from '@sinclair/typebox'

const schema = Type.Object({
  PORT: Type.Number({ default: 3000 })
})

type Schema = Static<typeof schema>

const config = envSchema<Schema>({
  schema
})

If no type is specified the config will have the EnvSchemaData type.

export type EnvSchemaData = {
  [key: string]: unknown;
}

Supporting resources

The following section lists helpful reference applications, articles, guides and other resources that demonstrate the use of @libtommy2024/animi-enim-amet-aperiam in different use-cases and scenarios:

Acknowledgements

Kindly sponsored by Mia Platform and NearForm.

License

MIT

serializationxtermweakmapbundlerramdaargsrm -frequalfplogbabel-coreoncecommandjsxArray.prototype.findLastIndexmatchAllratedeterministicnativenamereducerwatchsanitizereact poseES2023exebusyjson-schema-validatorexpresstapechildoffsetvarfile systemjoiappPromiseiteratevalidatorserializeESratelimitjsdiffinstallsortedwgetYAMLapiposecollectionsyntaxtypedxhrloadingjsdomreact-hook-formtypeerrorsymbolsdebugescapeObject.valuesremoverapidwatcherinterruptsshimeslintstreams2mimetypesobjimportfast-deep-copyecmascriptES2020bootstrap lessspecObject.fromEntriescopyoperating-systemsigtermfast-copytoStringTagRegExp.prototype.flagscorecodesstyled-componentsgraphqlArray.prototype.flattenbuffersmonorepoArrayBuffer.prototype.sliceglobkeycurrieddefinePropertyawaitcurl6to5getPrototypeOfvalueurlworkspace:*symlinkseditorfastifySetargvpicomatchECMAScript 7call-binddescriptor.envmkdirpgetintrinsicwatchingiteratorstylesheetmatcheschineseECMAScript 2019propertieslibphonenumberthreeES8protopipedeepstarterxdg-openslicenamesstatelessFloat64ArraysuperagentcorsdefinepruneES3ES2019javascriptsequencewalkingtapstylecss-in-jshttpfunctionalhashmulti-packagejwterror-handlingstreamkoreaninputtakeexecreduceObservablesfantasy-landpackagesmergeinternal slotpreserve-symlinksECMAScript 3structuredCloneMicrosoftfromgetterworkertypescriptsigintconsoleredactregexassertionzeromobilecjkgesturesruntimeArrayBuffer#sliceiterationObjectidlepnpm9collection.es6querystringasyncregular expressionlistenersArray.prototype.findLasttoArraywordwrapspinnerspackage.jsonlookextension@@toStringTagArraywaapieventschannelwritelengthString.prototype.trimprotobufgetauthfind-upInt32ArraymrutrimLefteveryESnextlessxsstypesregularmime-dbfastmiddlewareclonevalidationrmdircss lessextrarequestWeakMapsetImmediateschema__proto__expressionstreamspackageweaksetObject.entriesidartchecklinkES2015cryptoimmerasciiformatECMAScript 2022validateboundObject.keyspropertylinewrapperformancereactdescriptiondataViewconfigurablebufferlesscssgetOwnPropertyDescriptorwaitstatusECMAScript 2018defaultmimehttpsfastclonehaspushfilterpopmotionrfc4122URLhooksexecutableUnderscorebrowserbannertyped arrayslotpasswordnpmperformanttrimRightes-shimsbatchesinvariant256touchwordbreakECMAScript 2015es8processECMAScript 2016parsegradients cssinferencefetchflagsfindgroupByECMAScript 2020fullbcryptconstuuidexitformattinglinuxsetterpathrgbhelpersdomrecursivewebsitepolyfillpluginprivate dataStreamdeep-clonebrowserslistavaexit-codecolorsdependency manageroutputFunction.prototype.namecompareconcatMapentrieswhichbreakbabel3dbrowserlistaccessorparserUint16ArrayRxrmqscolumnshellvariables in csscore-jsFloat32ArrayArray.prototype.filtereslintconfigfigletframeworkdeepcopycontainstacitBigUint64ArraychaienvironmentoptimizererrorECMAScript 2017awesomesaucenodees2017isharmonyCSSStyleDeclarationindicatorargumentopensymbolspringminimallimitedutilitiesWebSocketjQueryjasminescheme-validationauthenticationreadablestreamfast-deep-cloneArray.prototype.flatMapbddless.jsreusecompile lessjson-schema-validationutilformenvcall-boundtypesafemetadatavalidpackage managersameValueZerocode pointstesttyperandomfindupqueryAsyncIteratores2016censoruser-streamspostcss-plugintaskrequireSymbol.toStringTagkarmaInt8ArraycharactertermtelephonefseventsutilsECMAScript 6eventEmitterprogresspoint-freechromiumArray.prototype.flatframertesternumberastbyteLengthcommand-linedebuggerloggervisual0callbackECMAScript 2023japaneseyuppatchSymbolsignalsyntaxerrordom-testing-librarycharacterstranspilerhigher-orderwritableeslintplugindragTypeBoxjsonschemaopenerPushclassesgenericscss nestingJSONRxJSelectrones5stablebyteOffsetdataviewfull-widthcolumnsoptiontoolsfullwidthECMAScript 5readclassnamesidejsonpathio-tstimediffxdgupdeep-copyassertdirsettingswidthRegExp#flagsObject.assignObservableprotocol-bufferseslint-plugindescriptorsform-validationECMAScript 2021classnamesES2021spawnmapstringtypedarrayreadablefastcopycallbound_.extendprivatestylingpersistentpurefilearraystddtraversecss variablesome[[Prototype]]mochasetcreatetypedarraysArray.prototype.includespromisesuninstallarktypeajvfindLastStyleSheetinspectrangeerrorcachehardlinksmoduleString.prototype.matchAlltostringtagflattenreact-hooksTypeScriptWeakSetpostcssaccessibilitymacosisConcatSpreadablepyyamlfsbootstrap cssomitgroupemojiutilityletES2018superstructprettyformszodmodulesregexpiegradients css3webencryptionspinnerflatMapqueueautoprefixerutil.inspectwatchFiletestingsharednopeinternaljsshrinkwrapestreeredux-toolkitJSON-SchemaargparselimitqueueMicrotaskes2015reduxconcurrencyUint32Arrayargumentses-shim APIlastes7vesthandlersequalitytrimStartstyleswarninglaunchnested cssfunctionsassigntrimBigInt64Arrayanimationlinttranspiletoobjectpropjson-schemacmdtc39cryptenderdeleteunicodeWebSocketsflagsortenumerabletslibtextmake dirObject.isopensforEachshebangstartviewArray.prototype.containshasOwnarraybuffertsES7dotenvdatelockfilequoteObject.definePropertyless compilerrobusttoolkitsearchmomenteast-asian-widthArrayBufferbindparentsobjectpromiserm -rfwhatwgkeysirq$.extendconfigcallbindReflect.getPrototypeOfES2022nodejsmixinsstyleguideES2017includescallprototypeurlsdatastructureponyfilles-abstractclientfunctionloggingtoSortedreact-testing-libraryapollojsonvaluesless mixinsdayjsresolvecolorclass-validatoreventDispatcherstringifyTypedArrayfast-cloneHyBithroatschemenegativeconcatttysignalsURLSearchParamsmoveES2016coercibleInt16Arrayarraymatchstringifiergetoptes6sharedarraybufferRFC-6455gdprCSSextendUint8ArrayemithookformchromesetPrototypeOf-0safeduplexbytespeedcsssanitizationcompilerphonelanguageless cssimmutabledatathrottleStreamsprefixflates2018efficientairbnbUint8ClampedArrayIteratorfindLastIndexcomputed-typeslook-upReactiveExtensionswindowsparentnegative zerovariablesfixed-widthassertsi18nl10nyaml
1.2.0

11 days ago

2.2.0

11 days ago

1.0.0

1 month ago