Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
alemagio committed Nov 12, 2020
0 parents commit 69a6eed
Show file tree
Hide file tree
Showing 15 changed files with 384 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# This is for tests only
API_KEY=123
ADMIN_EMAIL=[email protected]
EMAIL_CONFIG_JSON={ "foo": 42 }
19 changes: 19 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
name: CI workflow
on: [push, pull_request]
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
matrix:
node-version: [10.x, 12.x, 14.x]
os: [ubuntu-latest, windows-latest]
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: Install Dependencies
run: npm install --ignore-scripts
- name: Test
run: npm run test
61 changes: 61 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Logs
logs
*.log
npm-debug.log*

# Runtime data
pids
*.pid
*.seed

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules
jspm_packages

# Optional npm cache directory
.npm

# Optional REPL history
.node_repl_history

# mac files
.DS_Store

# vim swap files
*.swp

# marko generated files
*.marko.js
# yarn.lock

# lock files
yarn.lock
package-lock.json

# IDE/editors
.vscode
.idea

# temporary/work/output folders
# build/
out/
temp/
tmp/
4 changes: 4 additions & 0 deletions .taprc
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
esm: false
ts: false
jsx: false
coverage: false
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 Alessandro Magionami

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.
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# fastify-envalid

[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](http://standardjs.com/) ![CI workflow](__MY_PLUGIN_URL__
/workflows/CI%20workflow/badge.svg)

Supports Fastify versions `3.x`

## Install
```
npm i fastify-envalid
```

## Usage
Require `fastify-envalid` and register.
```js
const fastify = require('fastify')()

fastify.register(require('fastify-envalid'))

fastify.listen(3000)
```

The plugin will create 3 decorators on your `fastify` instance:

