Egg.js Build back-end service API


Words written in the front

I’ve been studying recently Egg.js It is a koa based node development framework launched by Ali, which is born for enterprise level framework and application.Egg.js Official document ofIt’s perfect. I want to learn Egg.js You can view the official documents directly.

Because the usual development is the mode of front-end and back-end separation, I want to use egg to create background services and write a set of API interfaces to cooperate with other projects. The technology stack of this project is used Egg.js 、MongoDB、mongoose。 This article records the process of writing the registration and login module and the user center module. The purpose is to summarize the learning process in time, exercise the document ability, share and communicate with you, and make progress together.

Project address:Egg-API

During the continuous updating of the project, I would like to ask for snacks, attention, star and fork, which are the driving force for me to stick to it for a long time. _ 。) ✎_

Here is the text

requirement analysis

For the login module, the requirement analysis is as follows:

  • Register as a new user and check the input data
  • Login into the system, you need to verify the input data, based on token authentication
  • Logout function
  • Log in to view personal information in the user center module
  • Modify personal information in user center module

Data analysis and design

Explicit data:

  • User name: String user name
  • Userpass: String account password
  • Useremail: String user mailbox
  • Telphone: string mobile number
  • Avatar: String Avatar
  • Age: number age
  • Sex: String gender
  • City: String City

Implicit data:

  • Userrole: number user role (1. Ordinary user, 2. Administrator, 3. Super administrator, default user is ordinary user, super administrator is created when creating database)
  • Usercreate: Date user creation time
  • Lastlogintime: date last login time
  • Laseloginplace: String last login address

API analysis and design

In the following interface description, API refers to the interface name, params refers to the incoming data, code refers to the response result identification code, MSG refers to the response result information description, and data refers to the data successfully returned by the response

Registration interface
api: /api/v1/signup  (post)

params: {
    Username: string, // user name, unique
    Userpass: string, // user password
    Useremail: string, // user mailbox

Code: 1, registration success 0: input information is incomplete or incorrect - 1: registration failure, the user name already exists

MSG: description of the information returned by the response

data: {
    _id: _id,
    User name: user name,
    Token: generated token,
Login interface
API: / API / V1 / sign (post, request header token)

params: {
    User name: string, // user name
    Userpass: string, // user password

Code: 1, login success 0: input information is incomplete or incorrect - 1: user does not exist

MSG: description of the information returned by the response

data: {
    _id: _id,
    User name: user name,
    Lastlogintime: last login time,
    Lastloginplace: last login location,
Logout interface
api: /api/v1/signout  (get)

Code: 1. Log out successfully. The front end exits the system and clears the token

MSG: log out response return information description

data: {}
View personal information interface
API: / API / V1 / user / username (post, request header with token)

params: {
    userName: String,

Code: 1, query success 0, input information incomplete - 1, query failure

MSG: find personal information return information description

data: {
    User name: user name,
    Useremail: user email,
    Age: age,
    City: City,
Change personal information interface
api: /api/v1/user/userName (put,token)

params: {
    ... // changed information

Code: 1, update success 0, input information incomplete or wrong - 1, update failure

MSG: update personal information return information description

data: {
    User name: user name,

Coding implementation

Note: the code implementation description is only partial, please move the complete contentEgg-API

Suppose you have initialized a project, and the directory structure of the project is consistent with the official one. Because we want to use mongodb database, we need to first install egg mongoose and write it in the configuration file:

// config/plugin.js
exports.mongoose = {
    enable: true,
    package: 'egg-mongoose',
// config/config.default.js
config.mongoose = {
    url: 'mongodb://',
    options: {},

Define our schema file in the model folder:

const UserSchema = new Schema({
    userName: { type: String, unique: true, required: true, },

Route definition:'/api/v1/signup', controller.user.signup);

Controller preparation: used to parse the user’s input, and return the corresponding results after processing. We can put the acquired data into the render to render, and then send the rendered results to the viewer, or we can assign the data to the browser directly ctx.body , and then returns as JSON.

class UserController extends Controller {
    async signin() {
        const { ctx } = this;
        const rule = {
            User name: {type: 'string', required: true, message: 'required'},
            Userpass: {type: 'string', required: true, message: 'required'},
        const signinMsg = ctx.request.body;
        await ctx.validate(rule, signinMsg);
        signinMsg.userPass = ctx.helper.encrypt(signinMsg.userPass);
        const result = await ctx.service.user.signin(signinMsg);
        ctx.body = result;

Service writing: used to write business logic layer, which can be reused. The processing of complex data, such as the information to be presented, needs to be obtained from the database, or the call of third-party services.

class UserService extends Service {
    //Update user information
    async updateUser(userMsg) {
        const { ctx } = this;
        const res = {};
        const result = await ctx.model.User.findByIdAndUpdate(userMsg._id, userMsg);
        res.code = 1;
        res.msg  ='user information changed'; = result;
        return res;

This is a simple node application structure, so it can be used Egg.js Responsible for interface services.