Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: 使用 mockm #4011

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ node_modules
.nvmrc
coverage
CODEOWNERS
.nitro
.output


Expand Down
1 change: 0 additions & 1 deletion apps/backend-mock/.env

This file was deleted.

1 change: 1 addition & 0 deletions apps/backend-mock/.eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/**/*
26 changes: 20 additions & 6 deletions apps/backend-mock/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,28 @@

## Description

Vben Admin 数据 mock 服务,没有对接任何的数据库,所有数据都是模拟的,用于前端开发时提供数据支持。由于 sqlite 安装需要在本地进行编译,所以这里接口是直接返回的。线上环境不再提供mock集成,可自行部署服务或者对接真实数据,同步 mock.js等工具有一些限制,比如上传文件不行、无法模拟复杂的逻辑等,所以这里使用了 真是的后端服务来实现。唯一麻烦的是本地需要同时启动后端服务和前端服务,但是这样可以更好的模拟真实环境。
Vben Admin 数据 mock 服务,没有对接任何的数据库,所有数据都是模拟的,用于前端开发时提供数据支持。无需安装数据实现基于 json 的类数据库存储。线上环境不再提供mock集成,可自行部署服务或者对接真实数据,避免在前端直接使用 mock.js 存在的一些限制,比如上传文件不行、无法模拟复杂的逻辑等,所以这里使用了真实的后端服务来实现。唯一麻烦的是本地需要同时启动后端服务和前端服务,但是这样可以更好的模拟真实环境。

文件说明如下:

```
./
- api/ -- 手动创建的 api
- httpData/ -- 请求记录, 一般不提交到版本库
- apiWeb.json -- 从 UI 界面上创建的接口数据
- util.js -- 一些公用方法
- mm.config.js -- mockm 的配置文件
```

## Running the app

```bash
# development
$ pnpm run start

# production mode
$ pnpm run build
$ pnpm i mockm
$ npx mm
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fix Markdownlint issues by removing dollar signs.

The dollar signs before the commands should be removed to comply with Markdownlint rules.

- $ pnpm i mockm
- $ npx mm
+ pnpm i mockm
+ npx mm
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
$ pnpm i mockm
$ npx mm
pnpm i mockm
npx mm
Tools
Markdownlint

21-21: null
Dollar signs used before commands without showing output

(MD014, commands-show-output)


22-22: null
Dollar signs used before commands without showing output

(MD014, commands-show-output)

```

## 参考

