ElMassimo / js_from_routes

๐Ÿ›ฃ๏ธ Generate path helpers and API methods from your Rails routes
https://js-from-routes.netlify.app/
MIT License
100 stars 7 forks source link

fix: serialize data before sending it to the backend #41

Closed mochetts closed 4 months ago

mochetts commented 10 months ago

Description ๐Ÿ“–

This pull request fixes the inertia client so that it serializes data, using deepConvertKeys(data, snakeCase) before sending it to the backend. This is the same behavior as the standard js_from_routes client.

Background ๐Ÿ“œ

This was happening because the data serialization / deserialization is completely missing for the inertia client. This causes a mismatch between the rails backend and the frontend as when submitting data to the rails app, it's expecting snake_case params but the inertia client is sending camelCase params.

image _Image: the expected param is tax_id in the backend, but the frontend is sending taxId_

The Fix ๐Ÿ”จ

By using the same convention as for the standard client, in which we have a Config object that takes a serializeData function that gets called before sending data to the backend, we can deepConvertKeys with snakeCase in order to send the right key casing to the backend.

Future Work ๐Ÿ”ฎ

It could be also good to implement the rest of the configuration options (e.g deserializeData, baseUrl, etc). I didn't implement the deserializeData because I'm using types_from_serializers which already sends the data in camelCase format to the frontend. So no need for deserialization.

mochetts commented 4 months ago

This can be better solved by adding a before_action hook in the rails application controller:

class ApplicationController < ActionController::Base

  before_action :deep_transform_params

  # Underscore params keys as they come camelized from the frontend
  def deep_transform_params
    params.merge!(params.to_unsafe_h.deep_transform_keys(&:underscore))
  end
end

This way we don't hijack the inertia transform that can only be used once (cannot stack transforms)