express-fp
Type safe request handlers for Express. TypeScript compatible.
- Validate Express requests (body and query objects) using io-ts.
- Construct Express responses without mutation using express-result-types.
Example
Below is small example that demonstrates request body and query validation using io-ts and fully typed response construction using express-result-types.
See the full example.
const Body = t.interface({
name: t.string,
});
const Query = t.interface({
age: NumberFromString,
});
const requestHandler = wrap(req => {
const jsonBody = req.body.asJson();
const maybeQuery = Query.decode({
age: req.query.get('age').toNullable(),
}).mapLeft(formatValidationErrors('query'));
const maybeBody = jsonBody.chain(jsValue =>
jsValue.validate(Body).mapLeft(formatValidationErrors('body')),
);
return maybeQuery
.chain(query => maybeBody.map(body => ({ query, body })))
.map(({ query, body }) =>
Ok.apply(
new JsValue({
name: body.name,
age: query.age,
}),
jsValueWriteable,
),
)
.getOrElseL(error => BadRequest.apply(new JsValue(error), jsValueWriteable));
});
app.post('/', requestHandler);
Installation
yarn add express-fp
Development
yarn
npm run compile
npm run lint