feat: request plugin 添加接口前缀

This commit is contained in:
bac-joker 2021-03-30 21:35:12 +08:00
parent 19108db7ce
commit 9a5b6eb075
5 changed files with 24 additions and 4 deletions

View File

@ -20,6 +20,7 @@
export default {
request: {
dataField: 'result',
base: '',
},
}
```
@ -32,6 +33,14 @@ export default {
`dataField` 对应接口统一格式中的数据字段,比如接口如果统一的规范是 `{ success: boolean, result: any}` ,那么就不需要配置,这样你通过 `useRequest` 消费的时候会生成一个默认的 `formatResult`,直接返回 `result` 中的数据,方便使用。如果你的后端接口不符合这个规范,可以自行配置 `dataField`。配置为 `''`(空字符串)的时候不做处理。
#### base
- 类型: `string`
- 默认值: `''`
- 详情:
`base` 接口前缀。
### 运行时配置
`app.js` 中进行运行时配置。

View File

@ -12,10 +12,14 @@ export default (api) => {
dataField: joi
.string()
.pattern(/^[a-zA-Z]*$/)
.allow(''),
base: joi
.string()
.allow('')
});
},
default: {
base: '',
dataField: ''
}
}
@ -26,11 +30,12 @@ export default (api) => {
const requestTemplate = readFileSync(join(__dirname, 'template', 'request.js'), 'utf-8');
api.onGenerateFiles(() => {
// 文件写出
const { dataField = '' } = api.config.request;
const { dataField = '', base = '' } = api.config.request;
api.writeTmpFile({
path: absoluteFilePath,
content: requestTemplate
.replace('REPLACE_DATA_FIELD', JSON.stringify(dataField))
.replace('REPLACE_BASE', base || '')
});
});

View File

@ -87,9 +87,15 @@ function getRequestInstance() {
};
}
function handleApiPathBase(url, options = {}) {
if (options.base) {
return `${options.base}${url}`;
}
return `REPLACE_BASE${url}`;
}
function userConfigHandler(url, data, options = {}) {
options.url = url;
options.url = handleApiPathBase(url, options);
options.method = (options.method || 'post').toUpperCase();
if (checkHttpRequestHasBody(options.method)) {
options.data = data;

View File

@ -7,9 +7,9 @@ export default {
// __VUE_OPTIONS_API__: true,
// __VUE_PROD_DEVTOOLS__: false
},
base: '/#/app/#',
publicPath: '/',
request: {
base: '/ras-mas',
dataField: ''
},
html: {

View File

@ -28,7 +28,7 @@ export default {
const clickIcon = () => {
console.log('click Icon');
};
const { loading, data } = useRequest('api');
const { loading, data } = useRequest('/api');
return {
loading,
data,