Guest User

Untitled

a guest
Apr 22nd, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. "use strict";
  2.  
  3. const Validator = use('Validator');
  4. const HTTP = use("App/HTTPResponse");
  5.  
  6. /**
  7. * Class model for basic operations
  8. *
  9. * @author gabriel
  10. * @class
  11. */
  12. class Operation {
  13. constructor() {
  14. this.errors = [];
  15. this.validator = Validator
  16. }
  17.  
  18. /**
  19. * Common rules
  20. *
  21. * @returns {{}}
  22. */
  23. get rules() {
  24. return {}
  25. }
  26.  
  27. async validate() {
  28. this.errors = [];
  29.  
  30. const validation = await this.validator.validate(this, this.rules);
  31.  
  32. if (validation.fails()) {
  33. validation.messages().map((err) => {
  34. this.addError(HTTP.STATUS_INTERNAL_SERVER_ERROR, err.message);
  35. });
  36.  
  37. return false
  38. }
  39.  
  40. return true;
  41. }
  42.  
  43. /**
  44. * Function for adding an error message to the array of errors
  45. *
  46. * @param code
  47. * @param message
  48. * @returns {Promise<void>}
  49. */
  50. async addError(code, message) {
  51. await this.errors.push({ code, message })
  52. }
  53.  
  54. /**
  55. * Gets the first error on the errors list
  56. *
  57. * @returns {Promise<*>}
  58. */
  59. getFirstError() {
  60. return this.errors[0]
  61. }
  62. }
  63.  
  64.  
  65. module.exports = Operation;
  66.  
  67. class InvoiceInfoOperation extends Operation {
  68. ...
  69. async store() {
  70. if (!this.validate()) {
  71. return false;
  72. }
  73. ...
  74. ...
  75.  
  76. async store({ request, response }) {
  77. const op = new InvoiceInfoOperation();
  78. op.invoiceId = request.input("invoiceId");
  79. op.invoiceAmount = request.input("invoiceAmount");
  80. op.paymentTarget = request.input("paymentTarget");
  81.  
  82. const store = await op.store();
  83.  
  84. if (!store) {
  85. const error = op.getFirstError();
  86. return await response.send(error.code);
  87. // return await response.send(error.code, error.message);
  88. // return response.status(error.status).send(error.message);
  89. }
  90.  
  91. return response.send(200);
  92. }
Add Comment
Please, Sign In to add comment