1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
| const express = require('express'); const router = express.Router(); const {Web} = require('../../models') const {Op} = require("sequelize"); const {NotFoundError} = require("../../utils/errors"); const {success, failure} = require("../../utils/response");
router.get('/',async (req,res)=>{ try{ const {name} = req.query 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 } if(name){ condition.where = { name:{[Op.like]:`%${name}%`} } } const {rows, count} = await Web.findAndCountAll(condition) success(res,'站点列表查询成功',{ webs:rows, pagination:{ total:count, currentPage, pageSize } }) }catch(error){ failure(res,error) } })
router.get('/:id',async (req,res)=>{ try{ const web = await getDataById(req) success(res,'站点详情查询成功',web) }catch(error){ failure(res,error) } })
router.post('/',async (req,res)=>{ try{ const body = { ...getFilterBody(req), view:0 } const web = await Web.create(body) success(res,'创建站点成功',web,201) }catch(error){ failure(res,error) } })
router.delete('/:id',async (req,res)=>{ try{ const web = await getDataById(req) await web.destroy() success(res,'删除站点成功') }catch(error){ failure(res,error) } })
router.put('/:id',async (req,res)=>{ try{ const web = await getDataById(req) const body = getFilterBody(req) await web.update(body) success(res,'站点更新成功',web) }catch(error){ failure(res,error) } })
async function getDataById(req){ const {id} = req.params const data = await Web.findByPk(id) if(!data){ throw new NotFoundError(`未找到ID为:${id} 的站点`) } return data }
function getFilterBody(req){ const { href, name, webIcon, webCover, content, categoryId, github, blogHref } = req.body return{ href, name, webIcon, webCover, content, categoryId:Number(categoryId), github, blogHref } }
module.exports = router;
|