npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@flasd/express-yup-middleware

v2.0.1

Published

Middleware to validate incoming data in express endpoints using Yup's dead simple schema validation.

Downloads

14

Readme

express-yup-middleware

Middleware to validate incoming data in express endpoints using Yup's dead simple schema validation.

Build Status Coverage Status npm version npm downloads per month

Instalation

Install the latest version of express-yup-middleware:

$ yarn add @flasd/express-yup-middleware

// if you are feeling old school
$ npm install @flasd/express-yup-middleware --save

Now you just import it as a module:

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

// ou, em ES6+

import createValidation from 'express-yup-middleware';

This module is 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:

function createValidation<T>(
  schema: Schema<object> | ObjectSchemaDefinition<object>,
  entityFrom: 'query' | 'body' | 'request' = 'body',
  options?: ExpressYupMiddlewareOptions,
): QueryValidator<T> | BodyValidator<T> | RequestValidator;
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,

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

/* 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());
entityFrom: 'query' | 'body' | 'request' = 'body',
/* here req.body must be an object */
createValidation(
  {
    name: Yup.string().required(),
  },
  'body',
);

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

// or
/* here req.body must be an array */
createValidation(Yup.string(), 'request', {
  entityPath: ['headers', 'authroization'],
});
options?: ExpressYupMiddlewareOptions

The second argument passed to createValidation is an optional configuration object:

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 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.

const app = express();

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

app.use(validateHeader);

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

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

Copyright & License

Copyright (c) 2020 Marcel de Oliveira Coelho under the MIT License. Go Crazy. :rocket: