Lesson 52-Deep Dive into Koa Design Patterns

Using the Onion Model to Implement Middleware

Onion Model Concept

The onion model is a design pattern commonly used to describe the execution flow of middleware. In Koa2, middleware execution resembles peeling an onion, moving from the outermost layer inward and then returning outward. This model provides a clear structure for handling asynchronous requests, making middleware easy to invoke, understand, and maintain.

Onion Model Implementation in Koa2

Koa2’s middleware execution mechanism is designed based on the onion model. When a request arrives, Koa2 starts executing from the outermost middleware, progressing to the innermost layer, and then backtracks until all middleware execution is complete.

Registering Middleware in Koa2

In Koa2, middleware is registered using the app.use() method. Each middleware is an asynchronous function that accepts ctx and next as parameters.

const Koa = require('koa');
const app = new Koa();

app.use(async (ctx, next) => {
    console.log('Middleware 1');
    await next();
});

app.use(async (ctx, next) => {
    console.log('Middleware 2');
    await next();
});

Middleware Execution Flow

When a request arrives, Koa2 begins execution with the first middleware. Each middleware executes its logic and calls the next() function to pass control to the next middleware. When all middleware is executed or a middleware does not call next(), control backtracks to the outermost middleware.

Onion Model Code Implementation

Below is an example demonstrating the middleware execution flow using the onion model:

const Koa = require('koa');
const compose = require('koa-compose'); // Import koa-compose package
const app = new Koa();

// Define middleware
const middleware1 = async (ctx, next) => {
    console.log('Entering Middleware 1');
    await next();
    console.log('Leaving Middleware 1');
};

const middleware2 = async (ctx, next) => {
    console.log('Entering Middleware 2');
    await next();
    console.log('Leaving Middleware 2');
};

// Combine middleware using koa-compose
const middlewares = [middleware1, middleware2];
const middlewareStack = compose(middlewares);

// Replace default middleware execution logic
app.callback = middlewareStack;

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

In this example, two middleware functions, middleware1 and middleware2, are defined and combined using the koa-compose package. The compose function merges multiple middleware into an executable function. When the server starts and a request is sent, the middleware executes in the order defined by the onion model.

Advantages of the Onion Model

  • Clear Execution Order: The onion model ensures a clear middleware execution sequence, making it easy to understand and maintain.
  • Flexible Middleware Composition: Middleware can be freely combined to meet various requirements.
  • Error Handling: Middleware can throw or catch errors at any point, enhancing application robustness.

Object-Oriented Programming

Application of Object-Oriented Programming (OOP) in Koa2

Although Koa2 is based on Node.js’s event-driven and asynchronous I/O model, its core design fully embodies object-oriented programming principles. In Koa2, Application, Context, Request, and Response are all classes, and their instantiation and method calls form the primary interaction mechanism of the Koa2 framework.

Koa2 Core Class: Application

The Application class is the entry point of Koa2, responsible for managing middleware, listening to events, and starting the server.

class Application {
    constructor() {
        this.context = Object.create(context);
        this.middleware = [];
        // ...other initialization code
    }

    use(fn) {
        if ('function' !== typeof fn) throw new TypeError('middleware must be a function!');
        this.middleware.push(fn);
        return this;
    }

    listen(...args) {
        const server = http.createServer(this.callback());
        return server.listen(...args);
    }

    callback() {
        const fn = compose(this.middleware);
        return function (req, res) {
            const ctx = this.createContext(req, res);
            return fn(ctx).catch(err => this.onerror(err, ctx));
        }.bind(this);
    }
}

Koa2 Core Class: Context

The Context class is one of Koa2’s most central concepts, encapsulating the request and response context and providing a rich API for developers.

class Context {
    constructor(app) {
        this.app = app;
        this.request = new Request(this);
        this.response = new Response(this);
        // ...other initialization code
    }

    get body() {
        return this._body;
    }

    set body(val) {
        this._body = val;
    }

    // ...other methods and properties
}

Koa2 Core Classes: Request and Response

