From 9aa37b32c3307dcb5896e1b768967666a6fdbf65 Mon Sep 17 00:00:00 2001
From: Eugen Rochko <eugen@zeonfederated.com>
Date: Mon, 1 Mar 2021 04:59:13 +0100
Subject: Add `details` to error response for `POST /api/v1/accounts` in REST
 API (#15803)

---
 app/lib/validation_error_formatter.rb | 32 ++++++++++++++++++++++++++++++++
 1 file changed, 32 insertions(+)
 create mode 100644 app/lib/validation_error_formatter.rb

(limited to 'app/lib')

diff --git a/app/lib/validation_error_formatter.rb b/app/lib/validation_error_formatter.rb
new file mode 100644
index 000000000..3f964f739
--- /dev/null
+++ b/app/lib/validation_error_formatter.rb
@@ -0,0 +1,32 @@
+# frozen_string_literal: true
+
+class ValidationErrorFormatter
+  def initialize(error, aliases = {})
+    @error   = error
+    @aliases = aliases
+  end
+
+  def as_json
+    { error: @error.to_s, details: details }
+  end
+
+  private
+
+  def details
+    h = {}
+
+    errors.details.each_pair do |attribute_name, attribute_errors|
+      messages = errors.messages[attribute_name]
+
+      h[@aliases[attribute_name] || attribute_name] = attribute_errors.map.with_index do |error, index|
+        { error: 'ERR_' + error[:error].to_s.upcase, description: messages[index] }
+      end
+    end
+
+    h
+  end
+
+  def errors
+    @errors ||= @error.record.errors
+  end
+end
-- 
cgit