1.1.62 • Published 6 years ago

egg-common-modules v1.1.62

Weekly downloads
2
License
MIT
Repository
github
Last release
6 years ago

egg-common-modules

NPM version build status Test coverage David deps Known Vulnerabilities npm download

Introduction

It includes middlewares, utils, basis for service/controller, etc.

Middlewares:
  1. errorHandler: It will handle all errors thrown from the application and convert to a common http response.
  2. retrieveCookie: It will retrieve the cookie from the request header and set it to field - cookie. e.g. const cookie = ctx.request.cookie;
Utils:
  1. sign: It includes md5 and suffix function.
  2. decorator function for egg-mysql transaction mode.
Exception:

This a common error type.Error { code: 1, msg: "通用错误" }

Basis:
  1. BasicService: It is a basic service for the application.
  2. BasicController: It is a basic controller for the application.

Install

$ npm i egg-common-modules --save

Usage

// {app_root}/config/plugin.js
exports.commonModules = {
    enable: true,
    package: 'egg-common-modules'
};

Configuration

// {app_root}/config/config.default.js
exports.commonModules = {};

see config/config.default.js for more detail.

Example

// {app_root}/config/config.default.js
exports.commonModules = {};

// {app_root}/app/controller/mainController.js
const { BasicController } = require('egg-common-modules').basis;

class mainController extends BasicController {
    async checkIfGotThePrize() {
        const { ctx } = this;
        const result = await ctx.service.mainService.checkIfGotThePrize();
        this.success(result);
    }
}

module.exports = mainController;

// {app_root}/app/service/mainService.js
const { BasicService } = require('egg-common-modules').basis;
const Exception = require('egg-common-modules').exception;

class mainService extends BasicService {
    async checkIfGotThePrize() {
        const result = await this.calPercentage();
        return result;
    }

    @transaction // this will make the database operations be in transaction mode
    async calPercentage() {
        const { ctx } = this;
        if (!ctx.userid) throw new Exception({ code: 1, msg: '未登录' });
        const user = await ctx.service.userService.getUser(ctx.userid);
        if (user.isPrime) {
            const rn = Math.random();
            if (rn > 0.5) return true;
        }
        return false;
    }
}

module.exports = mainService;

Questions & Suggestions

Please open an issue here.

Author

Chris

License

MIT