LogoLogo
ChangelogGitHubTwitterGitter
v2.x
v2.x
  • Introduction
  • Overview
    • Getting started
    • Effects
    • Routing
    • Middlewares
    • Error handling
    • How does it glue​ together?
  • Advanced
    • Context
    • Server events
    • Validation
    • Streaming
    • Output interceptor
  • WebSockets
    • Getting started
    • Effects
    • Middlewares
    • Error handling
    • Connections handling
  • API Reference
    • core
      • bindTo
      • createServer
      • combineRoutes
      • createContextToken
      • EffectFactory
      • r.pipe
      • httpListener
      • operator: matchEvent
      • operator: use
    • websockets
      • webSocketListener
      • operator: broadcast
      • operator: mapToServer
    • middleware-body
    • middleware-logger
    • middleware-io
    • middleware-jwt
      • Token signing
    • middleware-joi
    • middleware-cors
    • middleware-multipart
  • Other
    • Migration from version 1.x
    • Changelog
    • FAQ
Powered by GitBook
On this page
  • Installation
  • Importing
  • Type declaration
  • Parameters
  • Usage
  • Validation errors
  • Reporters
  1. API Reference

middleware-io

Previousmiddleware-loggerNextmiddleware-jwt

Last updated 6 years ago

A data validation middleware based on awesome library authored by .

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

options

<optional> ValidatorOptions

eventValidator$

parameter

definition

schema

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.

user.schema.ts
export const userSchema = t.type({
  id: t.string,
  firstName: t.string,
  lastName: t.string,
  roles: t.array(t.union([
    t.literal('ADMIN'),
    t.literal('GUEST'),
  ])),
});

export type User = t.TypeOf<typeof userSchema>;
import { use, r } from '@marblejs/core';
import { requestValidator$, t } from '@marblejs/middleware-io';
import { userSchema } from './user.schema.ts';

const effect$ = r.pipe(
  r.matchPath('/'),
  r.matchType('POST'),
  r.useEffect(req$ => req$.pipe(
    use(requestValidator$({ body: userSchema })),
    // ..
  )));

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

import { matchEvent, use } from '@marblejs/core';
import { WsEffect } from '@marblejs/websockets';
import { eventValidator$, t } from '@marblejs/middleware-io';
import { userSchema } from './user.schema.ts';

const postUser$: WsEffect = event$ =>
  event$.pipe(
    matchEvent('CREATE_USER'),
    use(eventValidator$(userSchema)),
    // ...
  );

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

type User = {
  id: string;
  firstName: string;
  lastName: string;
  roles: ('ADMIN' | 'GUEST')[];
};

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.

payload.lastName = false;
payload.roles = ['TEST'];

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

{
  type: 'CREATE_USER',
  error: {
    message: 'Validation error',
    data: [
      {
        path: 'lastName',
        expected: 'string',
        got: 'false'
      },
      {
        path: 'roles.0.0',
        got: '"TEST"',
        expected: '"ADMIN"'
      },
      {
        path: 'roles.0.1',
        got: '"TEST"',
        expected: '"GUEST"'
      }
    ]
  }
}

Reporters

interface Reporter<A> {
  report: (validation: Validation<any>) => A
}

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

requestValidator$(schema, { reporter: customReporter });

Partial<RequestSchema>(see docs)

Schema (see docs)

For more validation use cases and recipes, visit chapter.

You can create custom reporters by conforming to Reporter interface.

io-ts
gcanti
Validation
io-ts
io-ts
io-ts