通過前面的建表,我們可以找到對應的字段如下圖:
實作賬單新增接口
1、在控制層建立bill.js
'use strict';
const Controller = require('egg').Controller;
class BillController extends Controller {
async add() {
const { ctx, app } = this;
// 1、擷取請求中攜帶的參數
const { amount, type_id, type_name, date, pay_type, remark = '' } = ctx.request.body;
// 2、判空處理
if (!amount || !type_id || !type_name || !date || !pay_type) {
ctx.body = {
status: 400,
desc: '參數錯誤',
data: null
}
return;
}
try {
// 3、拿到 token 擷取使用者資訊
const token = ctx.request.header.authorization;
const decode = await app.jwt.verify(token, app.config.jwt.secret);
if (!decode) return;
// user_id 預設添加到每個賬單項,用于濾出
let user_id = decode.id
const result = await ctx.service.bill.add({
amount,
type_id,
type_name,
date,
pay_type,
remark,
user_id
});
ctx.body = {
status: 200,
desc: '請求成功',
data: null
}
} catch (error) {
ctx.body = {
status: 500,
desc: '系統錯誤',
data: null
}
}
}
}
module.exports = BillController;
2、在服務層添加bill.js
'use strict';
const Service = require('egg').Service;
class BillService extends Service {
async add(params) {
const { app } = this;
try {
// 往 bill 表中,插入一條賬單資料
const result = await app.mysql.insert('bill', params);
return result;
} catch (error) {
console.log(error);
return null;
}
}
}
module.exports = BillService;
3、添加路由
// 添加賬單
router.post('/api/bill/add', verify_token, controller.bill.add);
測試新增賬單接口
上面我們已經寫好了新增的邏輯,接下來我們用 apifox 測試一下:
1、先在 apifox 建立接口
點選建立接口之後,填寫好相關資訊
2、添加參數測試
我們先登入拿到token
然後填寫需要的參數,記得把請求改成post,不然會報錯