- [mockm 代码仓库](https://github.com/wll8/mockm/)
- [mockm 文档](https://hongqiye.com/doc/mockm/)
- [mockjs 文档](https://wll8.github.io/mockjs-examples/)
43 changes: 43 additions & 0 deletions apps/backend-mock/api/auth.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/* eslint-disable */

const {
wrapApiData,
useResponseSuccess,
useResponseError,
MOCK_USERS,
MOCK_CODES,
MOCK_MENUS,
} = require(`../util.cjs`)

/** @type {import('mockm/@types/config').Config} */
module.exports = util => {
const {
libObj: { mockjs },
} = util
return {
api: {
'/api/auth/codes'(req, res) {
const codes = MOCK_CODES.find((item) => item.username === req.username)?.codes ?? [];
res.json(useResponseSuccess(codes))
},
'post /api/auth/login'(req, res) {
const { password, username } = req.body;

const findUser = MOCK_USERS.find(
(item) => item.username === username && item.password === password,
);

if (!findUser) {
return res.status(403).json(useResponseError('UnauthorizedException', '用户名或密码错误'))
}

const accessToken = Buffer.from(username).toString('base64');
res.json(useResponseSuccess({
accessToken,
// TODO: refresh token
refreshToken: accessToken,
}));
Comment on lines +23 to +39
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reminder: Generate refresh token.

There is a TODO comment for generating a refresh token.

Do you want me to generate the code for generating a refresh token or open a GitHub issue to track this task?

},
},
}
}
15 changes: 0 additions & 15 deletions apps/backend-mock/api/auth/codes.ts

This file was deleted.

20 changes: 0 additions & 20 deletions apps/backend-mock/api/auth/login.post.ts

This file was deleted.

26 changes: 26 additions & 0 deletions apps/backend-mock/api/menu.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/* eslint-disable */

const {
wrapApiData,
useResponseSuccess,
useResponseError,
MOCK_USERS,
MOCK_CODES,
MOCK_MENUS,
} = require(`../util.cjs`)

/** @type {import('mockm/@types/config').Config} */
module.exports = util => {
const {
libObj: { mockjs },
} = util
return {
api: {
'/api/menu/all'(req, res){
const menus = MOCK_MENUS.find((item) => item.username === req.username)?.menus ?? [];
res.json(useResponseSuccess(menus))

},
},
}
}
14 changes: 0 additions & 14 deletions apps/backend-mock/api/menu/all.ts

This file was deleted.

5 changes: 0 additions & 5 deletions apps/backend-mock/api/status.ts

This file was deleted.

1 change: 0 additions & 1 deletion apps/backend-mock/api/test.get.ts

This file was deleted.

1 change: 0 additions & 1 deletion apps/backend-mock/api/test.post.ts

This file was deleted.

25 changes: 25 additions & 0 deletions apps/backend-mock/api/user.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
const {
wrapApiData,
useResponseSuccess,
useResponseError,
MOCK_USERS,
MOCK_CODES,
MOCK_MENUS,
} = require(`../util.cjs`)

/** @type {import('mockm/@types/config').Config} */
module.exports = util => {
const {
libObj: { mockjs },
} = util
return {
api: {
'/api/user/info'(req, res) {
const user = MOCK_USERS.find((item) => item.username === req.username);

const { password: _pwd, ...userInfo } = user;
res.json(useResponseSuccess(user))
},
},
}
}
14 changes: 0 additions & 14 deletions apps/backend-mock/api/user/info.ts

This file was deleted.

4 changes: 4 additions & 0 deletions apps/backend-mock/apiWeb.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"paths": {},
"disable": []
}
7 changes: 0 additions & 7 deletions apps/backend-mock/error.ts

This file was deleted.

19 changes: 19 additions & 0 deletions apps/backend-mock/get-user.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
module.exports = {
key: `get-user`,
main() {
return {
useCreated(app) {
app.use((req, res, next) => {
try {
const token = req.get(`Authorization`);
const username = Buffer.from(token, 'base64').toString('utf8');
req.username = username;
} catch {
// ...
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add logging for errors and improve error handling.

The current error handling is minimal and lacks logging. This can make debugging difficult.

-          } catch {
-            // ...
+          } catch (error) {
+            console.error('Error decoding Authorization header:', error);
+            res.status(400).send('Invalid Authorization header');
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try {
const token = req.get(`Authorization`);
const username = Buffer.from(token, 'base64').toString('utf8');
req.username = username;
} catch {
// ...
}
try {
const token = req.get(`Authorization`);
const username = Buffer.from(token, 'base64').toString('utf8');
req.username = username;
} catch (error) {
console.error('Error decoding Authorization header:', error);
res.status(400).send('Invalid Authorization header');

next();
});
},
};
},
};
6 changes: 6 additions & 0 deletions apps/backend-mock/httpData/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
openApiHistory/
request/
db.json
httpHistory.json
log.err.txt
store.json
4 changes: 4 additions & 0 deletions apps/backend-mock/httpData/apiWeb.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"paths": {},
"disable": []
}
14 changes: 0 additions & 14 deletions apps/backend-mock/middleware/1.api.ts

This file was deleted.

61 changes: 61 additions & 0 deletions apps/backend-mock/mm.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
const {
wrapApiData,
useResponseSuccess,
useResponseError,
} = require(`./util.cjs`)
const getUser = require(`./get-user.cjs`)

/**
* 配置说明请参考文档:
* https://hongqiye.com/doc/mockm/config/option.html
* @type {import('mockm/@types/config').Config}
*/
module.exports = util => {
return {
watch: [`./api/`],
plugin: [getUser],
proxy: {
'/': `http://www.httpbin.org/`, // 后端接口主域
},
api: {
'use /'(req, res, next){
const noCheckList = [
`/`,
`/public`,
`/favicon.ico`,
`/api/test`,
`/api/status`,
`/api/auth/login`,
]
if( req.path === `/` || noCheckList.some(item => {
return item.startsWith(req.path)
})) {
next()
} else {
const token = req.get(`Authorization`)
if (!token) {
return res.status(401).json(useResponseError('UnauthorizedException', 'Unauthorized Exception'))
}
next()
}
wll8 marked this conversation as resolved.
Show resolved Hide resolved
},
// 跳转到接口列表
'/api'(req, res){
const url = `http://127.0.0.1:${globalThis.config.testPort}/#/apiStudio`
res.redirect(url)
},
...require(`./api/auth.cjs`)(util).api,
...require(`./api/menu.cjs`)(util).api,
...require(`./api/user.cjs`)(util).api,
'/api/status'(req, res) {
const { status } = req.query
res.status(status).json(useResponseError())
},
'get /api/test': `Test get handler`,
'post /api/test': `Test post handler`,
},
static: [],
resHandleReplay: ({req, res}) => useResponseSuccess({}),
resHandleJsonApi: ({req, res: {statusCode: code}, data}) => wrapApiData({code, data}),
}
}
18 changes: 0 additions & 18 deletions apps/backend-mock/nitro.config.ts

This file was deleted.

8 changes: 4 additions & 4 deletions apps/backend-mock/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
"private": true,
"license": "MIT",
"author": "",
"type": "commonjs",
"scripts": {
"start": "nitro dev",
"build": "nitro build"
"mm": "npx mockm"
},
"dependencies": {
"nitropack": "^2.9.7"
"devDependencies": {
"mockm": "1.1.27-alpha.2"
}
}
12 changes: 0 additions & 12 deletions apps/backend-mock/routes/[...].ts

This file was deleted.

4 changes: 0 additions & 4 deletions apps/backend-mock/tsconfig.build.json

This file was deleted.

Loading