请求规范
背景与问题
api种封装了很多接口,import导入的时候,需要逐一导入,但事实上,在一个vue文件中,我们需要导入多个方法,略显麻烦
api 文件名重复等问题
API文件的命名
Api文件必须导出对象必须以Api为结尾,如:employeeApi、noticeApi,方便查找
所有的文件要以api为结尾,比如 employee-api.js
、login-api.js
等等,那么对应java端的EmployeeController.java
、LoginController.java
;
好处:
- 很方便快速找到文件,比如在文件搜索中直接输入
login api
,有且找到唯一的一个对应文件 - 当看到文件时,知道这是一个接口 api 文件
- 避免和 状态管理 vuex或者路由router 中、异或常量中的
login.js
这类重名
需要导出一个API类对象
Api中以一个对象将方法包裹
- 我们只需要导入这一个api对象即可使用 所有的接口
- 以
Api
为结尾,这样我们在使用的时候,一眼就知道这个变量是api
接口
js
department-api.js文件
import { getRequest, postRequest } from '/@/lib/axios';
export const departmentApi = {
/**
* @description: 查询部门列表 @author 卓大
*/
queryAllDepartment: () => {
return getRequest('/department/listAll');
},
/**
* @description: 查询部门树形列表 @author 卓大
*/
queryDepartmentTree: () => {
return getRequest('/department/treeList');
},
/**
* @description: 添加部门 @author 卓大
*/
addDepartment: (param) => {
return postRequest('/department/add', param);
},
/**
* @description: 更新部门信息 @author 卓大
*/
updateDepartment: (param) => {
return postRequest('/department/update', param);
}
};
在department-form-modal.vue文件中使用:
import { departmentApi } from '/@/api/system/department-api';
async function save(param){
loading();
try{
if(condition){
await departmentApi.save(param);
}else{
await departmentApi.delete(param);
}
}catch(e){
sentry.log(e);
}finally{
unloading();
}
}
⚠️:反面写法
js
import { getRequest, postRequest } from '/@/lib/axios';
/**
* @description: 查询部门列表 @author 卓大
*/
export const queryAllDepartment: () => {
return getRequest('/department/listAll');
},
/**
* @description: 查询部门树形列表 @author 卓大
*/
export const queryDepartmentTree: () => {
return getRequest('/department/treeList');
},
/**
* @description: 添加部门 @author 卓大
*/
export const addDepartment: (param) => {
return postRequest('/department/add', param);
},
/**
* @description: 更新部门信息 @author 卓大
*/
export const updateDepartment: (param) => {
return postRequest('/department/update', param);
}
在department-form-modal.vue文件中使用:
import { save, delete } from '/@/api/system/department-api';
async function save(param){
loading();
try{
if(condition){
await save(param);
}else{
await delete(param);
}
}catch(e){
sentry.log(e);
}finally{
unloading();
}
}
import { save, delete } from '/@/api/system/department-api';
这行代码中,delete
是 js的一个关键字,会有可能冲突,第二个,如果页面简单,那么每次用这个接口,导入会变成import { save, delete,xxx, xxx, xxx, xxxx, xxxx, xxxx, } from '/@/api/system/department-api';
很长很长....
标注后端作者和接口地址
必须和后端 swagger 文档保持一致,同时保留后端作者和每个接口对应的地址
如下代码,写清楚了后端接口作者是谁?好处:
- 找接口问题的时候知道后端找谁
- 本身在后端swagger中就有接口作者,一举两得
js
import { getRequest, postRequest } from '/@/lib/axios';
export const departmentApi = {
/**
* @description: 查询部门列表
@author 卓大
*/
queryAllDepartment: () => {
return getRequest('/department/listAll');
},
/**
* @description: 查询部门树形列表 @author 卓大
*/
queryDepartmentTree: () => {
return getRequest('/department/treeList');
},
...
...
}