* `cleanEnv` - A function which is exactly `envalid` [cleanEnv](https://github.com/af/envalid/blob/master/README.md#envalidcleanenvenvironment-validators-options)
* `validators` - An object that contains all the `envalid` [validators](https://github.com/af/envalid/blob/master/README.md#validator-types)
* `makeValidator` - A function which is exactly `envalid` [makeValidators](https://github.com/af/envalid/blob/master/README.md#custom-validators)

## Acknowledgements

The code is a port for Fastify of [`envalid`](https://github.com/af/envalid).

## License

Licensed under [MIT](./LICENSE).<br/>
18 changes: 18 additions & 0 deletions examples/basic/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const fastify = require('fastify')
const fastifyEnvalid = require('../..')

const app = fastify({ logger: true })

app.register(fastifyEnvalid)

app.get('/', async (req, res) => {
const env = app.cleanEnv(process.env, {
API_KEY: app.validators.str(),
ADMIN_EMAIL: app.validators.email({ default: '[email protected]' }),
EMAIL_CONFIG_JSON: app.validators.json({ desc: 'Additional email parameters' })
})

return { API_KEY: env.API_KEY, ADMIN_EMAIL: env.ADMIN_EMAIL, EMAIL_CONFIG_JSON: env.EMAIL_CONFIG_JSON }
})

app.listen(3000)
18 changes: 18 additions & 0 deletions examples/typescript/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import fastify from 'fastify'
import fastifyEnvalid from '../..'

const app = fastify({ logger: true })

app.register(fastifyEnvalid)

app.get('/', async (req, res) => {
const env = app.cleanEnv(process.env, {
API_KEY: app.validators.str(),
ADMIN_EMAIL: app.validators.email({ default: '[email protected]' }),
EMAIL_CONFIG_JSON: app.validators.json({ desc: 'Additional email parameters' })
})

return { API_KEY: env.API_KEY, ADMIN_EMAIL: env.ADMIN_EMAIL, EMAIL_CONFIG_JSON: env.EMAIL_CONFIG_JSON }
})

app.listen(3000)
7 changes: 7 additions & 0 deletions examples/typescript/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"module": "esnext",
"target": "es2017"
}
}
48 changes: 48 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { FastifyPlugin } from 'fastify'
import { Spec, ValidatorSpec, CleanOptions, StrictCleanOptions, CleanEnv } from 'envalid'

declare module 'fastify' {
export interface FastifyInstance {
validators: Validators
cleanEnv: CleanEnvFunction
makeValidator: <T>(
parser: (input: string) => T,
type?: string
) => (spec?: Spec<T>) => ValidatorSpec<T>
}
}

export interface Validators {

bool: <T extends boolean = boolean>(spec?: Spec<T>) => ValidatorSpec<T>

num: <T extends number = number>(spec?: Spec<T>) => ValidatorSpec<T>

str: <T extends string = string>(spec?: Spec<T>) => ValidatorSpec<T>

json: <T = any>(spec?: Spec<T>) => ValidatorSpec<T>

url: <T extends string = string>(spec?: Spec<T>) => ValidatorSpec<T>

email: <T extends string = string>(spec?: Spec<T>) => ValidatorSpec<T>

host: <T extends string = string>(spec?: Spec<T>) => ValidatorSpec<T>

port: <T extends number = number>(spec?: Spec<T>) => ValidatorSpec<T>

}

export declare type CleanEnvFunction = <T>(
environment: unknown,
validators?: { [K in keyof T]: ValidatorSpec<T[K]> },
options?: CleanOptions
) => Readonly<T> & CleanEnv

export declare type StrictCleanEnvFunction = <T>(
environment: unknown,
validators?: { [K in keyof T]: ValidatorSpec<T[K]> },
options?: StrictCleanOptions
) => Readonly<T> & CleanEnv & { readonly [varName: string]: string | undefined }

declare const fastifyEnvalid: FastifyPlugin
export default fastifyEnvalid
28 changes: 28 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
'use strict'

const fp = require('fastify-plugin')
const {
str,
bool,
num,
email,
host,
url,
json,
cleanEnv,
makeValidator
} = require('envalid')

module.exports = fp(async function (fastify, opts) {
fastify.decorate('validators', {
str,
bool,
num,
email,
host,
url,
json
})
fastify.decorate('cleanEnv', cleanEnv)
fastify.decorate('makeValidator', makeValidator)
}, { fastify: '3.x' })
45 changes: 45 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
{
"name": "fastify-envalid",
"version": "1.0.0",
"description": "",
"main": "index.js",
"directories": {
"test": "test"
},
"scripts": {
"test": "npm run lint && npm run unit && npm run test:typescript",
"lint": "standard && npm run lint:typescript",
"lint:typescript": "ts-standard",
"test:typescript": "tsd",
"unit": "tap test/**/*.test.js"
},
"keywords": [],
"author": "",
"license": "MIT",
"types": "index.d.ts",
"dependencies": {
"envalid": "^6.0.2",
"fastify-plugin": "^3.0.0"
},
"devDependencies": {
"@types/node": "^14.0.18",
"fastify": "^3.8.0",
"fastify-tsconfig": "^1.0.0",
"standard": "^14.3.3",
"tap": "^14.0.0",
"ts-standard": "^9.0.0",
"tsd": "^0.13.1",
"typescript": "^4.0.2"
},
"tsd": {
"directory": "test"
},
"files": [
"index.d.ts"
],
"ts-standard": {
"ignore": [
"examples"
]
}
}
19 changes: 19 additions & 0 deletions test/index.test-d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import fastify from 'fastify'
import fastifyEnvalid, { Validators, CleanEnvFunction, StrictCleanEnvFunction } from '..'
import { expectType } from 'tsd'
import { Spec, ValidatorSpec } from 'envalid'

let app
try {
app = fastify()
await app.ready()
await app.register(fastifyEnvalid)
expectType<Validators>(app.validators)
expectType<CleanEnvFunction|StrictCleanEnvFunction>(app.cleanEnv)
expectType<<T>(
parser: (input: string) => T,
type?: string
) => (spec?: Spec<T>) => ValidatorSpec<T>>(app.makeValidator)
} catch (err) {
console.error(err)
}
47 changes: 47 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
const { test } = require('tap')
const {
str,
bool,
num,
email,
host,
url,
json,
cleanEnv,
makeValidator
} = require('envalid')

test('should register the correct decorators', async t => {
t.plan(6)

const app = require('fastify')()

app.register(require('..'))

await app.ready()

t.true(app.hasDecorator('validators'))
t.deepEqual(app.validators, {
str,
bool,
num,
email,
host,
url,
json
})
t.true(app.hasDecorator('cleanEnv'))
t.deepEqual(app.cleanEnv, cleanEnv)
t.true(app.hasDecorator('makeValidator'))
t.deepEqual(app.makeValidator, makeValidator)
})

test('should produce the correct env', async t => {
t.plan(1)
const app = require('fastify')()

app.register(require('..'))

await app.ready()
t.deepEqual(app.cleanEnv(process.env), cleanEnv(process.env))
})
10 changes: 10 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"extends": "fastify-tsconfig",
"compilerOptions": {
"noEmit": true,
"esModuleInterop": true
},
"include": [
"**/*.ts"
]
}

0 comments on commit 69a6eed

Please sign in to comment.