You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现无name属性返回400不入库,有则返回201并入库

问题解决:未携带name时数据仍被添加至notes数组

你的核心问题是逻辑执行顺序颠倒,同时条件判断存在错误,导致未携带name属性时,数据已经被push进数组,之后才返回400响应。

原代码的问题点

  • 执行顺序错误:先执行notes.push(newNote)再做name校验,不管name是否存在,数据都已经被写入数组,校验仅返回响应但无法撤销数组修改。
  • 条件判断逻辑错误:name === undefined && name === null永远为false——一个变量不可能同时是undefined和null,应该用||来判断两种缺失情况。
  • 冗余判断:isSuccess的校验完全没必要,刚创建的note直接push进数组,必然存在于数组中。

修正后的代码

const addNoteHandler = (request, h) => {
    const { name, year, author, summary, publisher, pageCount, readPage, reading } = request.payload;

    // 先校验name是否存在/有效,不通过直接返回400
    if (name === undefined || name === null || name.trim() === '') {
        const response = h.response({
            status: 'fail',
            message: 'Gagal menambahkan buku, mohon isi nama buku',
        });
        response.code(400);
        return response;
    }

    // 校验通过后再创建数据并写入数组
    const id = nanoid(16);
    const createdAt = new Date().toISOString();
    const updatedAt = createdAt;
    const newNote = {
        name, year, author, summary, publisher, pageCount, readPage, reading, id, createdAt, updatedAt,
    };
    notes.push(newNote);    

    // 直接返回成功响应
    const response = h.response({
        status: 'success',
        message: 'Buku berhasil ditambahkan',
        data: {
            bookId: id,
        },
    });
    response.code(201);
    return response; 
};

关键改动说明

  1. 调整执行流程:把name校验放在最前面,不满足条件直接终止函数返回400,避免无效数据写入数组。
  2. 修正判断逻辑:用||替代&&,同时增加name.trim() === ''的判断(如果需求允许空字符串name,可移除该条件)。
  3. 移除冗余代码:删除无意义的isSuccess校验,简化流程。

内容的提问来源于stack exchange,提问作者itsadityo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 20:45:14