0
0
Expressframework~5 mins

Middleware factory pattern in Express - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a middleware factory in Express?
A middleware factory is a function that returns a middleware function. It allows you to create middleware with custom settings or parameters.
Click to reveal answer
beginner
Why use a middleware factory instead of a simple middleware function?
Middleware factories let you customize behavior by passing arguments when creating the middleware, making your code reusable and flexible.
Click to reveal answer
intermediate
Example: What does this middleware factory do?
<pre>function logger(level) {
  return function(req, res, next) {
    console.log(`[${level}] ${req.method} ${req.url}`);
    next();
  };
}</pre>
This factory creates a logger middleware that logs the HTTP method and URL with a custom log level like 'INFO' or 'DEBUG'.
Click to reveal answer
beginner
How do you apply a middleware created by a factory in Express?
Call the factory with parameters to get the middleware, then use it with app.use or route handlers, e.g., app.use(logger('INFO')).
Click to reveal answer
intermediate
What is the benefit of middleware factories for code maintenance?
They keep code DRY (Don't Repeat Yourself) by letting you write one factory and create many customized middleware instances from it.
Click to reveal answer
What does a middleware factory return in Express?
AA database connection
BA route handler
CAn Express app instance
DA middleware function
Why might you pass parameters to a middleware factory?
ATo customize middleware behavior
BTo start the server
CTo define routes
DTo connect to a database
How do you use a middleware factory in an Express app?
AUse the factory as a database model
BCall the factory and pass the result to app.use()
CImport the factory as a route
DCall app.listen() with the factory
Which of these is NOT a benefit of middleware factories?
AAutomatic database queries
BCode reuse
CCustomizable middleware
DCleaner code
What is the main difference between a middleware factory and a regular middleware?
AFactory connects to database; regular middleware logs requests
BFactory runs the server; regular middleware handles requests
CFactory returns middleware; regular middleware is the middleware itself
DFactory is a route; regular middleware is a template
Explain how a middleware factory works in Express and why it is useful.
Think about how you can create middleware that changes behavior based on input.
You got /4 concepts.
    Describe a simple example of a middleware factory and how you would use it in an Express app.
    Imagine you want to log requests with different levels.
    You got /4 concepts.