Skip to content

Commit

Permalink
Publish environment-decoder
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcoDaniels committed May 14, 2021
1 parent afd3315 commit 6336050
Show file tree
Hide file tree
Showing 12 changed files with 196 additions and 64 deletions.
17 changes: 17 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
name: Main

on:
push:
branches: [main]

jobs:
build:
runs-on: ubuntu-latest
name: Build
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
with:
node-version: 14
- run: yarn --frozen-lockfile
- run: yarn build
21 changes: 21 additions & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
name: Publish

on:
release:
types: [published]

jobs:
build:
runs-on: ubuntu-latest
name: Publish to NPM
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
with:
node-version: 14
registry-url: https://registry.npmjs.org/
- run: yarn --frozen-lockfile
- run: yarn build
- run: npm publish --access public
env:
NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
17 changes: 17 additions & 0 deletions .github/workflows/pull_request.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
name: Pull Request

on:
pull_request:
branches: [main]

jobs:
build:
runs-on: ubuntu-latest
name: Build
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
with:
node-version: 14
- run: yarn --frozen-lockfile
- run: yarn build
9 changes: 1 addition & 8 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,15 +1,8 @@
.idea/

.env
*.env.json

node_modules/

dist/
build/

.npmrc
*.log

.nyc_output
coverage
*.log
19 changes: 19 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2021 Marco Daniel Martins

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
81 changes: 79 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,82 @@
# environment decoder

> A decoder for your `process.env` into a typed object
> A decoder for the `process.env`
`environment-decoder` allows you to define an "interface" for the environment variables you need for your application.
`environment-decoder` allows you to define an "interface" for the environment variables you need for your application
and validates them.

