const express = require('express');
const router = express.Router();
const { Op } = require('sequelize');
const { NotFoundError, successRes, failureRes } = require('../../utils/responseHandler');
const { Article: CurrentTableClass } = require("../../models");
// 白名單字段
function filterBody(req) {
const { title, content } = req.body;
return { title, content };
}
// 當(dāng)前實(shí)體
async function getItem(req) {
const { id } = req.params;
const item = await CurrentTableClass.findByPk(id)
if (!item) {
throw new NotFoundError("文章不存在")
}
return item
}
// 獲取列表
router.get('/', async function (req, res, next) {
try {
const currentPage = Math.abs(Number(req.query.currentPage)) || 1;
const pageSize = Math.abs(Number(req.query.pageSize)) || 10;
const offset = (currentPage - 1) * pageSize
const condition = {
order: [['id', "DESC"]],
limit: pageSize,
offset: offset
}
const { title } = req.query
if (title) {
condition["where"] = {
title: {
[Op.like]: `%${title}%`
}
}
}
const { count, rows } = await CurrentTableClass.findAndCountAll(condition);
successRes(res, "查詢列表成功圆雁。", {
data: rows,
pagination: {
count,
currentPage,
pageSize
}
})
} catch (error) {
failureRes(res, error)
}
});
// 新增實(shí)體
router.post('/', async function (req, res, next) {
try {
const fb = filterBody(req)
const item = await CurrentTableClass.create(fb);
successRes(res, "創(chuàng)建成功梢褐。", { item })
} catch (error) {
failureRes(res, error)
}
});
// 獲取實(shí)體
router.get('/:id', async function (req, res, next) {
try {
const item = await getItem(req)
successRes(res, "查詢詳情成功气堕。", { item })
} catch (error) {
failureRes(res, error)
}
});
// 編輯實(shí)體
router.post('/:id/edit', async function (req, res, next) {
try {
const item = await getItem(req)
const fb = filterBody(req)
await item.update(fb)
successRes(res, "編輯成功拆挥。", {
item
})
} catch (error) {
failureRes(res, error)
}
});
// 刪除實(shí)體
router.post('/:id/delete', async function (req, res, next) {
try {
const item = await getItem(req)
await item.destroy();
successRes(res, "刪除成功。")
} catch (error) {
failureRes(res, error)
}
});
module.exports = router;
const { Article: CurrentTableClass } = require("../../models");
// 修改為
const { Category: CurrentTableClass } = require("../../models");