??lazy-mock 是基于koa2構(gòu)建的,使用lowdb持久化數(shù)據(jù)到JSON文件。愛(ài)掏網(wǎng) - it200.com只需要簡(jiǎn)單的配置就可以實(shí)現(xiàn)和json-server差不多的功能,但是比json-server更加靈活,后期可配置性更強(qiáng),完全可以模擬真實(shí)后端業(yè)務(wù)邏輯。愛(ài)掏網(wǎng) - it200.com
??lazy-mock默認(rèn)包含了jwt實(shí)現(xiàn)的登錄與登出,實(shí)現(xiàn)了基于RBAC模型的通用權(quán)限控制邏輯。愛(ài)掏網(wǎng) - it200.com具體可查看vue-quasar-admin。愛(ài)掏網(wǎng) - it200.com
git clone https://github.com/wjkang/lazy-mock.git
復(fù)制代碼
npm install
復(fù)制代碼
npm run start
復(fù)制代碼
使用Postman模擬登錄功能
下面通過(guò)模擬圖書(shū)的增刪改查 介紹lazy-mock的簡(jiǎn)單使用
修改codeGenerate/config/config.js:
export default {
ApiServer:'http://localhost:3000',
ServerRootPath:'G:/GitHubProject/lazy-mock',
//server
RouteRelativePath:'/src/routes/',
ControllerRelativePath:'/src/controllers/',
ServiceRelativePath:'/src/services/',
ModelRelativePath:'/src/models/',
DBRelativePath:'/src/db/'
}
復(fù)制代碼
只需要修改ServerRootPath
為當(dāng)前項(xiàng)目的根目錄。愛(ài)掏網(wǎng) - it200.com
接著修改codeGenerate/config/model.js:
var shortid = require('shortid')
var Mock = require('mockjs')
var Random = Mock.Random
//必須包含字段id
export default {
name: "book",
Name: "Book",
properties: [
{
key: "id",
title: "id"
},
{
key: "name",
title: "書(shū)名"
},
{
key: "author",
title: "作者"
},
{
key: "press",
title: "出版社"
}
],
buildMockData: function () {//不需要生成設(shè)為false
let data = []
for (let i = 0; i 100; i++) {
data.push({
id: shortid.generate(),
name: Random.cword(5, 7),
author: Random.cname(),
press: Random.cword(5, 7)
})
}
return data
}
}
復(fù)制代碼
更多生成模擬數(shù)據(jù)的規(guī)則可看github.com/nuysoft/Moc…
生成代碼
確保之前npm run start
的窗口還開(kāi)著,打開(kāi)新的命令行窗口,執(zhí)行npm run code
復(fù)制src/routes/bookApiMap.txt某一行數(shù)據(jù)到Postman訪問(wèn)
get http://localhost:3000/book/get?id=
復(fù)制代碼
get http://localhost:3000/book/paged?pageIndex=&pageSize=&sortBy=&descending=&id=&name=&author=&press=
復(fù)制代碼
delete http://localhost:3000/book/del?id=
復(fù)制代碼
delete http://localhost:3000/book/batchdel?ids=[]
復(fù)制代碼
//不設(shè)置id則新增,否則為更新
post http://localhost:3000/book/save
{
"id":"",
"name":"",
"author":"",
"press":"",
}
復(fù)制代碼
請(qǐng)求頭記得加上Authorization:Bearer token
token之前模擬登錄獲取的
修改自動(dòng)生成的代碼格式
直接修改codeGenerate/serverTemplates 下文件
去掉接口需要授權(quán)訪問(wèn)的限制
去掉scr/app.js 里的.use(jwt({ secret: publicKey }).unless({ path: [/^\/public|\/auth\/login|\/assets/] }))
修改接口返回格式
修改src/lib/responseTemplate.js
修改路由
修改src/routes 下文件
添加更多業(yè)務(wù)邏輯
主要修改src/services下文件,具體可參考memuService.js
使用權(quán)限控制邏輯
前端參考vue-quasar-admin。愛(ài)掏網(wǎng) - it200.com實(shí)現(xiàn)了頁(yè)面(菜單),接口,元素級(jí)的權(quán)限控制。愛(ài)掏網(wǎng) - it200.com
后端在路由處加上權(quán)限控制的中間件,比如
.get('/function/pagedlist', PermissionCheck({ permission: ["function_view"], role: ["test"] }), controllers.function.getFunctionPagedList)
復(fù)制代碼
permission表明當(dāng)前登錄用戶必須具備數(shù)組里的任意一個(gè)權(quán)限碼,才能訪問(wèn)當(dāng)前接口。愛(ài)掏網(wǎng) - it200.com
role表明當(dāng)前登錄用戶必須具備數(shù)組里的任意一個(gè)角色碼,才能訪問(wèn)當(dāng)前接口
permission與role為或關(guān)系
原文發(fā)布時(shí)間為:2024年07月09日
本文作者:若邪
本文來(lái)源:掘金?如需轉(zhuǎn)載請(qǐng)聯(lián)系原作者