Plugin architecture — extend functionality without modifying core code.
1// Plugin system2class PluginManager {3 constructor() {4 this.plugins = [];5 this.hooks = new Map();6 }78 register(plugin) {9 this.plugins.push(plugin);10 if (plugin.hooks) {11 for (const [name, fn] of Object.entries(plugin.hooks)) {12 if (!this.hooks.has(name)) this.hooks.set(name, []);13 this.hooks.get(name).push(fn);14 }15 }16 }1718 async execute(hookName, context) {19 const hooks = this.hooks.get(hookName) || [];20 for (const hook of hooks) {21 await hook(context);22 }23 return context;24 }25}2627// Plugin28const loggerPlugin = {29 name: "logger",30 hooks: {31 "request:start": async (ctx) => {32 console.log(`${ctx.method} ${ctx.url}`);33 },34 "request:end": async (ctx) => {35 console.log(`Finished in ${ctx.duration}ms`);36 },37 },38};3940const manager = new PluginManager();41manager.register(loggerPlugin);42await manager.execute("request:start", { method: "GET", url: "/" });
Key concepts: