Bird
Raised Fist0
Expressframework~20 mins

Service layer pattern in Express - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Service Layer Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
1:30remaining
What does this Express service layer return?
Consider this service function called by a route handler. What will be the resolved value when calling getUserById(2)?
Express
const users = [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}];

function getUserById(id) {
  return new Promise((resolve) => {
    const user = users.find(u => u.id === id);
    resolve(user ? user.name : null);
  });
}
A"Bob"
B"{ id: 2, name: 'Bob' }"
Cnull
Dundefined
Attempts:
2 left
💡 Hint
Look at what the promise resolves with: the user's name or the whole user object.
❓ state_output
intermediate
1:30remaining
What is the final state of req.user after middleware and service call?
Given this Express middleware and service call, what will req.user contain after next()?
Express
const users = [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}];

function userService(id) {
  return users.find(u => u.id === id) || null;
}

function authMiddleware(req, res, next) {
  req.user = userService(1);
  next();
}
A{ id: 2, name: 'Bob' }
Bnull
Cundefined
D{ id: 1, name: 'Alice' }
Attempts:
2 left
💡 Hint
Check what userService returns for id 1.
📝 Syntax
advanced
2:00remaining
Which option correctly implements an async service function in Express?
You want to create a service function that fetches user data asynchronously. Which option is syntactically correct and returns a promise resolving to the user object?
Express
const users = [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}];
Aasync function getUser(id) { return users.find(u => u.id === id); }
Bfunction getUser(id) { return new Promise(resolve => resolve(users.find(u => u.id === id))); }
Casync function getUser(id) { const user = users.find(u => u.id === id); return user; }
Dfunction getUser(id) { return await users.find(u => u.id === id); }
Attempts:
2 left
💡 Hint
Remember that Array.find is synchronous and does not return a promise.
🔧 Debug
advanced
2:00remaining
Why does this Express service call cause an unhandled promise rejection?
Examine the code below. Why does calling getUserById(3) cause an unhandled promise rejection?
Express
const users = [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}];

function getUserById(id) {
  return new Promise((resolve, reject) => {
    const user = users.find(u => u.id === id);
    if (!user) reject('User not found');
    else resolve(user);
  });
}

getUserById(3).then(user => console.log(user));
ABecause the promise rejects but there is no catch handler to handle the rejection.
BBecause users.find throws an error when user is not found.
CBecause resolve is called twice causing a conflict.
DBecause the function does not return a promise.
Attempts:
2 left
💡 Hint
Check how the promise rejection is handled after calling getUserById.
🧠 Conceptual
expert
1:30remaining
What is the main benefit of using a service layer in Express apps?
Why do developers use a service layer between Express route handlers and data access logic?
ATo replace middleware functions with simpler code.
BTo speed up HTTP requests by caching all responses automatically.
CTo separate business logic from routing logic, making code easier to maintain and test.
DTo directly connect route handlers to the database without abstraction.
Attempts:
2 left
💡 Hint
Think about code organization and responsibilities.

Practice

(1/5)
1. What is the main purpose of the service layer pattern in an Express application?
easy
A. To manage database connections only
B. To handle HTTP requests and responses directly
C. To separate business logic from route handling for cleaner code
D. To serve static files like images and CSS

Solution

  1. Step 1: Understand the role of route handlers

    Route handlers in Express mainly handle HTTP requests and responses, not business logic.
  2. Step 2: Identify the service layer role

    The service layer contains business logic, keeping route handlers clean and focused on HTTP concerns.
  3. Final Answer:

    To separate business logic from route handling for cleaner code -> Option C
  4. Quick Check:

    Service layer = separates logic [OK]
Hint: Service layer keeps logic out of routes for clarity [OK]
Common Mistakes:
  • Confusing service layer with route handlers
  • Thinking service layer manages HTTP directly
  • Assuming service layer only handles database connections
