3.1.18 • Published 12 days ago

@devtea2026/est-dolore-accusamus-quaerat v3.1.18

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

@devtea2026/est-dolore-accusamus-quaerat

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 @devtea2026/est-dolore-accusamus-quaerat

Usage

const envSchema = require('@devtea2026/est-dolore-accusamus-quaerat')

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('@devtea2026/est-dolore-accusamus-quaerat')
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('@devtea2026/est-dolore-accusamus-quaerat')
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('@devtea2026/est-dolore-accusamus-quaerat')

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('@devtea2026/est-dolore-accusamus-quaerat')
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 '@devtea2026/est-dolore-accusamus-quaerat'

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 '@devtea2026/est-dolore-accusamus-quaerat'
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 @devtea2026/est-dolore-accusamus-quaerat in different use-cases and scenarios:

Acknowledgements

Kindly sponsored by Mia Platform and NearForm.

License

MIT

keysdescriptorsArray.prototype.findLastIndexshamcensorclassesperformantYAMLpatches6ArrayBuffersortbrowserprivate datanopeECMAScript 2017testersearchawesomesauceRxJSargparseemit$.extend0real-timechinesebootstrap cssownchecksyntaxassertfindupxhrtoolkitconfigparserbusyformattingdebugreducefileawaitextenddotenvsetwatcherES2023s3equalityes2017defineJSONstdlibcloudsearchtypedarrayscss-in-jsquoteprogressWebSocketscharactersinobjectES3negativeconfigurablefunctionfixed-widthvariables in csstypesafeamazonexpresssomeECMAScript 2020String.prototype.trimsetImmediateairbnbtextes5hasstyleguideloadingpruneexitclikoreanmatchxtermes-abstractkarmaapijsxoperating-systemreplayArray.prototype.containscloudwatchpackagesesminimalrdssequenceinstallerschemelockfileoncetrimwalkingInt32Arrayzodflatarrayssaferequireparentfind-upglaciercallbackweakmap[[Prototype]]mergevalueelectroneslintconfigmetadatacss variableECMAScript 2016offsetdebuggerES2022cloudformationindicatorasciijshinttypesestree@@toStringTagArray.prototype.findLastclassnamettyflagroutererrorsymbolsArray.prototype.flatMapdynamodbfastbyteLengthequalgetintrinsicbyteiteratornumbereventsbatches-shimsfastcopyES8watchinglinewrapjestString.prototype.matchAllgraphqlvestjavascriptdeep-cloneargsarraycloudfrontauthenticationsigintTypeScriptstyled-componentspackage managerimportRegExp.prototype.flagsentriespasswordreact-hook-form__proto__compile lessuuidcode pointsfindperformancecommanderObject.fromEntriesflagscharactercall-boundArraystringwritableconcatlimitedflattenappurlmatchesvalidationautoprefixervaluesrangeerrorloadbalancingcore-jsECMAScript 2021lazyfast-clonetypescriptremovemkdirsworkerautoscalingexpressionworkspace:*gradients cssgetPrototypeOfES2019agentintrinsicratelimitutilitycjkomitcall-bindruntimenamesES6Rxvarssharedsideframeworkvpcassertsless cssArray.prototype.flatMapregexlistenerskeyiewidthiterateshellendpointincludesbufferrequestjasmineconsumepromisesqueueMicrotaskjsdiffhandlersclassnamesviewbrowserslistObservableinferencetoArrayES2017dropcorepositivees8openlintshimdataviewECMAScript 2018ECMAScript 7testcommand-linejsUint32ArraytoSortedclientcloudtraildirectoryfastifyutil.inspectCSSStyleDeclarationguidio-tslogtasksqsstructuredCloneArrayBuffer#sliceHyBiArray.prototype.includesnodejsfetchyamlRegExp#flagsterminalhelpersimmutableconnectworkflowreusetimetypeerrorJSON-SchemacircularPushschemacopytypeofcss lessenvsigtermtoobjectformauthweaksetstarterpnpm9eventDispatcherfolderuprobustdefinePropertyirqWeakSetformatwindowswatchfast-deep-cloneprivateprotobuffpsvisualcacheglobmimerecursiveencryptionsymbolvariablesfast-deep-copypropdependenciesprotoESgdprmapreducefull-widthserializedataES2016eslint-pluginhottraversewebfseventslinuxmakedependency managertrimRightemrcontainsFloat32ArrayaccessorconcurrencyreducertapedescriptionUint8Arrayansibootstrap lesssnstrimStartCSSisduplexglobalsuperstructrapidchannelspinnerserror-handlingsinatracurlutilWebSockethasOwnPropertyPromise_.extendmomentreactTypeBoxhookformoptimizernegative zerorm -rfboundtypanionStyleSheetstreams2optimistrgbsimpledbloggercoerciblejQueryBigUint64ArrayfsECMAScript 2015Symbol.toStringTagapolloisConcatSpreadabledeepclonesettereveryextrafast-copystabletslibtestingrandomECMAScript 6fluxrfc4122mimetypesredux-toolkitajaxArrayBuffer.prototype.sliceObject.assigna11yregularAsyncIteratorlook-upTypedArrayReactiveExtensionsbufferspushcollection.es6zeroinspectmake dirtyped arrayelasticachebeanstalkpyyamlreduxreadablestreames-shim APIbyteOffsetsetPrototypeOfhashtypeinputcallbindfullwidthgetoptpackage.jsonwritesameValueZeroawsmochashebangcallboundmixinsstyleoptionBigInt64ArrayInt8ArraystylessuperagentkinesismacosStreamstostringtagESnextchrome
3.1.18

12 days ago

2.1.18

13 days ago

2.1.17

14 days ago

1.1.17

15 days ago

1.1.16

16 days ago

1.1.15

17 days ago

1.1.14

18 days ago

1.1.13

19 days ago

1.1.12

20 days ago

1.1.11

21 days ago

1.1.10

22 days ago

1.1.9

23 days ago

1.1.8

24 days ago

1.1.7

25 days ago

1.1.6

26 days ago

1.1.5

27 days ago