node_egg_service Service

// Service (Service) 
// simple terms, Service is an abstraction layer for doing business logic is encapsulated in a complex business scenarios, providing this abstract has the following advantages: 
  keep the Controller logic in a more concise.
  Maintain the independence of business logic, abstracted Service can be called repeatedly multiple Controller.
  The separation of logic and presentation, easier to write test cases,

// usage scenarios 
  dealing with complex data, such as information to show the need to obtain from the database, but also through certain rules of calculation, in order to return to the user display. Or after completion of the calculation, to update the database.
  Call third-party services, such as access to information and so on GitHub.

// 定义 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;

// Each time a user request, instantiates the corresponding frame will Service instance, since it inherits egg.Service, so we have developed to facilitate the following properties: 
  the this .ctx: Context object instance context current request, through which we can encapsulated frame to get a variety of convenient handling properties and methods of the current request.
  the this the .app: Examples of the Application object of the current application, through its global objects and methods provided by the framework that we can get.
  the this .service: application-defined Service, through which we can have access to other business layer, is equivalent to the this .ctx.service.
  the this .config: the application run-time configuration items.
  the this .logger: Logger objects, the above four methods (debug, info, warn, error ), representing four different levels of print logs, and use the results as described in context logger


// Service ctx explain 
  the this .ctx.curl initiate network calls.
  the this .ctx.service.otherService call other Service.
  the this .ctx.db initiate database calls, etc., db may be other plug-in modules to be mounted in advance on the app


// Service files must be placed in app / service directory, can support multi-level directory, when accessing the directory names can be accessed through the cascade. 

  App /service/biz/user.js => ctx.service.biz.user
  app/service/sync_user.js => ctx.service.syncUser
  App /service/HackerNews.js => ctx.service.hackerNews
 // a Service file can contain only one class that needs to be returned by module.exports way. 
// Service Class needs to be defined by the way, the parent must be egg.Service. 
// Service not a single embodiment, an object is a request level, the frame delay instantiation ctx.service.xx each first access request, the Service may be obtained by context this.ctx current request.


// use the service curl http://127.0.0.1:7001/user/1234

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

// app/controller/user.js
const Controller = require('egg').Controller;
class UserController extends Controller {
  async info() {
    const { ctx } = this;
    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 {
  // default constructor is not required to provide. 
  // constructor (ctx) { 
  //    Super (ctx); if you need to do some processing in the constructor, must have these words, in order to ensure `behind the use this.ctx`. 
  //    // this.ctx can be directly acquired by the ctx 
  //    // this.app also be acquired directly by the app 
  @ } 
  the async Find (UID) {
     // If we got a user from the database to obtain the user id Details information 
    const = the User the await the this .ctx.db.query ( 'the SELECT * from the User the wHERE uid =?' , uid);
     // assume that there are some complex calculations here, and then return the required information. 
    the await Picture = const the 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;

 

Guess you like

Origin www.cnblogs.com/JunLan/p/12536282.html