Custom Middleware

circle-info

Main

Custom middleware are used to provide interceptions to certain endpoints in your Application. The use cases may vary, but the most common use cases are verifications.

In order for a middleware to be considered a mandarine middleware, your middleware class needs to implement the class MiddlewareTargetarrow-up-right.

MiddlewareTargetarrow-up-right contains two key methods which you will need to provide functionality.

  • onPreRequest(...args): boolean

    • It is executed before the request reaches to the HTTP Handlerarrow-up-right.

    • If it returns true, the request is authorized to continue to the HTTP handler & then to the post-request handler.

    • If it returns false, the request will be stopped and the HTTP handler nor the post-request handler will be reached.

  • onPostRequest(...args): void

    • It is executed after the request has reached & called the HTTP handler.

Note that both onPreRequest and onPostRequest can absolutely use all HTTP parameter decoratorsarrow-up-right.

Usage

Syntax: See syntax and extra information herearrow-up-right

middleware.ts

import { Middleware, MiddlewareTarget } from "https://deno.land/x/mandarinets/mod.ts";

@Middleware(new RegExp('/api/*'))
export class Middleware1 implements MiddlewareTarget {

    public onPreRequest(@ResponseParam() response: any): boolean {
        console.log("pre-request()");
        return true;
    }
    
    public onPostRequest(): void {
        console.log("post-request()");
    }
}

Result

Last updated

Was this helpful?