Service

Simply speaking, Service is an abstract layer which is used to encapsulate business logics in complex business circumstances, and this abstraction offers advantages as below:

# Usage Scenario

# Defining Service

// app/service/user.js
const Service = require('egg').Service;

class UserService extends Service {
async find(uid) {
const user = await this.ctx.db.query('select * from user where uid = ?', uid);
return user;
}
}

module.exports = UserService;

# Properties

Framework will initialize a new Service instance for every request accessing the server, and, for the example above, several attributes are attached to this since the Service class inherits egg.Service.

# Service ctx in Detail

To get the path chain of user request, the request context is injected by us during the Service initialization, so you are able to get the related information of context directly by this.ctx in methods. For detailed information about context, please refer to Context. With ctx, we can get various convenient attributes and methods encapsulated by the framework. For example we can use:

# Notes

app/service/biz/user.js => ctx.service.biz.user
app/service/sync_user.js => ctx.service.syncUser
app/service/HackerNews.js => ctx.service.hackerNews

# Using Service

We begin to see how to use Service from a complete example below.

// app/router.js
module.exports = app => {
app.router.get('/user/:id', app.controller.user.info);
};

// app/controller/user.js
const Controller = require('egg').Controller;
class UserController extends Controller {
async info() {
const userId = ctx.params.id;
const userInfo = await ctx.service.user.find(userId);
ctx.body = userInfo;
}
}
module.exports = UserController;

// app/service/user.js
const Service = require('egg').Service;
class UserService extends Service {
// the constructor is not a must by default
// constructor(ctx) {
// super(ctx); if some processes should be made in the constructor, this statement is a must in order to use `this.ctx` later
// // get ctx through this.ctx directly
// // get app through this.app directly too
// }
async find(uid) {
// suppose we've got user's id and are going to get detailed user information from databases
const user = await this.ctx.db.query('select * from user where uid = ?', uid);

// suppose some complex processes should be made here, and demanded informations are returned then.
const picture = await this.getPicture(uid);

return {
name: user.user_name,
age: user.age,
picture,
};
}

async getPicture(uid) {
const result = await this.ctx.curl(`http://photoserver/uid=${uid}`, { dataType: 'json' });
return result.data;
}
}
module.exports = UserService;

// curl http://127.0.0.1:7001/user/1234