preface

State-owned national law, the home has rules, when we are a group of people together when doing one thing, if not restrained, everyone’s way of doing things will be according to their favorite way, messy, let later entrants will need more time, familiar with the predecessors, the things you did do is messy, however, why don’t we to restrain them.

Eggjs is a NodeJS framework, inherited from KOA framework. Egg.js is born for enterprise-level frameworks and applications.

The website address

Github personal source: github.com/xiloudada/E…

The installation

Environmental requirements

  • The minimum requirement for nodeJS is 8.x

Erection of scaffolding

$ mkdir egg-example && cd egg-example
$ npm init egg --type=simple
$ npm i
Copy the code

The website also has a step-by-step building process

Directory structure constraints

This section describes the directory structure constraints on the official website

An egg - project ├ ─ ─ package. Json ├ ─ ─ app. Js (optional) ├ ─ ─ agent. The js (optional) ├ ─ ─ app | ├ ─ ─ the router. The js │ ├ ─ ─ controller │ | └ ─ ─ home. Js │ │ ├ ─ ─ service (optional) | └ ─ ─ the user. The js │ ├ ─ ─ middleware (optional) │ | └ ─ ─ response_time. Js │ ├ ─ ─ the schedule (optional) │ | └ ─ ─ my_task. Js │ │ ├ ─ ─ public (optional) | └ ─ ─ reset. CSS │ ├ ─ ─ the view (optional) │ | └ ─ ─ home. TPL │ └ ─ ─ the extend (optional) │ ├ ─ ─ helper. Js (optional) │ ├ ─ ─ Request. Js (optional) │ ├ ─ ─ the response. The js (optional) │ ├ ─ ─ the context, js (optional) │ ├ ─ ─ application. Js (optional) │ └ ─ ─ agent. The js (optional) ├ ─ ─ the config | ├ ─ ─ plugin. Js | ├ ─ ─ config. The default. The js │ ├ ─ ─ config. Prod. Js | ├ ─ ─ config. The test. The js (optional) | ├ ─ ─ config. Local, js (optional) | └ ─ ─ Config. Unittest. Js (optional) └ ─ ─ the test ├ ─ ─ middleware | └ ─ ─ response_time. Test. The js └ ─ ─ controller └ ─ ─ home. Test. JsCopy the code

Built-in base object

The official website has built-in links to basic objects

The EggJS framework inherits four objects (Application, Context, Request, and Response) from the KOA framework. The framework also extends some objects (Controller, Service, Helper,Config,Looger).

The Application object

The Application object is a global object, and only one is instantiated. The Application object inherits from the KOa. Application object, on which some global methods and properties can be mounted

Simple to use

We express the use of technology in terms of business, for example we now have an accounting business.

router

First we have to have an API, when we have multiple apis, how do we differentiate? Use the Router route to distribute the request. We create router.js under the app file to use the routing functionality by structuring the Router from the Application object

// router.js 
module.exports = app= > {
  const { router, controller, jwt } = app;
  // Login interface
  router.get('/keeping/api/v1/login', controller.login.login);
  // Query the user
  router.get('/keeping/api/v1/getUser', jwt, controller.user.selectUser);
};
// The first argument is the address of the access, the second argument tells us that the match is successful and distributed to the corresponding controller,
Copy the code

costroller

When we distribute to the corresponding controller to parse the user’s input, we return the corresponding result after processing.

Create a controller.js file under the app and get the user’s input value. We will split the business logic and call the corresponding business logic, which is what we call service

// controller.js
const { Controller } = require('egg');

class LoginController extends Controller {
  / / login API
  async login() {
    const { ctx, app } = this;
     // Get the user's input value
    const query = ctx.query;
    // Invoke the service service
    const loginInfo = await ctx.service.login.login(query);
   / / token is generated
    const token = app.jwt.sign({
      user: loginInfo,
    }, app.config.jwt.secret);
    const openid = loginInfo.openid;
    / / the return value
    ctx.body = {
      openid,
      token: `Bearer ${token}`.success: 'Successful landing'.code: 200}; }// Query the user
  async selectUser() {
    const { ctx } = this;
    const query = ctx.query;
    console.log(query, '... query======');
    const user = await ctx.service.user.selectUser(query);
    if (user) {
      this.ctx.body = {
        success: true.message: 'Query successful'.status: 200.data: user,
      };
    } else {
      this.ctx.body = {
        success: false.message: 'Query failed'.status: 40023}; }}}module.exports = LoginController;
Copy the code

service

The controller calls the service business logic. We create a service file under the APP file and write the package of the extracted business logic under the service file. By pulling out the business logic, we make our controller more concise and maintain the independence of business. The extracted service can be used by multiple controllers.

// service.js
const { Service } = require('egg');
class LoginService extends Service {
  / / login
  async login(data) {
    const { app, ctx } = this;
     // This interface is called by reference by setting constants under config
    const { appid, secret } = app.config.weapp;
    const result = await ctx.curl(`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${data.code}&grant_type=authorization_code`, { dataType: 'json' });
    const aa = await ctx.service.user.selectUser(result.data);
    if(! aa) {await ctx.service.user.addUser({ openid: result.data.openid });
    }
    return result.data;
  }
  
  // Query the user
  async selectUser(openid) {
    const { app } = this;
    const userTable = app.config.sqlTable.user;
    const user = await app.mysql.get(userTable, openid);
    returnuser; }}module.exports = LoginService;
Copy the code

config

If you want to use a database, you need to use plugin. For example, if you want to use mysql database, you need to install egg-mysql, and then declare in config/plugin.js:

/ / configure the mysql
  mysql: {
    enable: true.package: 'egg-mysql',},Copy the code

Then configure the database connection configuration in config/config.default.js

/ / configure the mysql
  config.mysql = {
    // Configure single database information
    client: {
      host: 'localhost'./ / host name
      port: '3306'./ / the port number
      user: 'root'.// Database user name
      password: '123456'.// Database password
      database: 'xilou'.// Database table name
    },
    // Whether to load to app, enabled by default
    app: true.agent: false};Copy the code

Later, some egg-Cors plug-ins will be configured to solve cross-domain problems, and egg-jwt plug-ins will be generated to generate tokens. The configuration is similar to mysql, and such a process will be completed. We will use Postman for request, because the database has been configured. Now let’s query a request from a user whose data I have inserted into the database

The middleware

We can write our own middleware, put it under the app/middleware file, and configure the middleware under config.default.js

conclusion

The basic use of EggJS has been described above.

Eggjs provides conventions for development teams, which facilitates team development and reduces learning costs for developers, out of the box.

  • Eggjs uses a route to distribute the request, which action is performed
  • The controller is responsible for parsing the user’s input and processing and returning the corresponding results
  • Use service to handle the corresponding business logic
  • Because NodeJS is asynchronous, async is used for processing
  • The rest is nothing more than using plug-ins to enhance functionality, such as connecting to a database, or using middleware to enhance functionality by mounting it under Application

If there are any improper words, mistakes, welcome to correct, will be changed later