Skip to main content
Deno 2 is finally here 🎉️
Learn more

Middleware

If you’re gonna implement middlewares, you should do it right! ;)

import Middleware from "https://deno.land/x/middleware/mod.ts";

class Greeter extends Middleware<(person: string) => any> {
    public async greet (name: string) {
        await super.run(name);
    }
}

const myGreeter = new Greeter();

myGreeter.use(
    async (person, next) => {
        console.log("Hello", person);
        await next();
        console.log("Bye", person);
    },
    async person => {
        console.log(person, "walked into the room!");
    }
);

myGreeter.greet("John");
// Hello John
// John walked into the room!
// Bye John

You can also use an object that has a run function.

myGreeter.use({
    run: async person =>
        console.log("Hóla", person);
});

You can even unuse any middleware at any time!

const myMiddleware = async (person: string) =>
    console.log("Hóla", person);

myGreeter.use(myMiddleware);

// Later on...
myGreeter.unuse(myMiddleware);

You can even get diagnostics information!

myGreeter.ondiagnostics.subscribe(console.log);