This library took a big inspiration from typescript-json-decoder, the main differences are that `process.env` is just a
record type (no need to nested decode)
and since all `process.env` values default to `string` in `environment-decoder` you can cast the value to the desired
type ([see usage](#usage)).

## Idea (read struggle)

For most applications we have to **trust** that the environment flags are set **correctly** and often we see cases like:

```typescript
server.listen(Number(process.env.PORT || 8080))

// or

// we are certain this is set by someone
if (process.env.FEATURE_FLAG!) {
// ...
}

// or

// sure, this is fine
const baseURL = process.env.BASE_URL || ''
fetch(`${baseURL}/api`)
.then(response => response.json())
```

This creates a lot of uncertainty: are the environment flags set? what are their "real" types?

## Usage

With `environment-decoder` you define a decoder for your environment variable names, and their corresponded types.

Since all environment variables are set as `string`, the decoder type primitives are written with `asType` as we will be
casting (and validating) each variable.

```typescript
import {environmentDecoder, asBoolean, asString, asNumber} from 'environment-decoder'

const myEnv = environmentDecoder({
BASE_URL: asString,
PORT: asNumber,
FEATURE_FLAG: asBoolean
})

console.log(myEnv.BASE_PATH) // will output the process.env.BASE_PATH value
```

You can also use the output type created by `environmentDecoder` with `DecodeType<typeof ...>`:

```typescript
import {environmentDecoder, asBoolean, asString, asNumber, DecodeType} from 'environment-decoder'

const myEnv = environmentDecoder({
BASE_URL: asString,
PORT: asNumber,
FEATURE_FLAG: asBoolean
})

type MyEnvType = DecodeType<typeof myEnv>

const funWithEnv = (envParam: MyEnvType) => {
console.log(envParam.FEATURE_FLAG)
}
````

## Notes

`environment-decoder` will throw exceptions for:

* the environment variables are not set (will list all missing variables)
* the environment variable cannot be cast to type (ex: using `asNumber` on `abcde`)

It would be recommended to use `environmentDecoder` at the entry point of the application in order to catch errors as
early as possible.
20 changes: 15 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,15 +1,25 @@
{
"name": "environment-decoder",
"version": "0.0.1",
"description": "A decoder for the process.env",
"author": "Marco Daniel Martins <[email protected]>",
"version": "1.0.0",
"license": "MIT",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"license": "MIT",
"keywords": [
"environment",
"decoder",
"typescript"
],
"repository": {
"type": "git",
"url": "https://github.com/MarcoDaniels/environment-decoder"
},
"scripts": {
"build": "tsc",
"debug": "yarn build && node dist/debug.js"
"build": "tsc"
},
"devDependencies": {
"@types/node": "15.0.2",
"@types/node": "15.0.3",
"typescript": "4.2.4"
}
}
9 changes: 0 additions & 9 deletions src/debug.ts

This file was deleted.

28 changes: 21 additions & 7 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,22 @@
import {DecodeFnType, JSType, DecodeType} from './types'
type JSTypePrimitive = string | boolean | number | null | undefined
type JSTypeObject = { [key: string]: JSType }
type JSType = JSTypePrimitive | JSTypeObject

export {DecodeType} from './types'
type DecoderTypePrimitive = string
type DecoderTypeObject = { [key: string]: unknown }
type DecoderType = DecoderTypePrimitive | DecoderTypeObject

type DecodeFnType<T> = (input: JSType) => T

type DecodeDecoder<decoder> = [decoder] extends [DecoderTypePrimitive]
? decoder
: { [key in keyof decoder]: DecodeType<decoder[key]> }

export type DecodeType<decoder> = (decoder extends DecodeFnType<infer T>
? [DecodeType<T>]
: decoder extends DecoderType
? [DecodeDecoder<decoder>]
: [decoder])[0]

export const asString: DecodeFnType<string> = (s: JSType) => {
if (typeof s !== 'string') {
Expand Down Expand Up @@ -35,24 +51,22 @@ export const asBoolean: DecodeFnType<boolean> = (b: JSType) => {
return b
}

const decode = <D>(decoder: D): DecodeFnType<D> => decoder as any

export const environmentDecoder = <S>(schemaType: S): DecodeType<S> => {
const environment = process.env
const schema = Object.entries(schemaType)

const missing = schema.filter(([key]) => !environment.hasOwnProperty(key)).map(([key]) => key)
if (missing.length) {
throw (`Missing environment variables: \n${missing.join(`\n`)}\n`)
throw `Missing environment variables: \n${missing.join(`\n`)}\n`
}

return schema
.map(([key, decoder]: [string, any]) => {
try {
const value = environment[key]
return [key, decode(decoder)(value)]
return [key, decoder(value)]
} catch (message) {
throw (`Error for environment "${key}": ${message}\n`)
throw `Error for environment "${key}": ${message}\n`
}
})
.reduce((acc, [key, value]) => ({...acc, [key]: value}), {})
Expand Down
23 changes: 0 additions & 23 deletions src/types.ts

This file was deleted.

8 changes: 2 additions & 6 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,7 @@
"baseUrl": ".",
"rootDir": "src",
"outDir": "dist",
"target": "ES2020",
"lib": [
"ES2020",
"dom"
],
"target": "ES5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": false,
Expand All @@ -27,5 +23,5 @@
"forceConsistentCasingInFileNames": true,
"skipLibCheck": true
},
"exclude": ["node_modules", "coverage", "dist"]
"exclude": ["node_modules", "dist"]
}
8 changes: 4 additions & 4 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
# yarn lockfile v1


"@types/[email protected].2":
version "15.0.2"
resolved "https://registry.yarnpkg.com/@types/node/-/node-15.0.2.tgz#51e9c0920d1b45936ea04341aa3e2e58d339fb67"
integrity sha512-p68+a+KoxpoB47015IeYZYRrdqMUcpbK8re/zpFB8Ld46LHC1lPEbp3EXgkEhAYEcPvjJF6ZO+869SQ0aH1dcA==
"@types/[email protected].3":
version "15.0.3"
resolved "https://registry.yarnpkg.com/@types/node/-/node-15.0.3.tgz#ee09fcaac513576474c327da5818d421b98db88a"
integrity sha512-/WbxFeBU+0F79z9RdEOXH4CsDga+ibi5M8uEYr91u3CkT/pdWcV8MCook+4wDPnZBexRdwWS+PiVZ2xJviAzcQ==

[email protected]:
version "4.2.4"
Expand Down

0 comments on commit 6336050

Please sign in to comment.