The Request and Response classes encapsulate the details of HTTP requests and responses, providing convenient methods and properties to read and set request headers, response headers, status codes, etc.

class Request {
    constructor(ctx) {
        this.ctx = ctx;
        // ...other initialization code
    }

    // ...various methods to read request data
}

class Response {
    constructor(ctx) {
        this.ctx = ctx;
        // ...other initialization code
    }

    status(code) {
        this.statusCode = code;
        // ...other processing
    }

    // ...various methods to set response data
}

Design Advantages of Object-Oriented Programming

  • Encapsulation: Classes and objects encapsulate complex functionality, exposing simple interfaces and reducing coupling between modules.
  • Inheritance: Koa2’s class design allows subclasses to inherit properties and methods from parent classes, facilitating extension and code reuse.
  • Polymorphism: Different objects can respond to the same message, enhancing code flexibility and maintainability.

Practical Application of Object-Oriented Programming

Below is an example of a Koa2 middleware designed using object-oriented programming principles:

const Koa = require('koa');
const app = new Koa();

class LoggerMiddleware {
    apply(app) {
        app.use(async (ctx, next) => {
            console.log(`Request received: ${ctx.method} ${ctx.url}`);
            await next();
        });
    }
}

class AuthMiddleware {
    apply(app) {
        app.use(async (ctx, next) => {
            if (!ctx.isAuthenticated()) {
                ctx.status = 401;
                ctx.body = 'Unauthorized';
                return;
            }
            await next();
        });
    }
}

const logger = new LoggerMiddleware();
const auth = new AuthMiddleware();

logger.apply(app);
auth.apply(app);

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

In this example, we define two classes, LoggerMiddleware and AuthMiddleware, each implementing an apply method to register middleware with the Koa2 application. This design makes middleware management and extension cleaner and more modular.

Decorator Pattern

Introduction to the Decorator Pattern

The decorator pattern is a design pattern that allows new responsibilities to be dynamically added to an object without altering its structure. In JavaScript, decorators are a special type of declaration that can modify class behavior. Decorators are particularly common in TypeScript, which provides native support for them.

Application of Decorators in Koa2

In Koa2, decorators can enhance class functionality, such as adding routes, middleware, or permission checks to controller methods. Decorators simplify code, making the framework more flexible and extensible.

Implementing Decorators in Koa2

Using decorators in Koa2 typically requires TypeScript. Below is an example of using decorators to define routes:

import { Router } from 'koa-router';
import { Controller, Get, Post, Put, Delete } from './decorators';

@Controller('/users')
class UserController {
    @Get('/')
    async index(ctx) {
        ctx.body = 'List of users';
    }

    @Post('/')
    async create(ctx) {
        ctx.body = 'Create user';
    }

    @Get('/:id')
    async show(ctx) {
        ctx.body = `Show user with id ${ctx.params.id}`;
    }

    @Put('/:id')
    async update(ctx) {
        ctx.body = `Update user with id ${ctx.params.id}`;
    }

    @Delete('/:id')
    async destroy(ctx) {
        ctx.body = `Delete user with id ${ctx.params.id}`;
    }
}

const router = new Router();
const controller = new UserController(router);
controller.registerRoutes();

In this example, we define Controller, Get, Post, Put, and Delete decorators. The Controller decorator specifies the base path for the controller, while Get, Post, etc., define specific route methods.

Decorator Implementation Details

Decorator functions typically receive three parameters: the target object, property key, and descriptor. For class method decorators, the target is the class prototype, the property key is the method name, and the descriptor contains the method’s configuration.

function Get(path: string) {
    return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
        const originalMethod = descriptor.value;
        descriptor.value = async function (ctx) {
            // Add additional logic here
            return await originalMethod.apply(this, arguments);
        };
        // Store route information in metadata
        Reflect.defineMetadata('route:get', path, target, propertyKey);
    };
}

Registering Routes and Middleware

In the example above, the registerRoutes method registers routes defined by decorators to the Koa2 router. This typically involves reading metadata from the class and generating corresponding route rules.

