Help us understand the problem. What is going on with this article?

frontend[react]、backend[rails]間でJSONのcasing(camelCase、snake_case)が異なる場合olive_branchが便利

問題

frontend -> backend

{
  "userId": "abcd1234"
}

camelCaseで送りたいし、受け取りたい

backend -> frontend

{
  user_id: "abcd1234"
}.to_json

snake_caseで受け取りたいし、送りたい

そこでolive_branch

https://github.com/vigetlabs/olive_branch

使用法

config/application.rb
...
...
# 全てはcamelCaseで来るのならここで指定[inflection]
# そうでなければClient側のリクエスト時にヘッダーで指定[Key-Inflection]
config.middleware.use OliveBranch::Middleware, inflection: "camel"

controller.rb
def create
  params[:user_id] # => ClientはuserIdで送ってるが、これで受け取れる

  render json: { user_id: "abcd1234" }.to_json # で送れば、Clientでは json.userId で取れる
end
Client.tsx
fetch("url", {
  method: "post",
  headers: {
    // OliveBranch側はContent-Type JSONを期待しているので、これがないと処理されない
    "Content-Type": "application/json; charset=utf-8",
    // 毎度指定が面倒なら config/application.rb で
    // config.middleware.use OliveBranch::Middleware, 
    //   content_type_check: -> (content_type) { true }
    // などとする
    // https://github.com/vigetlabs/olive_branch/issues/23
  },
  body: JSON.stringify({ userId }),
})
  .then((response) => response.json())
  .then(({userId}) => console.log(userId))
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away