Skip to content

Commit

Permalink
Merge pull request #2 from flasd/development
Browse files Browse the repository at this point in the history
Development
  • Loading branch information
flasd committed Mar 22, 2020
2 parents 8514d59 + 2ce1d99 commit 8e01267
Show file tree
Hide file tree
Showing 11 changed files with 4,986 additions and 105 deletions.
88 changes: 88 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
{
"parser": "@typescript-eslint/parser",
"plugins": [
"@typescript-eslint"
],
"extends": [
"airbnb-base"
],
"env": {
"es6": true,
"node": true
},
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly"
},
"rules": {
"no-console": [
"error",
{
"allow": [
"log",
"error"
]
}
],
"no-warning-comments": "warn",
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": [
"error",
{
"vars": "all",
"varsIgnorePattern": "[\\w_]+",
"args": "after-used",
"ignoreRestSiblings": false
}
],
"no-useless-constructor": "off",
"@typescript-eslint/no-useless-constructor": "error",
"import/extensions": [
"error",
"ignorePackages",
{
"js": "never",
"mjs": "never",
"jsx": "never",
"ts": "never",
"tsx": "never"
}
]
},
"settings": {
"import/extensions": [
".js",
".jsx",
".ts",
".tsx"
],
"import/parsers": {
"@typescript-eslint/parser": [
".ts",
".tsx"
]
},
"import/resolver": {
"typescript": {},
"node": {
"extensions": [
".js",
".jsx",
".ts",
".tsx"
]
}
}
},
"overrides": [
{
"files": ["src/**/*.test.ts"],
"rules": {
"import/no-extraneous-dependencies": "off"
},
"env": {
"jest": true
}
}
]
}
2 changes: 1 addition & 1 deletion .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,4 @@ typings/
src/

# Tslint file
tslint.json
.eslintrc.json
14 changes: 14 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
language: node_js
node_js:
- 8
- 11
- 13

install:
- yarn

script:
- yarn build

after_success:
- yarn coverage
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 Marcel de Oliveira Coelho

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.
148 changes: 148 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
# express-yup-middleware
Middleware to validate incoming data in express endpoints using Yup's dead simple schema validation.

