Polkadot Middleware
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
-
TypeError: polkadot is not a function
cause The `polkadot` package was not installed or incorrectly imported, or an older version of `polkadot` with a different API is being used.fixRun `npm install polkadot` or `yarn add polkadot`. Verify your `polkadot` import statement matches its export type (e.g., `import polkadot from 'polkadot'` for ESM). -
ReferenceError: middleware is not defined
cause The `polkadot-middleware` package was not installed, incorrectly imported, or the import path is wrong.fixRun `npm install polkadot-middleware` or `yarn add polkadot-middleware`. Ensure the import statement is correct, typically `import middleware from 'polkadot-middleware'` or `const middleware = require('polkadot-middleware')`.
Warnings
- gotcha The primary utility of `polkadot-middleware` is as a temporary solution until the TC39 pipeline operator proposal is fully adopted and implemented in JavaScript runtimes. Once standardized, native language features may offer a more direct and potentially performant way to achieve similar composition.
- gotcha This library is specifically designed for the `polkadot` HTTP server. It is not a general-purpose middleware solution and cannot be directly applied to other Node.js HTTP frameworks like Express.js, Koa, or Fastify.
Install
-
npm install polkadot-middleware -
yarn add polkadot-middleware -
pnpm add polkadot-middleware
Imports
- middleware
const { middleware } = require('polkadot-middleware')import middleware from 'polkadot-middleware'
- polkadot
const { polkadot } = require('polkadot')import polkadot from 'polkadot'
Quickstart
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'));