問題
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))