1.0.0 • Published 6 years ago

express-addon-response v1.0.0

Weekly downloads
2
License
ISC
Repository
gitlab
Last release
6 years ago

express-addon-response

express middleware, add some methods to response object of express.

Usage

npm i express-addon-response
const express = require('express');
const addonResponse = require('express-addon-response');
const app = express();
app.use(addonResponse);

// now you can use res.ok(), res.invalid()....

Source code

const response = { success: false };

const codeMap = {
  400: 'Bad Request',
  401: 'Unauthorized',
  403: 'Forbidden',
  404: 'Not Found',
  500: 'Internal Server Error'
};

module.exports = (req, res, next) => {
  const send = (code, msg) => {
    res.status(code).json(Object.assign({}, response, { msg, code, text: codeMap[code] }));
  };

  res.ok = (body) => {
    if (!body) {
      res.json({ success: true});
    } else {
      res.json({ success: true, data: body });
    }
  };

  res.invalid = (msg) => send(400, msg);

  res.unAuth = (msg) => send(401, msg);

  res.forbidden = (msg) => send(403, msg);

  res.notFound = (msg) => send(404, msg);

  res.error = (msg) => send(500, msg);

  next();
};