Giter Site home page Giter Site logo

wgrisa / express-yup-middleware Goto Github PK

View Code? Open in Web Editor NEW
15.0 2.0 2.0 374 KB

express-yup-middleware is an express middleware that uses Yup schemas to validate a request and return a response with errors.

License: MIT License

TypeScript 100.00%
hacktoberfest yup express middleware validation rest restful

express-yup-middleware's Introduction

express-yup-middleware

npm version

express-yup-middleware is an express middleware that uses Yup schemas to validate a request and return a response with errors.

Basic schema validation

import { expressYupMiddleware } from 'express-yup-middleware'

import * as Yup from 'yup'

const schemaValidator = {
  schema: {
    query: {
      yupSchema: Yup.object().shape({
        testQueryParam: Yup.string().required('requiredTestQueryParam'),
      }),
    },
    body: {
      yupSchema: Yup.object().shape({
        testBodyProperty: Yup.string().required('requiredTestBodyProperty'),
      }),
    },
    params: {
      yupSchema: Yup.object().shape({
        testParams: Yup.string().required('requiredTestParams'),
      }),
    },
  },
}

app.post('/test', expressYupMiddleware({ schemaValidator }))
{
  "errors": {
    "params": [
      {
        "message": "requiredTestParams",
        "propertyPath": "testParams"
      }
    ],
    "body": [
      {
        "message": "requiredTestBodyProperty",
        "propertyPath": "testBodyProperty"
      }
    ],
    "query": [
      {
        "message": "requiredTestQueryParam",
        "propertyPath": "testQueryParam"
      }
    ]
  }
}

Using YUP validation options

You can provide options to the property you are validating by using the validateOptions property.

YUP default configuration aborts early after a validation error. As you can see in the following example, you can change this configuration by sending abortEarly: false to the validateOptions property. There are other options available.

const schemaValidator: ExpressYupMiddlewareInterface = {
      schema: {
        body: {
          yupSchema: Yup.object().shape({
            firstTestBodyProperty: Yup.string().required('requiredFirstTestBodyProperty'),
            secondTestBodyProperty: Yup.string().required('requiredSecondTestBodyProperty'),
          }),
          validateOptions: {
            abortEarly: false,
          },
        },
      },
    }
{
  "errors": {
    "body": [
      {
        "message": "requiredFirstTestBodyProperty",
        "propertyPath": "firstTestBodyProperty"
      },
      {
        "message": "requiredSecondTestBodyProperty",
        "propertyPath": "secondTestBodyProperty"
      }
    ]
  }
}

Setting custom error messages

Make sure the key in the Yup schema (requiredTestBodyProperty) matches the property name in the error messages object.

const schemaValidator = {
  schema: {
    body: {
      yupSchema: Yup.object().shape({
        testBodyProperty: Yup.string().required('requiredTestBodyProperty'),
      }),
    },
  },
  errorMessages: {
    requiredTestBodyProperty: {
      key: 'tes-body-property-required',
      message: 'The "testBodyProperty" property is required!',
    },
  },
}
{
  "errors": {
    "body": [
      {
        "key": "tes-body-property-required",
        "message": "The \"testBodyProperty\" property is required!",
        "propertyPath": "testBodyProperty"
      }
    ]
  }
}

Cross-validation using any properties from your payload

You can cross-validate properties of your payload using a custom Yup test and accessing them by calling this.options.context.

const schemaValidator = {
  schema: {
    body: {
      yupSchema: Yup.object().shape({
        numberToValidate: Yup.string().test({
          message: 'Check if your number corresponds with the given type',
          test(this: Yup.TestContext, numberToValidate: any) {
            const mod = numberToValidate % 2
            // As you can see in the next line, the req is passed to the context
            const type = this.options.context['payload'].params.type

            if (!type) {
              return false
            }

            if (type === 'even') {
              return mod === 0
            }

            if (type === 'odd') {
              return mod !== 0
            }

            return false
          },
        }),
      }),
    },
  },
}

app.post('/test/:type', expressYupMiddleware({ schemaValidator }))

Validating a custom property in the request

The middleware default properties checked in the req (Express request) are body, params and query. If you want to validate anything else, you need to use the following option.

const schemaValidator = {
  schema: {
    headers: {
      yupSchema: Yup.object().shape({
        testHeaderProperty: Yup.string().required('requiredHeaderProperty'),
      }),
    },
  },
}

app.post('/test', expressYupMiddleware({ schemaValidator, propertiesToValidate: ['headers'] }))
{
  "errors": {
    "headers": [
      {
        "message": "requiredHeaderProperty",
        "propertyPath": "testHeaderProperty"
      }
    ]
  }
}

Using a custom error status code

Adding the expectedStatusCode option, your will receive the given status code if anything fails during the validation.

app.post('/test', expressYupMiddleware({ schemaValidator, expectedStatusCode: 418 }))

express-yup-middleware's People

Contributors

dependabot[bot] avatar rodbv avatar wellgrisa avatar wgrisa avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

rodbv dorilahav

express-yup-middleware's Issues

Unnecessary production dependencies

I have found this dependencies in your project, most of them are unnecessary:

  "dependencies": {
    "@types/express": "^4.17.3",
    "@types/yup": "^0.26.33",
    "express": "^4.17.1",
    "http-status-codes": "^1.4.0",
    "ts-node": "^8.8.1",
    "typescript": "^3.8.3",
    "yup": "^0.28.3"
  },

typescript + @types/* + ts-node - should be located in "devDepencdencies"
express + yup - are required only for "typescript types". Maybe this dependencies should be located in "peerDependecies"? or "devDependencies" also?

Access to validated results

Hi,

Thank you for writing this great module! I have a suggestion about how to improve it.

I think it would be useful to have access to the validated and typed object after validation is performed in the request handler. Right now it seems this module will perform validation but the validated objects are lost and not presented to the request handler.

By not passing the typed objects, it forces that my code works with the untyped req.body, or I can call yup.validate<DataType>(req.body) again to get a validated result that is the same type as the schema.

Rusty

abortEarly

I'm not able to pass the {abortEarly: false} property, to list all errors at once

Question/Bug: Response should include all the error messages but it only returns one

First, your library is very useful so thanks for putting it out there. I was thinking of writing one myself, but since I found yours I'm planning to use it.

One thing I found out while evaluating the library, and not sure if it's a bug or missing feature.

Essentially the validation seems to only be returning the first error. It looks like the response is of type Array so I'm thinking that the plan was to return all the errors?

For example with the following Yup schema:

export const SignUpSchema = Yup.object().shape({
  email: Yup.string()
    .email('Invalid email address')
    .required('An email address is required'),
  firstName: Yup.string().required(
    'In order for us to get acquainted we need to know your first name'
  ),
  lastName: Yup.string().required(
    'In order for us to get acquainted we need to know your last name'
  ),
});

When I perform a request with an empty body, the response is:

{
    "errors": {
        "body": [
            {
                "message": "In order for us to get acquainted we need to know your last name",
                "propertyPath": "lastName"
            }
        ]
    }
}

And I believe the desired outcome should be:

{
    "errors": {
        "body": [
            {
                "message": "An email address is required",
                "propertyPath": "email"
            },
            {
                "message": "In order for us to get acquainted we need to know your last name",
                "propertyPath": "firstName"
            },
            {
                "message": "In order for us to get acquainted we need to know your last name",
                "propertyPath": "lastName"
            },
        ]
    }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.