Introduction
Middleware and decorator patterns help add extra features to code without changing the main parts. They keep code clean and easy to manage.
Middleware example (Express.js):
app.use(function(req, res, next) {
// do something
next();
});
Decorator example:
function decorator(originalFunction) {
return function(...args) {
// extra work
return originalFunction(...args);
};
}app.use((req, res, next) => {
console.log('Request received');
next();
});function logDecorator(fn) {
return function(...args) {
console.log('Function called');
return fn(...args);
};
}app.use((req, res, next) => {
if (!req.user) {
res.status(401).send('Unauthorized');
} else {
next();
}
});function timingDecorator(fn) {
return function(...args) {
const start = Date.now();
const result = fn(...args);
console.log(`Time: ${Date.now() - start}ms`);
return result;
};
}This example shows middleware logging every request to the server. It also shows a decorator that adds extra text to a greeting function.
When you run this, the server logs requests and prints a decorated greeting once at start.
import express from 'express'; const app = express(); // Middleware to log requests app.use((req, res, next) => { console.log(`Received ${req.method} request for ${req.url}`); next(); }); // Simple route app.get('/', (req, res) => { res.send('Hello World'); }); // Decorator to add greeting to a function function greetDecorator(fn) { return function(name) { const original = fn(name); return original + ' Have a nice day!'; }; } function greet(name) { return `Hello, ${name}!`; } const decoratedGreet = greetDecorator(greet); // Start server app.listen(3000, () => { console.log('Server running on port 3000'); console.log(decoratedGreet('Alice')); });
function logDecorator(fn) {
return function(...args) {
console.log('Calling function');
return fn(...args);
};
}
function greet(name) {
return `Hello, ${name}!`;
}
const decoratedGreet = logDecorator(greet);
console.log(decoratedGreet('Alice'));function logger(req, res, next) {
console.log('Request URL:', req.url);
next;
}function fetchData(userId) {
return `Data for user ${userId}`;
}Pass the test and this pattern moves unknown