class BaseController {
    registerRoutes() {
        const methods = Object.getOwnPropertyNames(this.constructor.prototype);
        for (let method of methods) {
            if (method === 'constructor') continue;
            const route = Reflect.getMetadata('route:get', this.constructor.prototype, method);
            if (route) {
                this.router.get(route, this[method].bind(this));
            }
        }
    }
}

Koa2 Design Patterns

Core Principles

Koa2’s core principles are reflected in the following aspects:

Middleware Model

  • Koa2 uses an onion model middleware system, similar to Express but more flexible.
  • Middleware consists of functions that can perform any operation: responding, modifying request and response objects, executing header operations, or invoking downstream middleware.
  • Koa2 leverages async/await to manage middleware execution flow, making asynchronous code appear more synchronous.

Context Object

  • Koa2 introduces a Context object, encapsulating each HTTP request.
  • The Context object contains all request and response information, along with useful methods and properties.
  • Developers can directly manipulate the Context object to handle requests and responses.

Error Handling

  • Koa2 middleware can use try/catch structures to catch errors.
  • When an error is caught, it can be handled via ctx.throw() or ctx.app.emit('error', err, ctx).

Application Instance

  • A Koa2 application is a constructor that creates a new Koa instance, allowing middleware registration via the .use() method.
  • The application instance also provides other useful methods, such as listen() for listening on a port.

Koa2 Design Patterns Include:

Onion Model:

  • Middleware is invoked in sequence, with each middleware able to call the next or skip and return.
  • This model enables developers to build complex request processing chains.

Decorator Pattern:

  • The Context object uses the decorator pattern to add many useful methods and properties.
  • This pattern allows dynamic extension of the Context object’s functionality at runtime.

Composite Pattern:

  • Koa2 allows developers to compose multiple middleware to form more complex logic.
  • This pattern facilitates code organization and reuse.

Example Code

Below is a simple Koa2 application example demonstrating how to create a basic web server:

const Koa = require('koa');
const app = new Koa();

// Middleware definition
app.use(async ctx => {
    console.log(`Request URL: ${ctx.request.url}`);
    ctx.body = 'Hello, Koa!';
});

// Start the server
app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});

Deeper Implementation Details

Let’s dive into Koa2’s internal implementation, including the middleware execution flow:

const Koa = require('koa');

function Koa() {
    this.middleware = [];
}

Koa.prototype.use = function(fn) {
    if (typeof fn !== 'function') throw new TypeError('middleware must be a function!');
    this.middleware.push(fn);
    return this;
};

Koa.prototype.listen = function(...args) {
    const server = require('http').createServer(this.callback());
    server.listen(...args);
    return server;
};

Koa.prototype.callback = function() {
    const self = this;
    const handleRequest = async ctx => {
        try {
            await dispatch(0);
        } catch (err) {
            self.onerror(err, ctx);
        }
    };

    const dispatch = async id => {
        const fn = self.middleware[id];
        if (!fn) return Promise.resolve();
        try {
            await fn(ctx, () => dispatch(id + 1));
        } catch (err) {
            return Promise.reject(err);
        }
    };

    const ctx = this.createContext();
    return handleRequest.bind(ctx);
};

Koa.prototype.onerror = function(err, ctx) {
    console.error('Server Error', err);
    ctx.status = err.status || err.statusCode || 500;
    ctx.body = 'Internal Server Error';
};

Koa.prototype.createContext = function() {
    const ctx = Object.create(Koa.Context.prototype);
    ctx.app = this;
    return ctx;
};

// Context class definition
Koa.Context = class {
    constructor() {
        this.request = {};
        this.response = {};
    }
};

const app = new Koa();

app.use(async ctx => {
    console.log(`Request URL: ${ctx.request.url}`);
    ctx.body = 'Hello, Koa!';
});

app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});

In this example, we define a Koa constructor with a middleware array to store middleware functions. The use method registers middleware, and the listen method starts the server. The callback method creates the context (ctx) and defines the middleware execution flow.

Error Handling Mechanism

Koa2 provides a robust error-handling mechanism, allowing developers to catch errors in middleware and handle them based on error types.

Error Handling Example

