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: add mock plugin #49

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
6 changes: 6 additions & 0 deletions farm.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { defineConfig } from '@farmfe/core';
import less from '@farmfe/js-plugin-less';
import postcss from '@farmfe/js-plugin-postcss';
import { theme } from 'antd';
import { viteMockServe } from 'vite-plugin-mock';
import Pages from 'vite-plugin-pages';
import { adminInfo, theme as themeConfig } from './global.config';

Expand All @@ -11,6 +12,7 @@ const globalToken = getDesignToken(themeConfig);

export default defineConfig({
compilation: {
minify: false,
resolve: {
alias: {
'@/': path.join(process.cwd(), 'src'),
Expand Down Expand Up @@ -49,5 +51,9 @@ export default defineConfig({
moduleId: '~react-pages',
importMode: 'async',
}),
viteMockServe({
mockPath: 'mock',
enable: true,
}),
],
});
104 changes: 104 additions & 0 deletions mock/user.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import type { MockMethod } from 'vite-plugin-mock';
import { getRequestToken, type requestParams, resultError, resultSuccess } from './utils';

export function createFakeUserList() {
return [
{
userId: '1',
username: 'farmer',
realName: 'Farm Admin',
avatar: '',
desc: 'manager',
password: '123456',
token: 'fakeToken1',
homePath: '/dashboard/analysis',
roles: [
{
roleName: 'Super Admin',
value: 'super',
},
],
},
];
}

const fakeCodeList = {
'1': ['1000', '3000', '5000'],

'2': ['2000', '4000', '6000'],
};
export default [
// mock user login
{
url: '/basic-api/login',
timeout: 200,
method: 'post',
response: ({ body }) => {
const { username, password } = body;
const checkUser = createFakeUserList().find((item) => item.username === username && password === item.password);
if (!checkUser) {
return resultError('Incorrect account or password!');
}
const { userId, username: _username, token, realName, desc, roles } = checkUser;
return resultSuccess({
roles,
userId,
username: _username,
token,
realName,
desc,
});
},
},
{
url: '/basic-api/getUserInfo',
method: 'get',
response: (request: requestParams) => {
const token = getRequestToken(request);
if (!token) return resultError('Invalid token');
const checkUser = createFakeUserList().find((item) => item.token === token);
if (!checkUser) {
return resultError('The corresponding user information was not obtained!');
}
return resultSuccess(checkUser);
},
},
{
url: '/basic-api/getPermCode',
timeout: 200,
method: 'get',
response: (request: requestParams) => {
const token = getRequestToken(request);
if (!token) return resultError('Invalid token');
const checkUser = createFakeUserList().find((item) => item.token === token);
if (!checkUser) {
return resultError('Invalid token!');
}
const codeList = fakeCodeList[checkUser.userId];

return resultSuccess(codeList);
},
},
{
url: '/basic-api/logout',
timeout: 200,
method: 'get',
response: (request: requestParams) => {
const token = getRequestToken(request);
if (!token) return resultError('Invalid token');
const checkUser = createFakeUserList().find((item) => item.token === token);
if (!checkUser) {
return resultError('Invalid token!');
}
return resultSuccess(undefined, { message: 'Token has been destroyed' });
},
},
{
url: '/basic-api/testRetry',
statusCode: 405,
method: 'get',
response: () => {
return resultError('Error!');
},
},
] as MockMethod[];
62 changes: 62 additions & 0 deletions mock/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
export enum ResultEnum {
SUCCESS = 0,
ERROR = -1,
TIMEOUT = 401,
TYPE = 'success',
}

export function resultSuccess<T>(result: T, { message = 'ok' } = {}) {
return {
code: ResultEnum.SUCCESS,
result,
message,
type: 'success',
};
}

// biome-ignore lint/suspicious/noExplicitAny: <explanation>
export function resultPageSuccess<T = any>(page: number, pageSize: number, list: T[], { message = 'ok' } = {}) {
const pageData = pagination(page, pageSize, list);

return {
...resultSuccess({
items: pageData,
total: list.length,
}),
message,
};
}

export function resultError(message = 'Request failed', { code = ResultEnum.ERROR, result = null } = {}) {
return {
code,
result,
message,
type: 'error',
};
}

// biome-ignore lint/suspicious/noExplicitAny: <explanation>
export function pagination<T = any>(pageNo: number, pageSize: number, array: T[]): T[] {
const offset = (pageNo - 1) * Number(pageSize);
return offset + Number(pageSize) >= array.length
? array.slice(offset, array.length)
: array.slice(offset, offset + Number(pageSize));
}

export interface requestParams {
method: string;
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
body: any;
headers?: { authorization?: string };
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
query: any;
}

/**
* @description 本函数用于从request数据中获取token,请根据项目的实际情况修改
*
*/
export function getRequestToken({ headers }: requestParams): string | undefined {
return headers?.authorization;
}
6 changes: 6 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@
"commitlint": "commitlint --edit"
},
"dependencies": {
"@arco-design/web-react": "^2.61.3",
"@arco-themes/react-juzi001": "^0.0.1",
"@tanstack/react-query": "^5.32.0",
"mockjs": "^1.1.0",
"@ant-design/icons": "^5.3.7",
"@ant-design/plots": "^2.2.2",
"antd": "^5.17.3",
Expand All @@ -37,6 +41,7 @@
"@farmfe/core": "^1.1.13",
"@farmfe/js-plugin-less": "^1.7.0",
"@farmfe/js-plugin-postcss": "^1.6.0",
"@tanstack/react-query-devtools": "^5.32.0",
"@farmfe/plugin-react": "^1.1.0",
"@jstors/farm-plugin-html-template": "^0.0.3",
"@types/react": "^18.3.2",
Expand All @@ -49,6 +54,7 @@
"postcss": "^8.4.38",
"react-refresh": "^0.14.2",
"tailwindcss": "^3.4.3",
"vite-plugin-mock": "^3.0.2",
"vite-plugin-pages": "^0.32.1"
},
"lint-staged": {
Expand Down
Loading
Loading