LoginSignup
1
0

More than 3 years have passed since last update.

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

Last updated at Posted at 2019-09-18

問題

frontend -> backend

{
  "userId": "abcd1234"
}

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

backend -> frontend

{
  user_id: "abcd1234"
}.to_json

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

そこで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))
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0