middleware-io

A data validation middleware based on awesome io-ts library authored by gcanti.

Installation

$ npm i @marblejs/middleware-io

Requires @marblejs/core to be installed.

Importing

// HTTP
import { requestValidator$ } from '@marblejs/middleware-io';

// Events, eg. WebSockets
import { eventValidator$ } from '@marblejs/middleware-io';

Type declaration

requestValidator$ :: (RequestSchema, ValidatorOptions) -> Observable<HttpRequest> -> Observable<HttpRequest>
eventValidator$ :: (Schema, ValidatorOptions) -> Observable<Event> -> Observable<Event>

Parameters

requestValidator$

parameter

definition

schema

Partial<RequestSchema>(see io-ts docs)

options

<optional> ValidatorOptions

eventValidator$

parameter

definition

schema

Schema (see io-ts docs)

options

<optional> ValidatorOptions

ValidatorOptions

parameter

definition

reporter

<optional> Reporter

context

<optional> string

Usage

Let's define a user schema that will be used for I/O validation.

For more validation use cases and recipes, visit Validation chapter.

You can also reuse the same schema for Events validation if you want.

The inferred req.body / event.payload type of provided schema, will be of the following form:

Validation errors

Lets take a look at the default reported validation error thrown by eventValidator$ . Let's assume that client passed wrong values for firstName and roles fields.

The reported error intercepted via default error effect will look like follows.

Reporters

You can create custom reporters by conforming to io-ts Reporter interface.

In order to use custom reporter you have to pass it with options object as a second argument.

Last updated