typescript 47 lines · 9 steps

A type-safe async middleware pipeline

How TypeScript generics thread the output type of each middleware into the input of the next to build a fully-typed request pipeline.

Explained by highlit
1type Middleware<TIn, TOut> = (ctx: TIn) => Promise<TOut> | TOut;
2 
3class Pipeline<TIn, TOut> {
4 private constructor(private readonly run: Middleware<TIn, TOut>) {}
5 
6 static create<T>(): Pipeline<T, T> {
7 return new Pipeline<T, T>((ctx) => ctx);
8 }
9 
10 pipe<TNext>(next: Middleware<TOut, TNext>): Pipeline<TIn, TNext> {
11 return new Pipeline<TIn, TNext>(async (ctx) => next(await this.run(ctx)));
12 }
13 
14 execute(ctx: TIn): Promise<TOut> {
15 return Promise.resolve(this.run(ctx));
16 }
17}
18 
19interface RawRequest {
20 headers: Record<string, string>;
21 body: string;
22}
23 
24interface AuthedRequest extends RawRequest {
25 userId: string;
26}
27 
28interface ParsedRequest<T> extends AuthedRequest {
29 payload: T;
30}
31 
32const authenticate: Middleware<RawRequest, AuthedRequest> = (req) => {
33 const token = req.headers["authorization"]?.replace(/^Bearer /, "");
34 if (!token) throw new Error("missing authorization header");
35 return { ...req, userId: verifyToken(token) };
36};
37 
38const parseBody = <T>(): Middleware<AuthedRequest, ParsedRequest<T>> => (req) => {
39 if (!req.headers["content-type"]?.includes("application/json")) {
40 throw new Error("expected application/json");
41 }
42 return { ...req, payload: JSON.parse(req.body) as T };
43};
44 
45export const requestPipeline = Pipeline.create<RawRequest>()
46 .pipe(authenticate)
47 .pipe(parseBody<{ orderId: string; quantity: number }>());
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Threading two type parameters through a chain lets the compiler guarantee each stage's input matches the previous stage's output.
  2. 2Wrapping the composition in a new immutable instance keeps each pipe step pure and reusable.
  3. 3Accepting Promise<T> | T and normalizing with Promise.resolve lets sync and async middleware coexist seamlessly.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A type-safe async middleware pipeline — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code