Created
April 22, 2019 14:41
-
-
Save rubenmoya/3ce9d9ca9f45440ffd2bf8cb4185f9c7 to your computer and use it in GitHub Desktop.
Rails middleware to convert request params and response data from camelCase to snake_case
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module CaseConverter | |
class Transformations | |
class << self | |
def transform(value) | |
case value | |
when Array then value.map { |item| transform(item) } | |
when Hash then value.deep_transform_keys! { |key| transform(key) } | |
when String then camelize(value) | |
else value | |
end | |
end | |
def camelize(string) | |
string.underscore.camelize(:lower) | |
end | |
def underscore_params(env) | |
req = ActionDispatch::Request.new(env) | |
req.request_parameters | |
req.query_parameters | |
env['action_dispatch.request.request_parameters'].deep_transform_keys!(&:underscore) | |
env['action_dispatch.request.query_parameters'].deep_transform_keys!(&:underscore) | |
end | |
end | |
end | |
class Middleware | |
def initialize(app) | |
@app = app | |
end | |
def call(env) # rubocop:disable Metrics/MethodLength | |
# Transform request | |
Transformations.underscore_params(env) | |
# Transform response | |
status, headers, response = @app.call(env) | |
new_responses = [] | |
response.each do |body| | |
begin | |
new_response = MultiJson.load(body) | |
rescue MultiJson::ParseError | |
new_responses << body | |
next | |
end | |
Transformations.transform(new_response) | |
new_responses << MultiJson.dump(new_response) | |
end | |
[status, headers, new_responses] | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment