Interceptor — modify requests/responses before they reach handlers.
1class Interceptor {2 constructor() {3 this.requestInterceptors = [];4 this.responseInterceptors = [];5 }67 addRequestInterceptor(fn) {8 this.requestInterceptors.push(fn);9 }1011 addResponseInterceptor(fn) {12 this.responseInterceptors.push(fn);13 }1415 async processRequest(req) {16 for (const interceptor of this.requestInterceptors) {17 req = await interceptor(req);18 }19 return req;20 }2122 async processResponse(res) {23 for (const interceptor of this.responseInterceptors) {24 res = await interceptor(res);25 }26 return res;27 }28}2930// Express middleware31const interceptor = new Interceptor();3233// Add auth token to all requests34interceptor.addRequestInterceptor(async (req) => {35 const token = await getAuthToken();36 req.headers = req.headers || {};37 req.headers.Authorization = `Bearer ${token}`;38 return req;39});4041// Log all responses42interceptor.addResponseInterceptor(async (res) => {43 console.log("Response:", res.status, res.data);44 return res;45});4647app.use(async (req, res, next) => {48 const processedReq = await interceptor.processRequest(req);49 const originalJson = res.json.bind(res);50 res.json = async (data) => {51 const processedRes = await interceptor.processResponse({52 status: res.statusCode,53 data,54 });55 return originalJson(processedRes.data);56 };57 next();58});