Improve the response in the snippet create/update API endpoints
Reviewing another issue, I realized that the responses returned by the update and create are wrong or not accurate enough. For example in the update endpoint we have:
if snippet.persisted?
present snippet, with: Entities::PersonalSnippet
else
render_validation_error!(snippet)
end
Even if the snippet has a validation error, snippet.persisted?
will always be true, which means that we're not returning any error at all. Besides, now that we also commit things to the snippet repository we cannot rely only on validation errors. We need to check the ServiceResponse
we get from the service.
My proposal for the update and create endpoints would be something like:
diff --git a/lib/api/snippets.rb b/lib/api/snippets.rb
index 0aaab9a812f..ed40f928014 100644
--- a/lib/api/snippets.rb
+++ b/lib/api/snippets.rb
@@ -78,14 +78,14 @@ module API
attrs = declared_params(include_missing: false).merge(request: request, api: true)
service_response = ::Snippets::CreateService.new(nil, current_user, attrs).execute
- snippet = service_response.payload[:snippet]
- render_spam_error! if snippet.spam?
+ if service_response.success?
+ snippet = service_response.payload[:snippet]
- if snippet.persisted?
+ render_spam_error! if snippet.spam?
present snippet, with: Entities::PersonalSnippet
else
- render_validation_error!(snippet)
+ render_api_error!({ error: service_response.message }, service_response.http_status)
end
end
@@ -112,14 +112,15 @@ module API
attrs = declared_params(include_missing: false).merge(request: request, api: true)
service_response = ::Snippets::UpdateService.new(nil, current_user, attrs).execute(snippet)
- snippet = service_response.payload[:snippet]
- render_spam_error! if snippet.spam?
+ if service_response.success?
+ snippet = service_response.payload[:snippet]
+
+ render_spam_error! if snippet.spam?
- if snippet.persisted?
present snippet, with: Entities::PersonalSnippet
else
- render_validation_error!(snippet)
+ render_api_error!({ error: service_response.message }, service_response.http_status)
end
end
I'm not totally sure about the render_spam_error!
when success?
, we have to check that.
We also need to update the project snippet create/update endpoints as well.
/cc @dsatcher