1.1.1 • Published 5 years ago

egg-fetch-middleware v1.1.1

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

egg-fetch-middleware

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

Install

$ npm i egg-fetch-middleware --save

Usage

// {app_root}/config/plugin.js
exports.fetchMiddleware = {
  enable: true,
  package: "egg-fetch-middleware"
};

Configuration

// {app_root}/config/config.default.js
exports.fetchMiddleware = {
  // The local and unittest environments are forced to be enabled. Other environments use this configuration to specify whether to display Error stack information when an error is thrown
  showStack: false,
};

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

Example

fetchMiddleware is a plugin for formatting and getting data interactions.

Once enabled in plugin.js, it can be handled directly in the controller or service via methods such as ctx.ok(data, {}). The following is test/fixtures/apps/fetch-middleware-test/app/controller/home.js (return ctx.ok(data, {}) in service)

'use strict';

const Controller = require('egg').Controller;

class HomeController extends Controller {
  async convertToNumber(ctx) {
    const id = ctx.helper.convertToNumber(ctx.params.id);
    ctx.body = ctx.ok(id, {});
  }

  async index(ctx) {
    ctx.body = ctx.ok('Format 2xx data', {});
  }

  async sendInternalServerError(ctx) {
    const err = new Error('Custom 5xx server internal error');
    ctx.body = ctx.serverError(err);
  }

  async notFound(ctx) {
    ctx.throwError(404, 'Custom 4xx server internal error');
  }

  // Recommended to use a value greater than or equal to 10000 to use as a business error code
  async doBusinessError(ctx) {
    // Note: If throwError is on the server side, ctx.AcceptJSON must be true.
		// can refer to https://eggjs.org/api/Request.html#acceptJSON
    ctx.throwError(10000, 'Example, using 10000 as a business error code');
  }

  // Not recommended, but some business scenario is written like this.  Handle the front end by business error
  async doThrow5xxError(ctx) {
    // Note: If throwError is on the server side, ctx.AcceptJSON must be true.
		// can refer to https://eggjs.org/api/Request.html#acceptJSON
    ctx.throwError(500, 'It is not recommended to use the http status code to handle business errors.');
  }
}

module.exports = HomeController;

Questions & Suggestions

Please open an issue here.

License

MIT

1.1.1

5 years ago

1.1.0

5 years ago

1.0.9

5 years ago

1.0.8

5 years ago

1.0.7

5 years ago

1.0.6

5 years ago

1.0.5

5 years ago

1.0.4

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago