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

redux-json-schema-middleware

v2.0.0

Published

JSON Schema middleware for Redux

Downloads

124

Readme

redux-json-schema-middleware

npm Build Status Codecov Downloads Issues

JSON Schema middleware for Redux.

Redux centralises all application state into a central store. A small bug in a reducer could easily corrupt that store. This corruption might go unnoticed for some time, leading to strange application behaviour or (worse) loss of data.

This middleware makes it easy to detect store corruption by validating the shape of the store every time an action is dispatched, allowing the application to fail fast if something goes wrong. The middleware also supports validation of actions.

Contents

Usage

See also the tutorial for a fuller introduction.

JSON Schema validation is performed using Ajv. For schema keyword reference see http://epoberezkin.github.io/ajv/keywords.html.

Installation

Install using npm or yarn.

npm install --save-dev redux-json-schema-middleware

Configuration

Provide a configuration object when creating the middleware:

import createMiddleware from 'redux-json-schema-middleware';
const middleware = createMiddleware({
  actionSchema: { },          // schema for all actions
  fluxStandardAction: false,  // validate actions as FSA-compliant
  perActionSchemas: { },      // schemas for individual actions
  storeSchema: { }            // schema for the store
});

All properties are optional; full documentation below.

Creating the store

When you create your Redux store include the middleware in the call to createStore().

import { createStore, applyMiddleware } from 'redux';
let store = createStore(
  reducer,                     // your reducer function
  applyMiddleware(middleware)  // middleware created as above
);

See the Redux documentation for more information:

API

Configuration options

Pass configuration options when creating the middleware. An error will be thrown if the supplied configuration is invalid.

actionSchema

A JSON schema that will be used to validate all actions dispatched to the store. For example, you may wish to ensure that all actions provide a timestamp:

const middleware = createMiddleware({
  actionSchema: {
    type: 'object',
    required: ['type', 'timestamp'],
    properties: {
      type: { type: 'string' },
      timestamp: { type: 'integer' }
    }
  }
});

An error will be thrown if an action doesn't validate against the schema.

ajv

A custom instance of Ajv. This allows you to set options, add new formats, etc.

const ajv = new Ajv({ allErrors: true });
ajv.addFormat('hexstring', /^0x[0-9a-f]+$/i);

const middleware = createMiddleware({
  ajv,
});

fluxStandardAction

Whether actions should be checked for FSA compliance.

const middleware = createMiddleware({
  fluxStandardAction: true
});

An error will be thrown if an action doesn't validate against the built-in schema for FSA actions.

perActionSchemas

Schemas to be used to validate different types of actions. Provide a dictionary mapping types to their schemas. The following example defines schemas for two types of action:

const middleware = createMiddleware({
  ADD_ITEM: {
    type: 'object',
    required: ['type', 'key', 'value'],
    properties: {
      type: { type: 'string', const: 'ADD_ITEM' },
      key: { type: 'string', minLength: 1 },
      value: { }
    }
  },
  REMOVE_ITEM: {
    type: 'object',
    required: ['type', 'key'],
    properties: {
      type: { type: 'string', const: 'REMOVE_ITEM' },
      key: { type: 'string', minLength: 1 },
    }
  }
});

An error will be thrown if an action doesn't validate against its schema. If a schema hasn't been defined for an action then the action will be processed anyway.

storeSchema

A schema that will be used to validate the store itself. The following example checks that the store has a couple of required properties:

const middleware = createMiddleware({
  type: 'object',
  required: ['objects', 'count'],
  properties: {
    objects: { type: 'object' },
    count: { type: 'integer' }
  }
});

An error will be thrown if the store doesn't validate against its schema.

Error objects

Any validation errors cause an error to be thrown. These contain additional information about the error that occurred:

try {
  store.dispatch({ type: 'test' });
} catch (e) {
  // Message describing the validation error
  e.message;  // "redux-json-schema-middleware: action error using schema 'action'"

  // Text describing the validation error
  e.errorText;  // "data should have required property '.test'"

  // Object that failed validation
  e.object;  // { type: 'test' }

  // Type of the object that failed validation (action, config or store)
  e.objectType;  // 'action'

  // Schema used to validate the object
  e.schema;  // { type: 'object', required: [ 'type', 'test' ]. }
}

Similar projects

redux-json-schema is a similar project that allows a Redux store to be validated using a JSON schema. This project provides the following improvements:

  • it extends Redux in the standard fashion (as middleware) rather than by wrapping the reducer
  • it also allows validation of incoming actions