const Koa = require('koa');
const app = new Koa();

app.use(async ctx => {
    try {
        // Simulate an error
        if (ctx.request.url === '/error') {
            throw new Error('Something went wrong!');
        }
        ctx.body = 'Hello, Koa!';
    } catch (err) {
        // Handle error
        ctx.status = 500;
        ctx.body = 'Internal Server Error: ' + err.message;
    }
});

app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});

In this example, if the requested URL is /error, an error is thrown. The error is caught, the status code is set to 500, and an error message is returned.

Context Object Implementation

The Context object is a core component of Koa2, containing all request and response information along with a series of useful methods and properties.

Context Object Implementation

Koa.Context = class {
    constructor(app) {
        this.app = app;
        this.request = new Koa.Request(this);
        this.response = new Koa.Response(this);
    }

    get subdomains() {
        return this.request.subdomains;
    }

    get host() {
        return this.request.host;
    }

    get hostname() {
        return this.request.hostname;
    }

    get fresh() {
        return this.response.fresh;
    }

    get stale() {
        return !this.fresh;
    }

    get protocol() {
        return this.request.protocol;
    }

    get method() {
        return this.request.method;
    }

    get url() {
        return this.request.url;
    }

    get originalUrl() {
        return this.request.originalUrl;
    }

    get path() {
        return this.request.path;
    }

    get query() {
        return this.request.query;
    }

    get querystring() {
        return this.request.querystring;
    }

    get search() {
        return this.request.search;
    }

    get params() {
        return this.request.params;
    }

    get body() {
        return this.request.body;
    }

    set body(val) {
        this.response.body = val;
    }

    get status() {
        return this.response.status;
    }

    set status(code) {
        this.response.status = code;
    }

    get message() {
        return this.response.message;
    }

    set message(msg) {
        this.response.message = msg;
    }

    get headers() {
        return this.response.headers;
    }

    set headers(val) {
        this.response.headers = val;
    }

    get header() {
        return this.headers;
    }

    set header(val) {
        this.headers = val;
    }

    get cookies() {
        return this.request.cookies;
    }

    set cookies(val) {
        this.response.cookies = val;
    }

    get state() {
        return this._state || (this._state = {});
    }
};

In this implementation, the Context object includes request and response properties, referencing Koa.Request and Koa.Response objects. It also provides methods and properties like body, status, and headers for convenient access and modification of request and response information.

Request and Response Objects

Koa2’s request and response objects are implemented as classes, inheriting from Koa.Context and providing additional methods and properties.

Request Object Implementation

Koa.Request = class extends Koa.Context {
    constructor(ctx) {
        super(ctx.app);
        this.ctx = ctx;
        this.header = ctx.header;
        this.method = ctx.method;
        this.url = ctx.url;
        this.originalUrl = ctx.originalUrl;
        this.querystring = ctx.querystring;
        this.query = ctx.query;
        this.params = ctx.params;
        this.body = ctx.requestBody;
        this.hostname = ctx.hostname;
        this.fresh = ctx.fresh;
        this.stale = ctx.stale;
        this.protocol = ctx.protocol;
        this.subdomains = ctx.subdomains;
    }

    get ip() {
        return this.header['x-forwarded-for'] || this.header['x-real-ip'] || this.header['remote-addr'] || this.socket.remoteAddress;
    }

    get ips() {
        let ip = this.ip;
        if (ip) return [ip];
        return [];
    }

    get host() {
        return this.header.host;
    }

    get href() {
        return this.protocol + '://' + this.host + this.url;
    }

    get secure() {
        return this.protocol === 'https';
    }

    get socket() {
        return this.ctx.socket;
    }

    get trailers() {
        return this.ctx.trailers;
    }

    get path() {
        return this.url.split('?')[0];
    }

    get search() {
        return this.url.indexOf('?') > -1 ? this.url.split('?')[1] : '';
    }

    get origin() {
        return this.protocol + '://' + this.host;
    }

    get protocol() {
        return this.header['x-forwarded-proto'] || this.header['x-url-scheme'] || this.header['x-proxy-name'] || this.socket.encrypted ? 'https' : 'http';
    }

    get method() {
        return this.header.method;
    }

    get url() {
        return this.header.url;
    }

    get originalUrl() {
        return this.header['x-original-url'] || this.header.url;
    }

    get querystring() {
        return this.header['query-string'];
    }

    get query() {
        return this.header['query'];
    }

    get params() {
        return this.header['params'];
    }

    get body() {
        return this.header['body'];
    }

    get hostname() {
        return this.header['host'].split(':')[0];
    }

    get fresh() {
        return this.header['if-none-match'] === this.header['etag'];
    }

    get stale() {
        return !this.fresh;
    }

    get subdomains() {
        return this.header['host'].split('.').slice(0, -2);
    }
};

