ValidationError.js 952 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. const { asArray } = require('../utils/objectUtils');
  2. const Type = {
  3. ModelValidation: 'ModelValidation',
  4. RelationExpression: 'RelationExpression',
  5. UnallowedRelation: 'UnallowedRelation',
  6. InvalidGraph: 'InvalidGraph'
  7. };
  8. class ValidationError extends Error {
  9. static get Type() {
  10. return Type;
  11. }
  12. constructor({ type, message, data = {}, statusCode = 400 }) {
  13. super(message || errorsToMessage(data));
  14. this.name = this.constructor.name;
  15. this.type = type;
  16. this.data = data;
  17. this.statusCode = statusCode;
  18. }
  19. }
  20. function errorsToMessage(data) {
  21. return Object.keys(data)
  22. .reduce((messages, key) => {
  23. messages.push(
  24. `${key}: ${asArray(data[key])
  25. .map(message)
  26. .join(', ')}`
  27. );
  28. return messages;
  29. }, [])
  30. .join(', ');
  31. }
  32. function message(it) {
  33. if (typeof it === 'string') {
  34. return it;
  35. } else {
  36. return it.message;
  37. }
  38. }
  39. module.exports = ValidationError;