Rails API is growing in popularity, but from what I’ve seen there’s no easy way to auto-convert the snake_case of rails to the preferred camelCase of typical frontends (i.e. JS).
There’s ways to do it, but they all feel hacky. Serializers was almost the thing, but that struggled as well in baffling ways, also due to the snake_case conversion. Expressing relationships was painful. Heavier frameworks like JSON:API seemed to heavy-handed and required completely restructuring our frontend adapters as well.
This conversion seems like a super common use-case, and I’m so confused how it’s not something immediately configurable.
We’ve been left with rolling our own frontend “adapter” system to convert data the way we want for frontend to be able to read it.
Then we had other baffling side effects, like when we’re trying to POST to an endpoint that has more than one word.
params.require(:read_receipt).deep_transform_keys!(&:underscore)
.permit(:last_read_at)
If you make a POST request from the API, e.g.
axios.post('/frontend/read_receipts', { readReceipt: { lastReadAt: ... } })
It will shockingly create multiple nestings in the parameters, basically converting the params into something like { read_receipt: { readReceipt: { ... } } }
It took us a ton of time to figure out you could drop the explicit object naming on the frontend request, and then somehow weirdly it works out:
axios.post('/frontend/read_receipts', { lastReadAt: ... })
That was… a solid hour or two of WTF.
@Zee could also chime in with his own horror stories of this experience.
We’ve easily spent 20 hrs riffing on our adapter solution and it’s only just starting to come together, but it’s still frustrating and rough. Making something that expresses well with ActiveRecord but provides an encapsulation for frontend representation has been a breathtaking amount of work.
One could argue that there shouldn’t be an abstraction between Rails and the frontend, that if you just structure the data the way that’s expected by Rails we’re all hunky dory. That’s fair, and also I don’t think is realistic given the evolution of the frontend world.
… and we could at least start by making it easy to convert snake_case to camelCase and back.