APIレスポンスで要素がnullや空の値をどう返すべきか?
If a property is optional or has an empty or null value, consider dropping the property from the JSON, unless there's a strong semantic reason for its existence.
code:styleguide.json
{
"volume": 10,
// Even though the "balance" property's value is zero, it should be left in,
// since "0" signifies "even balance" (the value could be "-1" for left
// balance and "+1" for right balance.
"balance": 0,
// The "currentlyPlaying" property can be left out since it is null.
// "currentlyPlaying": null
}
キーを消す場合に不便なケースがある
プロパティのキーが消える場合、普通あるプロパティの場合、APIのユーザーが扱いづらくなってしまう
もしキーがnullableでなければ、フロントのコードで次のようなループは合法である
code:ts
const vtubers = response.data.vtubers
...
{vtubers.map(vtuber => <li>${vtuber.name}</li>)}
一方、キーが消えるなら
code:ts
// null checkが必要になった
// 要素が増えるとその数だけこのチェックをかかないといけなくなる
const vtubers = !! response.data.vtubers ? response.data.vtubers : []
...
{vtubers.map(vtuber => <li>${vtuber.name}</li>)}
バックエンドの都合(APIのユーザーの都合より優先度は低い)
PHPのget_object_varsでプロパティを変換するという意味ではキーを消すほうが実装しやすい