The Service Layer for Business Logic
🎯 Introduction
By the end of this article, you will understand the division between controllers and services, write data operations under app/service, and call them through ctx.service in controllers, following Egg's conventions.
🧱 Why Use Services?
Previously, we put the logic for retrieving and storing users in controllers. That works, but controllers become unwieldy as the application grows more complex.
Think of a controller as a restaurant's front-of-house staff: greeting guests, confirming orders, and serving food. A service is the kitchen, where the food is actually prepared. Asking the front-of-house staff to cook soon becomes chaotic as more guests arrive.
A separate service layer also offers practical benefits:
- Multiple controllers can reuse the same business logic.
- When you switch to a database, only the service changes; controllers stay the same.
- Lean controllers make an endpoint's request flow easy to follow.
🛠 Writing Your First Service
Create user.js under app/service and define a class that extends Service:
const { Service } = require('egg');
class UserService extends Service {
async findAll() {
// Start with fixed sample data; replace it with real data operations later
return [
{ id: 1, name: 'Ming', age: 18 },
{ id: 2, name: 'Hong', age: 20 },
];
}
}
module.exports = UserService;
The loading convention is the same as for controllers: call findAll in app/service/user.js through ctx.service.user.findAll(). Use it in a controller like this:
const { Controller } = require('egg');
class UserController extends Controller {
async index() {
const { ctx } = this;
const users = await ctx.service.user.findAll();
ctx.body = users;
}
}
module.exports = UserController;
Visit GET /users to retrieve the user list. Services can also access the context through this.ctx and the application instance through this.app when needed.
🛠 Simulating Data Operations with an In-Memory Array
Before connecting a database, we can use an in-memory array and wrap create, read, update, and delete operations in service methods:
const { Service } = require('egg');
// Simulate a database with a module-level array shared across requests; reset on restart
const users = [
{ id: 1, name: 'Ming', age: 18 },
{ id: 2, name: 'Hong', age: 20 },
];
let nextId = 3;
class UserService extends Service {
// List all users
async findAll() {
return users;
}
// Find a user by ID
async findById(id) {
return users.find(item => item.id === Number(id));
}
// Create
async create(data) {
const user = { id: nextId++, name: data.name, age: data.age };
users.push(user);
return user;
}
// Update
async update(id, data) {
const user = await this.findById(id);
if (!user) return null;
if (data.name !== undefined) user.name = data.name;
if (data.age !== undefined) user.age = data.age;
return user;
}
// Delete
async remove(id) {
const index = users.findIndex(item => item.id === Number(id));
if (index === -1) return false;
users.splice(index, 1);
return true;
}
}
module.exports = UserService;
this.users, each request starts with fresh data, so a query immediately after creation will not find the new user. Module scope lets requests share the same data. This is a temporary learning approach; real applications should use a database.🛠 Calling a Service from a Controller
With router.resources('users', '/users', controller.user) from the previous article, the controller becomes a coordinator:
const { Controller } = require('egg');
class UserController extends Controller {
// GET /users
async index() {
const { ctx } = this;
ctx.body = await ctx.service.user.findAll();
}
// GET /users/:id
async show() {
const { ctx } = this;
const user = await ctx.service.user.findById(ctx.params.id);
if (!user) {
ctx.status = 404;
ctx.body = { message: 'User not found' };
return;
}
ctx.body = user;
}
// POST /users
async create() {
const { ctx } = this;
const user = await ctx.service.user.create(ctx.request.body);
ctx.status = 201;
ctx.body = user;
}
}
module.exports = UserController;
The controller no longer contains data operation details. It simply reads parameters, calls a service, and returns the result.
⚡ Why Are Service Methods async?
Operations on an in-memory array are synchronous, so why add async?
This prepares the code for future changes. Real services access databases asynchronously. Defining methods with async and calling them with await now means you can later replace their internals with database operations without changing their signatures or the controllers.
❓ Questions and Answers
Q1: Are thin controllers and services overengineering?
The benefits may be less obvious in a small demo, but they become clear as business logic grows. Egg projects follow this convention, so using it from the start builds good habits and makes teamwork easier.
Q2: Can one service call another?
Yes. Use this.ctx.service.otherServiceName. For example, an order service can call a user service to look up user information.
Q3: Why define the array outside the class?
Egg creates a new service instance for each request by default, so instance data is isolated. At module scope, the module loads once and requests share the array, allowing additions and updates to persist across requests.
Q4: Must services extend the Service base class?
Following Egg's convention, extend the base class so the framework exposes the service through ctx.service and provides this.ctx and this.app.
🧪 Exercise
Create app/service/goods.js with a goods service that provides findAll and findById, using an in-memory array, and call it from a controller.
const { Service } = require('egg');
// Module-level sample data
const goods = [
{ id: 1, name: 'Keyboard', price: 99 },
{ id: 2, name: 'Mouse', price: 49 },
];
class GoodsService extends Service {
async findAll() {
// Write your code here
}
async findById(id) {
// Write your code here
}
}
module.exports = GoodsService;
🎉 You now understand the service layer! Next, we will explore Egg's configuration system and custom middleware.
Routes and Controllers
Define Egg.js routes, write controllers, read request parameters, and return responses while understanding each controller's responsibilities.
Configuration and Middleware
Configure Egg.js for different environments, write and register custom middleware, and understand its built-in security features.
