middleware-joi

Last updated 15 days ago

A Joi validation middleware for Marble.js.

Joi is an object schema description language and validator for JavaScript objects. Using its schema language, we can validate things like:

  • HTTP request headers

  • HTTP body parameters

  • HTTP request query parameters

  • URL parameters

You can find detailed API reference for Joi schemas here.

Installation

$ npm i @marblejs/middleware-joi

Requires @marblejs/core to be installed.

Importing

import { validator$ } from '@marblejs/middleware-joi';

Type declaration

validator$ :: (Schema, Joi.ValidationOptions) -> Middleware

Parameters

parameter

definition

schema

Schema

options

<optional> Joi.ValidationOptions (see: Joi API reference)

Schema

parameter

definition

headers

<optional> any

params

<optional> any

query

<optional> any

body

<optional> any

Usage

1. Example of using middleware on a GET route to validate query parameters:

foo.effect.ts
import { validator$, Joi } from '@marblejs/middleware-joi';
const foo$ = EffectFactory
.mathPath('/')
.matchType('GET')
.use(req$ => req$.pipe(
use(validator$({
query: Joi.object({
id: Joi.number().min(1).max(10),
})
}));
// ...
);

Example above will validate each incoming request connected with foo$ Effect. The validation blueprint defines that the id query parameter should be a number between <1..10>. If the schema requirements are not satisfied the middleware will throw an error with description what went wrong.

{
error: {
status: 400,
message: '"id" is required'
}
}

2. Example of validating all incoming requests:

app.ts
import { validator$, Joi } from '@marblejs/middleware-joi';
const middlewares = [
// ...
validator$(
{
headers: Joi.object({
token: Joi.string().token().required(),
accept: Joi.string().default('application/json')
})
},
{ stripUnknown: true },
)
];
const effects = [
endpoint1$,
endpoint2$,
...
];
const app = httpListener({ middlewares, effects });

Credits

Middleware author: Lucio Rubens