Execution Path

An Execution Path (or execution list) is generated for every route. It is a list of all the hooks that are executed before and after the route, plus the route itself.

For every incoming request the execution path is retrieved and all hooks and the route get executed in order.

Execution Order

The order in which Routes and Hooks are added to the router is important.
Hooks and Routes are executed in the same order they are defined (Top Down order)
import {Routes, registerRoutes} from '@mionkit/router';

const routes = {
    authorizationHook: {hook(): void {}}, // hook
    users: {
        userOnlyHook: {hook(): void {}}, // scoped hook
        getUser: (): null => null, // route
        setUser: (): null => null, // route
    },
    pets: {
        getPet: (): null => null, // route
        setPet: (): null => null, // route
    },
    errorHandlerHook: {hook(): void {}}, // hook
    loggingHook: {hook(): void {}}, // hook
} satisfies Routes;

export const myValidApi = registerRoutes(routes);

Generated execution path for: pets.getPets

graph LR A(authorizationHook) --> B{{getPet}} --> E(errorHandlerHook) --> C(loggingHook) style B color:#018c64

Hook's Scope

We can limit hooks to be executed only on a subset of routes.

The userOnlyHook from previous example will be executed only for the routes under users but not for routes under pets.

Generated execution path for: users.getUser

graph LR A(authorizationHook) --> B(userOnlyHook) --> C{{getUser}} --> E(errorHandlerHook) --> D(loggingHook) style B color:#b90f40 style C color:#018c64

Invalid Route Names

To guarantee the correct execution order, hooks and routes names CAN'T be numeric or digits only. You can read more about order of properties in JS objects here and here.

An error is thrown when registering routes when invalid route names.
import {Routes, registerRoutes} from '@mionkit/router';

const invalidRoutes = {
    authorizationHook: {hook(): void {}}, // hook
    1: {
        // Invalid naming !!!
        userOnlyHook: {hook(): void {}}, // hook
        getUser: (): null => null, // route
    },
    '2': {
        // Invalid naming !!!
        getPet: (): null => null, // route
    },
    errorHandlerHook: {hook(): void {}}, // hook
    loggingHook: {hook(): void {}}, // hook
} satisfies Routes;

// Throws an error as there are invalid route names
export const myInvalidApi = registerRoutes(invalidRoutes);