Response Object Implementation

Koa.Response = class extends Koa.Context {
    constructor(ctx) {
        super(ctx.app);
        this.ctx = ctx;
        this.header = ctx.header;
        this.status = 200;
        this.body = null;
        this.message = '';
        this.headers = {};
    }

    get header() {
        return this.headers;
    }

    set header(val) {
        this.headers = val;
    }

    get headers() {
        return this.header;
    }

    set headers(val) {
        this.header = val;
    }

    get body() {
        return this._body;
    }

    set body(val) {
        this._body = val;
    }

    get status() {
        return this._status;
    }

    set status(code) {
        this._status = code;
    }

    get message() {
        return this._message;
    }

    set message(msg) {
        this._message = msg;
    }

    setHeader(name, value) {
        this.header[name] = value;
    }

    getHeader(name) {
        return this.header[name];
    }

    removeHeader(name) {
        delete this.header[name];
    }

    getHeaderNames() {
        return Object.keys(this.header);
    }
};

Using Middleware

Koa2’s middleware model is highly flexible, allowing easy composition of multiple middleware to handle requests and responses.

Using Middleware Example

const Koa = require('koa');
const app = new Koa();

app.use(async (ctx, next) => {
    console.log('Middleware 1');
    await next();
    console.log('Middleware 1 (after)');
});

app.use(async (ctx, next) => {
    console.log('Middleware 2');
    await next();
    console.log('Middleware 2 (after)');
});

app.use(async ctx => {
    console.log('Middleware 3');
    ctx.body = 'Hello, Koa!';
});

app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});

In this example, we define three middleware functions that are called in sequence. Each middleware can choose to call the next() function to execute the next middleware or handle the request directly.

Koa2 AOP Design

Aspect-Oriented Programming (AOP) is a programming paradigm that aims to separate cross-cutting concerns from business logic. While Koa2 does not directly support AOP, its middleware model can be used to simulate AOP behavior.

Core Concepts of AOP

Key concepts in AOP include:

  • Aspect: A modularized concern that spans multiple objects’ behaviors.
  • Join Point: A specific point in program execution, such as a method call or exception throw.
  • Advice: An action executed at a specific join point.
  • Pointcut: An expression that matches join points, specifying which join points are affected by advice.
  • Weaving: The process of integrating aspects into the program.

Implementing AOP in Koa2

In Koa2, middleware can be used to implement AOP functionality. Below, we outline how to use Koa2 middleware to realize AOP’s core concepts.

Defining Aspects

First, define an aspect, typically a middleware function executed at specific join points.

// Logging middleware
function loggingMiddleware(next) {
    console.log('Before request');
    return next().then(() => {
        console.log('After request');
    });
}

// Authentication middleware
function authMiddleware(next) {
    console.log('Before authentication');
    return next().then(() => {
        console.log('After authentication');
    });
}

Defining Join Points

In Koa2, each middleware is a join point. Middleware can be registered using app.use().

const Koa = require('koa');
const app = new Koa();

// Register logging middleware
app.use(loggingMiddleware);

// Register authentication middleware
app.use(authMiddleware);

// Define business logic
app.use(async ctx => {
    ctx.body = 'Hello, Koa!';
});

Defining Advice

In Koa2, advice is the middleware function itself, invoked when a request arrives.

