経緯
req.bodyを省略したい → オブジェクとの分割代入だ!!!
export const create = (req, res) => {
// ①新しいシフトを登録する
// 必要な項目が無い場合にエラーを返す(成功201、失敗400)
if(!req.body.shift_date){
res.status(400).send({
message: 'いつのシフトですか?'
});
return
}
if(!req.body.start_time){
res.status(400).send({
message: '何時から出勤ですか?'
});
return
}
if(!req.body.end_time){
res.status(400).send({
message: '何時まで出勤ですか?'
});
return
}
// 送られてきた情報を入れるオブジェクト
const newShift = {
"shift_date": req.body.shift_date,
"start_time": req.body.start_time,
"end_time": req.body.end_time,
"shift_memo": req.body.shift_memo
};
};
勘違いを生み出した画像
勘違い① 分割代入を特別な処理だと思っていた
自分の知識不足(忘れていた箇所)と勘違いを生み出した画像も合わさり、テンプレートリテラルの箇所含めたものが分割代入だと思っていた
勘違い② オブジェクトは自分で作成するものだと思っていた
オブジェクトを自分で作って(勘違い②)、
${}で囲い省略する(テンプレートリテラル)までが分割代入の型だと思っていた
※今回の箱はExpressが準備してくれるから必要ない
勘違い③ create関数がデータを持っていると思っていた
const { shift_date ...} = create;
ChatGPTにreq.bodyはcreate関数が持っている!と言われていた。なので、勘違いした画像のままコーディングしたら間違っていた
正解のコード
export const create = (req, res) => {
const { shift_date, start_time, end_time, shift_memo } = req.body;
if(!shift_date){
res.status(400).send({
message: 'いつのシフトですか?'
});
return
}
const newShift = {
shift_date,
start_time,
end_time,
shift_memo
};
};