2. Which of the following is the correct way to use a service function inside an Express route handler?
easy
A. const result = serviceFunction(); res.send(result);
B. res.send(serviceFunction);
C. serviceFunction(res);
D. res.send(await serviceFunction);

Solution

  1. Step 1: Understand service function usage

    Service functions are called to get results, which are then sent in the response.
  2. Step 2: Check syntax correctness

    const result = serviceFunction(); res.send(result); calls the function and sends its result correctly. res.send(serviceFunction); sends the function itself, not its result. serviceFunction(res); wrongly passes response object to service. res.send(await serviceFunction); misses parentheses and awaits incorrectly.
  3. Final Answer:

    const result = serviceFunction(); res.send(result); -> Option A
  4. Quick Check:

    Call service, then send result [OK]
Hint: Call service function, then send its result [OK]
Common Mistakes:
  • Sending the function instead of its result
  • Passing Express response object to service
  • Incorrect use of async/await syntax
3. Given this Express route and service code, what will be the response when a GET request is made to /user/42?
const userService = {
  getUserById: (id) => ({ id, name: `User${id}` })
};

app.get('/user/:id', (req, res) => {
  const user = userService.getUserById(req.params.id);
  res.json(user);
});
medium
A. {"id":"42","name":"User"}
B. {"id":42,"name":"User42"}
C. Error: getUserById is not a function
D. {"id":"42","name":"User42"}

Solution

  1. Step 1: Analyze service function output

    The service returns an object with id as string and name as 'User' plus id string.
  2. Step 2: Check route response

    The route sends JSON of the user object, so id remains a string "42" and name is "User42".
  3. Final Answer:

    {"id":"42","name":"User42"} -> Option D
  4. Quick Check:

    Service returns object with string id [OK]
Hint: Check data types returned by service [OK]
Common Mistakes:
  • Assuming id is a number instead of string
  • Expecting an error from correct code
  • Ignoring string concatenation in name
4. Identify the error in this Express route using a service layer:
app.get('/items', (req, res) => {
  const items = itemService.getAllItems;
  res.json(items);
});
medium
A. Incorrect route path syntax
B. Missing parentheses when calling getAllItems function
C. res.json cannot send arrays
D. itemService is not defined

Solution

  1. Step 1: Check function call syntax

    The code assigns the function itself to items without calling it (missing parentheses).
  2. Step 2: Understand impact on response

    res.json(items) sends the function reference, not the data, causing wrong output or error.
  3. Final Answer:

    Missing parentheses when calling getAllItems function -> Option B
  4. Quick Check:

    Call functions with () to get results [OK]
Hint: Always use () to call service functions [OK]
Common Mistakes:
  • Forgetting parentheses on function calls
  • Thinking res.json can't send arrays
  • Assuming route path syntax is wrong
5. You want to add error handling in your service layer for a function that fetches a user by ID asynchronously. Which approach correctly separates concerns and handles errors in Express using the service layer pattern?
// Service function
async function getUserById(id) {
  if (!id) throw new Error('ID required');
  // simulate async DB call
  return { id, name: `User${id}` };
}

// Route handler
app.get('/user/:id', async (req, res) => {
  try {
    const user = await getUserById(req.params.id);
    res.json(user);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});
hard
A. Correctly separates logic and handles errors in route
B. Error handling should be inside the route only
C. Service should send response directly, not return data
D. Try/catch is unnecessary with async functions

Solution

  1. Step 1: Check separation of concerns

    The service function only throws errors or returns data, no response handling.
  2. Step 2: Verify error handling location

    The route handler catches errors and sends HTTP responses, keeping concerns separate.
  3. Final Answer:

    Correctly separates logic and handles errors in route -> Option A
  4. Quick Check:

    Service throws errors; route handles responses [OK]
Hint: Throw errors in service; catch and respond in route [OK]
Common Mistakes:
  • Putting response logic inside service functions
  • Ignoring try/catch for async errors
  • Handling errors only in service without route awareness
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard