📖 Scenario: You are building a simple Express server that needs to use a service for greeting users. To keep your code clean and testable, you will use dependency injection to provide the greeting service to your route handler.
🎯 Goal: Create an Express app that uses dependency injection to pass a greeting service to a route handler. The app will respond with a greeting message when a user visits the /greet endpoint.
📋 What You'll Learn
Create a greeting service function that returns a greeting string.
Create a configuration variable for the greeting message prefix.
Inject the greeting service into the Express route handler.
Set up the Express app to listen on port 3000.
💡 Why This Matters
🌍 Real World
Dependency injection helps keep Express apps modular and testable by separating service logic from route handlers.
💼 Career
Understanding dependency injection is important for writing clean, maintainable backend code in Node.js and Express, a common skill in web development jobs.
Progress0 / 4 steps
1
Create the greeting service function
Create a function called greetingService that takes a name parameter and returns the string `Hello, ${name}!`.
Express
Hint
Define a function that uses a template string to return a greeting.
2
Create a greeting prefix configuration variable
Create a constant called greetingPrefix and set it to the string 'Hello'.
Express
Hint
Create a constant variable to hold the greeting prefix string.
3
Inject the greeting service into the Express route handler
Create an Express app by requiring express and calling express(). Then create a route handler for /greet that uses the injected greetingService to send a greeting for the query parameter name. Use req.query.name to get the name.
Express
Hint
Use express() to create the app and define a GET route for /greet. Use the greeting service inside the route.
4
Start the Express server on port 3000
Add code to make the Express app listen on port 3000 using app.listen.
Express
Hint
Use app.listen(3000) to start the server on port 3000.
Practice
(1/5)
1. What is the main purpose of dependency injection in an Express app?
easy
A. To provide parts of the app with the resources they need without hardcoding them
B. To make the app run faster by caching data
C. To automatically generate routes based on file names
D. To handle errors globally in the app
Solution
Step 1: Understand dependency injection concept
Dependency injection means giving parts of your app what they need instead of making them find it themselves.
Step 2: Identify the purpose in Express
In Express, this helps keep code organized and flexible by passing dependencies explicitly.
Final Answer:
To provide parts of the app with the resources they need without hardcoding them -> Option A
Quick Check:
Dependency injection = Provide needed resources [OK]
Hint: Think: "Give what is needed, don't make it find" [OK]
Common Mistakes:
Confusing dependency injection with caching
Thinking it auto-generates routes
Mixing it with error handling
2. Which of the following is the correct way to inject a service into an Express router?
easy
A. const router = express.Router(); router.use(service);
B. const router = express.Router(service);
C. function createRouter(service) { const router = express.Router(); router.service = service; return router; }
D. const router = express.Router(); router.service = service();
Solution
Step 1: Check how to pass dependencies in Express
Express.Router() does not accept parameters directly, so passing service as argument is invalid.
Step 2: Use a factory function to inject service
Creating a function that takes service and returns a router with service attached is the correct pattern.
Final Answer:
function createRouter(service) { const router = express.Router(); router.service = service; return router; } -> Option C
Quick Check:
Inject by factory function = function createRouter(service) { const router = express.Router(); router.service = service; return router; } [OK]
Hint: Use a function to pass dependencies, not Router constructor [OK]
Common Mistakes:
Passing service directly to express.Router()
Calling service as a middleware incorrectly
Assigning service without a factory function
3. Consider this code snippet:
function createService() {
return { getName: () => 'MyService' };
}
function createRouter(service) {
const router = require('express').Router();
router.get('/name', (req, res) => {
res.send(service.getName());
});
return router;
}
const service = createService();
const router = createRouter(service);
// What happens when a GET request is made to '/name'?
medium
A. The server will crash due to missing middleware
B. The response will be undefined
C. There will be a runtime error because service is not defined
D. The response will be 'MyService'
Solution
Step 1: Analyze service creation
The createService function returns an object with getName method returning 'MyService'.
Step 2: Analyze router handler
The router uses the injected service and calls getName to send the response on '/name' route.
Final Answer:
The response will be 'MyService' -> Option D
Quick Check:
Injected service method returns 'MyService' [OK]
Hint: Injected service methods run as expected in route handlers [OK]