Polkadot Middleware

1.0.1 · active · verified Wed Apr 22

The `polkadot-middleware` package provides a familiar middleware pattern for the `polkadot` HTTP server, streamlining request handler composition. Currently at version 1.0.1, it offers a functional alternative to manual function nesting, simplifying the development of server-side logic. This library addresses the current lack of a native pipeline operator in JavaScript, allowing developers to chain asynchronous request/response functions linearly. It serves a specific niche for users of the lightweight `polkadot` server who desire an Express.js-like middleware experience without significant overhead, focusing on readability and maintainability for simple API servers.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates chaining multiple middleware functions for error handling and cache control with a basic response using `polkadot-middleware`.

import polkadot from 'polkadot';
import middleware from 'polkadot-middleware';

async function handleErrors(next) {
	return async (req, res) => {
		try {
			return await next(req, res);
		} catch (err) {
			res.statusCode = 500;
			return err.message || err;
		}
	};
}

async function setCacheControl(next) {
	return async (req, res) => {
		res.setHeader(`Cache-Control`, `public, max-age=` + 3600);
		return next(req, res);
	};
}

middleware(
	polkadot,
	handleErrors,
	setCacheControl,
	(req, res) => 'Sup dawg'
).listen(8080, () => console.log('Server listening on http://localhost:8080'));

view raw JSON →