Controller, Service, and Repository Responsibilities

Build a layered user endpoint and verify which parts change when the data source is replaced

🎯 Introduction

By the end of this article, you will be able to split a user query into request handling, business processing, and database access and identify where to make changes.

🗃 The Repository queries the database

Install the dependency for this section:

npm install mysql2@3.11.5

Use the user table from the MySQL Integration course, with id and username fields. Prepare a working connection URL in DATABASE_URL, using mysql://username:password@host:3306/database. Do not commit real credentials.

Create database.mjs and a connection pool. A connection pool maintains reusable database connections so each request need not reconnect:

database.mjs
import mysql from 'mysql2/promise';

if (!process.env.DATABASE_URL) throw new Error('Configure DATABASE_URL');
export const pool = mysql.createPool(process.env.DATABASE_URL);

Create user-repository.mjs solely to query records:

user-repository.mjs
import { pool } from './database.mjs';

export async function findUser(id) {
    const [rows] = await pool.execute(
        'SELECT id, username FROM user WHERE id = ?', [id]
    );
    return rows[0] ?? null;
}

The placeholder receives the ID through parameter binding; never concatenate client values into SQL. Return the database record when found, null when missing, and throw if the query fails.


⚙️ The Service provides business-facing data

Create user-service.mjs:

user-service.mjs
import { findUser } from './user-repository.mjs';

export async function getUserProfile(id) {
    const user = await findUser(id);
    if (!user) return null;
    return { id: user.id, name: user.username };
}

The API field is name while the database field is username. The Service maps it and returns only public fields. Add future business checks, such as account state, here too. The controller chooses HTTP statuses.


🚪 The Controller reads parameters and responds

Create user-controller.mjs:

user-controller.mjs
import { getUserProfile } from './user-service.mjs';

export async function showUser(req, res) {
    const id = Number(req.params.id);
    if (!/^[1-9]\d*$/.test(req.params.id) || !Number.isSafeInteger(id)) {
        return res.status(400).json({ error: 'Invalid user ID' });
    }
    const user = await getUserProfile(id);
    if (!user) return res.status(404).json({ error: 'User not found' });
    res.json({ data: user });
}

Pass a valid ID to the business function. Return 404 if missing, or 200 with the profile on success. Database failures reject the async function, and Express 5 forwards them to error middleware. The controller need not repeat a try/catch wrapper.


🔗 Connect the user query endpoint

Create user-app.mjs and connect the controller to its URL:

user-app.mjs
import express from 'express';
import { showUser } from './user-controller.mjs';
import { errorHandler } from './error-handler.mjs';

export const app = express();
app.get('/users/:id', showUser);
app.use(errorHandler);

For /users/1, the controller reads the ID, the Service shapes the fields, and the Repository queries the record. The middleware from the shared exception handling article handles database and other errors. Use the framework course's Router approach when multiple route files are needed.


🚀 Start and inspect the results

Create the startup file:

user-server.mjs
import { app } from './user-app.mjs';

app.listen(3000, '127.0.0.1');

Configure the database URL in .env, then run:

node --env-file=.env user-server.mjs

With a database record whose ID is 1 and username is Ming, /users/1 returns {"data":{"id":1,"name":"Ming"}}. A missing ID returns 404; /users/abc returns 400.

This endpoint publicly reads basic profile information. For private data, register authentication middleware first, then let the business layer decide whether the current user can access the target record.


🔄 Making changes after layering

For API field renaming, inspect the Service's return structure. For table or driver changes, update the Repository. For request parameters or response statuses, update the Controller.

For example, renaming the database's name column only requires a query or mapping change; the API can still return name. Preserve the external result while changing the internal data source.


❓ Questions and Answers

Q1: Must every simple endpoint use all these files?

No. Split when business rules or data access need independent maintenance. Avoid empty layers that only forward a single call.

Q2: Can the Repository call res.json directly?

Return data and let the controller respond, so database access can also serve background jobs and tests.

Q3: Will adding a password column automatically expose it to the frontend?

Not in this example: both the query and returned object explicitly select public fields.


🧪 Practice

Add a user record to the test database, query it, and verify the response. Then request a missing ID and confirm 404.

// Record your results here