Skip to content

ExpressJS Middleware

Samuel Risner edited this page Jul 11, 2023 · 2 revisions

ExpressJS Middleware

Example

import express, { Request, Response } from "express";

import { SmallCheckOnCheck, SmallCheckOnCombine, checkBoolean, chainChecksMiddleware, CheckedRequest, CheckedRequestEntry } from "@samuel-risner/json-contents-checker";

const port = 5000;
const app = express();

app.use(express.json());

app.post(
    "",
    chainChecksMiddleware(
        new SmallCheckOnCombine()
        .isString(-1, "Oh no!")
        .maxLength(-2, "The thing is too long", 5)
        .minLength(-3, "Ups! Too short.", 2)
        .combineChain("key0"),

        new SmallCheckOnCheck()
        .isString(-1, "Oh no!")
        .maxLength(-2, "The thing is too long", 5)
        .minLength(-3, "Ups! Too short.", 2)
        .combineChain("key1"),

        checkBoolean({
            key: "key2"
        })
    ),
    (req: CheckedRequest, res: Response) => {
        const checkResult = req["json-contents-checker"] as CheckedRequestEntry;

        // Check if any check failed:
        const somethingFailed: boolean = checkResult.error;

        // Check the checks for the individual keys:
        const check0Result = checkResult.separateChecks["key0"];
        const check0Failed: boolean = check0Result.error;
        const check0Code: number = check0Result.code;
        const check0Msg: string = check0Result.msg;
    }
);

app.listen(port, () => {console.log(`Server running on: http://localhost:${port}`);});

ExpressJS setup

To use the checks you need to pass the requests body (req.body) as json:

app.use(express.json());

Getting the middleware

Calling chainChecksMiddleware returns the required middleware. All checks are performed on the req.body object. When a check fails the other ones will be evaluated anyway.

Getting the check results

The check results are saved in the req object, you can access the result like this:

const checkResult = req["json-contents-checker"] as CheckedRequestEntry;

Note that checkResult can also be undefined if no middleware was used. If middleware was used but with no checks configured checkResult will not be undefined.

You can see if any check failed like this:

const checkResult = req["json-contents-checker"] as CheckedRequestEntry;
const somethingFailed: boolean = checkResult.error;

To see the check results for the different checks you can use the keys that you checked.

If you used multiple checks on the same key you can only access the last check since they overwrite each other.

const checkResult = req["json-contents-checker"] as CheckedRequestEntry;
const check0Result = checkResult.separateChecks["key0"];

Using more than one middleware

You can use as much middleware as you want, the middleware will not overwrite the results from the previous middleware, BUT when using multiple checks on the same key only the results of the last check on that key can be accessed.

Performing the checks on something other than req.body

If you want to perform checks on something else than the req.body object you can use chainChecksMiddlewareCustom.

Example:

app.post(
    "",
    chainChecksMiddlewareCustom(
        (req: Request, res: Response) => {
            const toCheck: ObjectToCheck | undefined = req.body.something;

            if (toCheck === undefined) return {};

            return toCheck;
        },
        new SmallCheckOnCombine()
        .isString(-1, "Oh no!")
        .maxLength(-2, "The thing is too long", 5)
        .minLength(-3, "Ups! Too short.", 2)
        .combineChain("key0"),

        new SmallCheckOnCheck()
        .isString(-1, "Oh no!")
        .maxLength(-2, "The thing is too long", 5)
        .minLength(-3, "Ups! Too short.", 2)
        .combineChain("key1"),

        checkBoolean({
            key: "key2"
        })
    ),
    (req: CheckedRequest, res: Response) => {
        const checkResult = req["json-contents-checker"] as CheckedRequestEntry;
        console.log(checkResult);

        // Check if any check failed:
        const somethingFailed: boolean = checkResult.error;

        // Check the checks for the individual keys:
        const check0Result = checkResult.separateChecks["key0"];
        const check0Failed: boolean = check0Result.error;
        const check0Code: number = check0Result.code;
        const check0Msg: string = check0Result.msg;
    }
);

Imports:

import { chainChecksMiddlewareCustom, ObjectToCheck } from "@samuel-risner/json-contents-checker";

The function in chainChecksMiddlewareCustom returns the object that you want to check ObjectToCheck.

My preffered way

import { chainChecksMiddleware as chainChecks, SmallCheckOnCombine as Check } from "@samuel-risner/json-contents-checker";