// Logging middleware
function loggingMiddleware(next) {
    console.log('Before request');
    return next().then(() => {
        console.log('After request');
    });
}

// Authentication middleware
function authMiddleware(next) {
    console.log('Before authentication');
    return next().then(() => {
        console.log('After authentication');
    });
}

Defining Pointcuts

In Koa2, pointcuts can be defined by registering middleware for specific routes. For example, authentication middleware can be applied only to certain routes.

app.use(async (ctx, next) => {
    if (ctx.request.url === '/protected') {
        // Execute authentication middleware only for protected routes
        await authMiddleware(ctx, next);
    } else {
        await next();
    }
    ctx.body = 'Hello, Koa!';
});

Weaving

In Koa2, weaving is automatic. When middleware is registered using app.use(), Koa2 executes them in order.

app.use(loggingMiddleware); // Logging middleware
app.use(authMiddleware);    // Authentication middleware

Complete Example

Below is a complete example demonstrating how to use Koa2 middleware to implement AOP functionality:

const Koa = require('koa');
const app = new Koa();

// Logging middleware
function loggingMiddleware(next) {
    console.log('Before request');
    return next().then(() => {
        console.log('After request');
    });
}

// Authentication middleware
function authMiddleware(next) {
    console.log('Before authentication');
    return next().then(() => {
        console.log('After authentication');
    });
}

// Register middleware
app.use(loggingMiddleware);
app.use(authMiddleware);

// Define business logic
app.use(async (ctx, next) => {
    if (ctx.request.url === '/protected') {
        // Execute authentication middleware only for protected routes
        await authMiddleware(ctx, next);
    } else {
        await next();
    }
    ctx.body = 'Hello, Koa!';
});

// Start the server
app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});

Enhancing AOP with Decorators

In Koa2, the decorator pattern can further enhance AOP functionality, allowing dynamic addition of responsibilities without altering the original object structure.

Application of the Decorator Pattern

In Koa2, decorators can add functionality to middleware, such as logging or performance monitoring.

Example: Using a Decorator to Log Middleware Execution Time

Suppose we want to log the execution time of each middleware. We can create a decorator to achieve this:

function timeit(middleware) {
    return async function timedMiddleware(ctx, next) {
        const start = Date.now();
        await middleware(ctx, next);
        const end = Date.now();
        console.log(`Middleware ${middleware.name} took ${end - start}ms`);
    };
}

// Using the decorator
const loggingMiddleware = timeit(async (ctx, next) => {
    console.log('Before request');
    await next();
    console.log('After request');
});

const app = new Koa();

app.use(loggingMiddleware);

app.use(async ctx => {
    ctx.body = 'Hello, Koa!';
});

app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});

In this example, we define a timeit decorator that takes a middleware function as a parameter and returns a new middleware function. The new middleware logs the execution time before and after invoking the original middleware.

Implementing AOP with Higher-Order Functions

In addition to the decorator pattern, higher-order functions can be used to implement AOP. A higher-order function takes one or more functions as parameters and returns a new function.

Example: Using a Higher-Order Function for Logging

Below is an example using a higher-order function to implement logging:

function createLogger(logLevel) {
    return function loggerMiddleware(next) {
        return async function wrappedMiddleware(ctx) {
            console.log(`${logLevel}: Before request`);
            await next(ctx);
            console.log(`${logLevel}: After request`);
        };
    };
}

const app = new Koa();

// Create logging middleware
const infoLogger = createLogger('INFO');
const debugLogger = createLogger('DEBUG');

// Use logging middleware with different levels
app.use(infoLogger);
app.use(debugLogger);

app.use(async ctx => {
    ctx.body = 'Hello, Koa!';
});

app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});

In this example, we define a createLogger higher-order function that takes a log level as a parameter and returns a middleware function. The middleware logs messages before and after the request.

Implementing Complex AOP with Middleware Composition

In Koa2, complex AOP functionality can be achieved by composing multiple middleware, such as combining decorators and higher-order functions.

Example: Combining Decorators and Higher-Order Functions

Below is an example combining decorators and higher-order functions to implement logging and performance monitoring:

