Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Camelcase keys? #286

Closed
ahmadabdelhalim opened this issue Oct 6, 2020 · 3 comments
Closed

Camelcase keys? #286

ahmadabdelhalim opened this issue Oct 6, 2020 · 3 comments

Comments

@ahmadabdelhalim
Copy link

I understand that you use jsonapi-rb under the hood for serialization, so I wanted to know how can I use graphiti to camelcase keys using it?

@Reizar
Copy link

Reizar commented Oct 21, 2020

This is what I used, found when digging into some past issues in the repo.

In application_resource.rb

class CustomSerializer < Graphiti::Serializer
  extend JSONAPI::Serializable::Resource::KeyFormat
  key_format -> (key) { key.to_s.camelize(:lower) }
end

class ApplicationResource < Graphiti::Resource
# .... Other code in here
self.serializer = CustomSerializer
end

This will transform all outgoing response keys to camelCase. If you also want incoming params to be converted from camelCase to snake_case, add a initializer with this:

# Transform JSON request param keys from JSON-conventional camelCase to
# Rails-conventional snake_case:

transformer = lambda { |raw_post|
  # Modified from action_dispatch/http/parameters.rb
  data = ActiveSupport::JSON.decode(raw_post)

  # Transform camelCase param keys to snake_case
  if data.is_a?(Array)
    data.map { |item| item.deep_transform_keys!(&:underscore) }
  else
    data.deep_transform_keys!(&:underscore)
  end

  # Return data
  data.is_a?(Hash) ? data : { '_json': data }
}

ActionDispatch::Request.parameter_parsers[:json] = transformer
ActionDispatch::Request.parameter_parsers[:jsonapi] = transformer

( I have it set for both json and jsonapi requests )

Hope this helps.

@ahmadabdelhalim
Copy link
Author

@Reizar That's a very nice solution. Thank you!

@nbarthel
Copy link

I used this approach, but had a problem with disappearing includes and relationships. I'll try and reproduce as time permits.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants