天天看點

eggjs 怎麼實作賬單詳情頁的編輯接口?

編輯接口實作

下圖我們可以看到,能修改的東西有支出還是收入,時間,賬單類型,備注,數量。

eggjs 怎麼實作賬單詳情頁的編輯接口?

1、控制層編寫 update 方法

擷取賬單詳情

async update () {
  const { ctx, app } = this;
  // 1、擷取請求中攜帶的參數
  const { id, amount, type_id, type_name, date, pay_type, remark = '' } = ctx.request.body;
  // 2、判空處理
  if (!id || !amount || !type_id || !type_name || !date || !pay_type) {
    ctx.body = {
      status: 400,
      desc: '參數錯誤',
      data: null
    }
    return;
  }
  console.log('1、擷取請求中攜帶的參數', {id, amount, type_id, type_name, date, pay_type, remark});
  try {
    // 3、拿到 token 擷取使用者資訊
    const token = ctx.request.header.authorization;
    const decode = await app.jwt.verify(token, app.config.jwt.secret);
    if (!decode) return;
    let user_id = decode.id;
    // 4、更新資料
    const result = await ctx.service.bill.update({
      id, // 賬單 id
      amount, // 金額
      type_id, // 消費類型 id
      type_name, // 消費類型名稱
      date, // 日期
      pay_type, // 消費類型
      remark, // 備注
      user_id // 使用者 id
    });
    console.log('4、更新資料', result);
    ctx.body = {
      status: 200,
      desc: '更新成功',
      data: null
    }
  } catch (error) {
    ctx.body = {
      status: 500,
      desc: '系統錯誤',
      data: null
    }
  }
}      

2、服務層編寫 update 方法

擷取賬單詳情資料

async update(params) {
  const { app } = this;
  try {
    const result = await app.mysql.update('bill', { ...params }, {
      where: {
        id: params.id,
        user_id: params.user_id
      }
    });
    return result;
  } catch (error) {
    console.log(error);
    return null;
  }
}      

3、路由配置

// 更新賬單資訊
router.get('/api/bill/update', verify_token, controller.bill.update);      

測試

我們輸入參數,不要忘記頭部 token。

我們修改 id 為1的資料,user_id 為 5.

eggjs 怎麼實作賬單詳情頁的編輯接口?

成功之後我們重新整理資料庫看看,發現已經更新成功

eggjs 怎麼實作賬單詳情頁的編輯接口?

繼續閱讀