// Decorator
function timeit(middleware) {
    return async function timedMiddleware(ctx, next) {
        const start = Date.now();
        await middleware(ctx, next);
        const end = Date.now();
        console.log(`Middleware ${middleware.name} took ${end - start}ms`);
    };
}

// Higher-order function
function createLogger(logLevel) {
    return function loggerMiddleware(next) {
        return async function wrappedMiddleware(ctx) {
            console.log(`${logLevel}: Before request`);
            await next(ctx);
            console.log(`${logLevel}: After request`);
        };
    };
}

const app = new Koa();

// Create logging middleware
const infoLogger = createLogger('INFO');
const debugLogger = createLogger('DEBUG');

// Use decorators and higher-order functions
const timedInfoLogger = timeit(infoLogger);
const timedDebugLogger = timeit(debugLogger);

app.use(timedInfoLogger);
app.use(timedDebugLogger);

app.use(async ctx => {
    ctx.body = 'Hello, Koa!';
});

app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});

In this example, we define a timeit decorator and a createLogger higher-order function. We create two logging middleware instances, enhance them with the timeit decorator, and register the enhanced middleware with the Koa application.

Narrow and Broad Middleware in Koa2

Narrow Middleware

Narrow middleware refers to middleware that directly operates within the HTTP request and response flow. These middleware are typically registered in a Koa application using the app.use() method and handle specific HTTP request and response logic. Key characteristics of narrow middleware include:

  • Request Handling: Processes HTTP requests sent by clients.
  • Response Generation: Generates HTTP responses returned to clients.
  • Error Handling: Catches and handles errors during request processing.
  • Request and Response Modification: Modifies request or response content, such as adding response headers or altering the response body.
  • Logging: Records request-related information, such as request time, method, and URL.

Broad Middleware

Broad middleware encompasses middleware that is not limited to HTTP request handling but serves other purposes. These middleware may not directly process HTTP requests but provide general services or functionality, such as database connection management, authentication, or logging. Key characteristics of broad middleware include:

  • Service Layer Middleware: Provides service-level functionality, such as database connection pool management or cache operations.
  • Business Logic Middleware: Handles parts of business logic, such as user authentication or permission validation.
  • Framework Extension: Extends Koa framework functionality, such as adding new APIs or modifying existing API behavior.
  • Environment Configuration: Loads different configurations based on the runtime environment.
  • Logging and Monitoring: Records application logs and monitors application health.

Examples

Below are specific examples illustrating the differences between narrow and broad middleware:

Narrow Middleware Example

const Koa = require('koa');
const app = new Koa();

// Narrow middleware: Logging
app.use(async (ctx, next) => {
    console.log(`Request: ${ctx.method} ${ctx.url}`);
    await next();
});

// Narrow middleware: Error handling
app.use(async (ctx, next) => {
    try {
        await next();
    } catch (err) {
        console.error(err);
        ctx.status = 500;
        ctx.body = 'Internal Server Error';
    }
});

// Narrow middleware: Business logic processing
app.use(async ctx => {
    if (ctx.request.url === '/') {
        ctx.body = 'Welcome to the homepage';
    } else {
        ctx.status = 404;
        ctx.body = 'Not Found';
    }
});

app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});

Broad Middleware Example

const Koa = require('koa');
const app = new Koa();

// Broad middleware: Database connection management
function dbConnectMiddleware(next) {
    // Assume some database connection initialization logic here
    console.log('Connecting to the database...');
    return next().then(() => {
        console.log('Database connection closed.');
    });
}

// Broad middleware: Authentication
function authMiddleware(next) {
    // Assume some authentication logic here
    console.log('Authenticating user...');
    return next().then(() => {
        console.log('User authenticated.');
    });
}

// Register broad middleware
app.use(dbConnectMiddleware);
app.use(authMiddleware);

// Narrow middleware: Business logic processing
app.use(async ctx => {
    if (ctx.request.url === '/') {
        ctx.body = 'Welcome to the homepage';
    } else {
        ctx.status = 404;
        ctx.body = 'Not Found';
    }
});

app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});
Share your love