Guest User

Untitled

a guest
Nov 16th, 2018
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. const apiResponse = (payload = {}) => {
  2.  
  3. const DataSymbol = Symbol('data');
  4. const StatusSymbol = Symbol('status');
  5. const ErrorsSymbol = Symbol('errors');
  6. const MessageSymbol = Symbol('message');
  7.  
  8. class ApiResponse {
  9. constructor({ data = {}, status = 1, errors = [], message = '' }) {
  10. this.data = data;
  11. this.status = status;
  12. this.errors = errors;
  13. this.message = message;
  14. }
  15.  
  16. get data() {
  17. return this[DataSymbol];
  18. }
  19.  
  20. set data(data) {
  21. if (typeof data === 'undefined')
  22. throw new Error('Data must be defined');
  23. this[DataSymbol] = data;
  24. }
  25.  
  26. get status() {
  27. return this[StatusSymbol];
  28. }
  29.  
  30. set status(status) {
  31. if (isNaN(status) || (status !== 0 && status !== 1))
  32. throw new Error('Status must be a number, 1 is OK, 0 is BAD');
  33. this[StatusSymbol] = status;
  34. }
  35.  
  36. get errors() {
  37. return this[ErrorsSymbol];
  38. }
  39.  
  40. set errors(errors) {
  41. if (!Array.isArray(errors))
  42. throw new Error('Errors must be an array');
  43. this[ErrorsSymbol] = errors;
  44. }
  45.  
  46. get message() {
  47. return this[MessageSymbol];
  48. }
  49.  
  50. set message(message) {
  51. if (typeof message !== 'string')
  52. throw new Error('Message must be a string');
  53. this[MessageSymbol] = message;
  54. }
  55.  
  56. toJSON() {
  57. return {
  58. data: this.data,
  59. status: this.status,
  60. errors: this.errors.map(e => e.stack ? e.stack : e),
  61. message: this.message,
  62. }
  63. }
  64. }
  65.  
  66. return new ApiResponse(payload);
  67.  
  68. }
  69.  
  70. //Usage
  71. const todos = [{ ... }, { ... }]; // an array of todos
  72.  
  73. router.get('/todos', function(req, res, next){
  74. res.status(200);
  75. res.json(apiResponse({
  76. data: todos,
  77. message: 'You have a lot todo!',
  78. }));
  79. });
Add Comment
Please, Sign In to add comment