response.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. const toArrayIfNot = require('../../../lib/util/toArrayIfNot');
  2. const ErrorV3 = require('../../models/vo/error-apiv3');
  3. const addCustomFunctionToResponse = (express, crowi) => {
  4. express.response.apiv3 = function(obj = {}, status = 200) { // not arrow function
  5. // obj must be object
  6. if (typeof obj !== 'object' || obj instanceof Array) {
  7. throw new Error('invalid value supplied to res.apiv3');
  8. }
  9. this.status(status).json({ data: obj });
  10. };
  11. express.response.apiv3Err = function(_err, status = 400, info) { // not arrow function
  12. if (!Number.isInteger(status)) {
  13. throw new Error('invalid status supplied to res.apiv3Err');
  14. }
  15. let errors = toArrayIfNot(_err);
  16. errors = errors.map((e) => {
  17. if (e instanceof ErrorV3) {
  18. return e;
  19. }
  20. if (e instanceof Error) {
  21. return new ErrorV3(e.message, null, e.stack);
  22. }
  23. if (typeof e === 'string') {
  24. return { message: e };
  25. }
  26. throw new Error('invalid error supplied to res.apiv3Err');
  27. });
  28. this.status(status).json({ errors, info });
  29. };
  30. };
  31. module.exports = addCustomFunctionToResponse;