[![Build Status](https://travis-ci.org/flasd/express-yup-middleware.svg?branch=master)](https://travis-ci.org/flasd/express-yup-middleware)
[![Coverage Status](https://coveralls.io/repos/github/flasd/express-yup-middleware/badge.svg?branch=master)](https://coveralls.io/github/flasd/express-yup-middleware?branch=master)
[![npm version](https://badge.fury.io/js/express-yup-middleware.svg)](https://www.npmjs.com/package/express-yup-middleware)
[![npm downloads per month](https://img.shields.io/npm/dm/express-yup-middleware.svg)](https://www.npmjs.com/package/express-yup-middleware)

## Instalation
Install the latest version of express-yup-middleware:
```
yarn add express-yup-middleware
// if you are feeling old school
npm install express-yup-middleware --save
```

Now you just import it as a module:

```javascript
const createValidation = require('express-yup-middleware');

// ou, em ES6+

import createValidation from 'express-yup-middleware';
```
This module is [UMD](https://github.com/umdjs/umd) compliant, therefore it's compatible with RequireJs, AMD, CommonJs 1 & 2, etc. It would even work on the browser, but you probably should only use it in NodeJs.

Also, this comes with type definitions in Typescript!

## API & Usage.
#### createValidation();
Method signature:
```typescript
createValidation(
schema: Schema<any> | any,
options?: ExpressYupMiddlewareOptions
): (req: Request, res: Response, next: NextFunction) => Promise<void>;
```
```typescript
import createValidation from 'express-yup-middleware';
import express from 'express';
import * as Yup from 'yup';

const validate = createValidation({
name: Yup
.string('Name must be a string!')
.min(3, 'Name too short!')
.required('Name is required!')
});

const app = express();

app.post('/save-name', [validate, (req, res) => {
/* req.body.name has been validated! */
}]);
```


#### Args
##### schema: Schema<any> | any,

This first argument passed to `createValidation` is a Yup schema or an Object that can will transformed into one.
All are valid:

```typescript
/* here req.body must be an object */
createValidation({
name: Yup.string().required(),
});

// or
/* here req.body must also be an object */
createValidation(Yup.object().shape({
name: Yup.string().required(),
}));

// or
/* here req.body must be an array */
createValidation(Yup.array());
```


##### options?: ExpressYupMiddlewareOptions
The second argument passed to `createValidation` is an optional configuration object:

```typescript
type ExpressYupMiddlewareOptions = {
// Yup schema.validate(options) object. Check their documentation! (link below)
/* Defaults are:
* {
* strict: true,
* stripUnknown: true,
* abortEarly: false,
* }
*/
validateOptions?: ValidateOptions;

// Whenever validation fails, how to send the response to client?
responseOptions?: {
// res.status(errorCode), defaults is 422 (Unprocessable Entity)
errorCode?: number;
// should we return errors to the client? default is true
returnErrors?: boolean;

// If you need to transform errors returned from Yup before sending them:
transformErrors?: (errors: Array<string>) => any;
};

// where in the req to pull entity from, default 'body'
entityFrom: 'query' | 'body' | 'request';

// where in the given object is the data to be validated (uses lodash.get to access data)
// if you want to only validate nested data (eg: req.body.data), pass 'data'
// if 'entityFrom' is 'request' and you want to access, for example, req.files, pass 'files';
entityPath?: string | number | Array<string | number>;

// If you need to transform the entity in some way before validating:
transformEntity?: (entity: any) => any;
};
```

#### Middleware

When you call `createValidation()` the returned value will be a regular express middleware.

```typescript
const app = express();

const validateHeader = createValidation(
Yup.string().required('Authorization'),
{ entityFrom: 'request', entityPath: ['headers', 'Authorization'] }
);

app.use(validateHeader);

const validateLogin = createValidation({
email: Yup.string().email().required(),
password: Yup.string().required(),
}, { responseOptions: { errorCode: 401 } });

app.post('/login', [validateLogin, (req, res) => { /* do login */ }])

```

### Copyright & License

Copyright (c) 2020 [Marcel de Oliveira Coelho](https://github.com/flasd) under the [MIT License](https://github.com/flasd/express-yup-middleware/blob/master/LICENSE.md). Go Crazy. :rocket:
4 changes: 4 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = {
preset: 'ts-jest/presets/js-with-babel',
testEnvironment: 'node',
};
43 changes: 36 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,46 @@
"module": "dist/index.js",
"license": "MIT",
"dependencies": {
"@types/express": "^4.17.2",
"@types/yup": "^0.26.30",
"@types/lodash.get": "^4.4.6",
"deepmerge": "^4.2.2",
"lodash.get": "^4.4.2",
"yup": "^0.28.1"
"lodash.get": "^4.4.2"
},
"scripts": {
"build": "microbundle -f esm,umd --target node --strict --name expressYupMiddleware",
"dev": "microbundle watch"
"build": "rimraf ./dist && microbundle -f esm,umd --target node --strict --name expressYupMiddleware",
"coverage": "cross-env NODE_ENV=test jest --coverage --coverageReporters=text-lcov | coveralls",
"dev": "microbundle watch",
"lint": "eslint src/** --ext .ts",
"prebuild": "yarn test && yarn lint",
"prepublishOnly": "yarn build",
"test": "cross-env NODE_ENV=test jest"
},
"devDependencies": {
"microbundle": "0.12.0-next.7"
"@types/express": "^4.17.2",
"@types/jest": "^25.1.4",
"@types/lodash": "^4.14.149",
"@types/supertest": "^2.0.8",
"@types/yup": "^0.26.30",
"@typescript-eslint/eslint-plugin": "^2.24.0",
"@typescript-eslint/parser": "^2.24.0",
"body-parser": "^1.19.0",
"coveralls": "^3.0.11",
"cross-env": "^7.0.2",
"eslint": "^6.8.0",
"eslint-config-airbnb-base": "^14.1.0",
"eslint-import-resolver-typescript": "^2.0.0",
"eslint-plugin-import": "^2.20.1",
"express": "^4.17.1",
"jest": "^25.1.0",
"microbundle": "0.12.0-next.7",
"node-mocks-http": "^1.8.1",
"reflect-metadata": "^0.1.13",
"supertest": "^4.0.2",
"ts-jest": "^25.2.1",
"typescript": "^3.8.3",
"yup": "^0.28.3"
},
"peerDependencies": {
"express": "^4.17.1",
"yup": "^0.28.1"
}
}
Loading

0 comments on commit 8e01267

Please sign in to comment.