VUE 动态处理axios BaseUrl
2020-02-25 本文已影响0人
fred_33c7
在调用axios与后端对接API的时候,可能后端的数据会存储在不同的数据库中。这时我们需要动态调用BaseURL来切换数据库。
假设:有 database1, database2.
api文件夹的架构如下:
repositories
│ Repository.js
│ RepositoryFactory.js
│ RepositoryInstance.js
│ userRepository.js
│ bookRepository.js
在 Repository.js
中,我们首先create a repository instance
import axios from "axios";
/// Creates a repository instance
export default function(urlPortion) {
if (!urlPortion) {
urlPortion = 'database1';
}
let baseURL = `http://example.com/${urlPortion}/`;
let instance = axios.create({
baseURL
});
instance.interceptors.response.use(
response => {
if (response.status === 200) {
return Promise.resolve(response);
} else {
return Promise.reject(response);
}
},
error => {
// 对请求错误做些什么
if (error && error.response) {
switch (error.response.status) {
case 400:
alert(error.response.data['info'])
break
}
}
}
)
return function (method, url, data = null) {
method = method.toLowerCase();
if (method === 'post') {
instance.headers = {
'Authorization': AUTH_TOKEN,
'content-type': 'application/json',
}
return instance.post(url, data)
} else if (method === 'get') {
return instance.get(url, {params: data})
} else if (method === 'delete') {
return instance.delete(url, {params: data})
} else if (method === 'put') {
return instance.put(url, data)
} else {
// eslint-disable-next-line no-mixed-spaces-and-tabs
console.error("unknow method" + method)
return false
}
}
}
在RepositoryInstance.js
中,我们构造一个repo类,后面所有的API都会从这里继承
export default class {
constructor(repo) {
this.repo = repo;
}
}
在userRepository.js
和bookRepository.js
中,我们具体对接后端API
import RepositoryInstance from '@/repositories/RepositoryInstance';
export default class extends RepositoryInstance {
getAllUserNames() {
return this.repo('get', 'all_data/AllUserNames')
}
getAllUserIDS() {
return this.repo('get', 'all_data/AllUserIDS')
}
}
最后,在RepositoryFactory.js
中,我们将所有的API抛出.
import Repository from './Repository';
import bookRepository from "./bookRepository"
import userRepository from "./userRepository"
export default function (dbTarget) {
const newRepo = new Repository(dbTarget);
return {
book: new bookRepository(newRepo),
user: new userRepository(newRepo)
};
}
这样就ok了。最后,在element中使用的时候,我们可以使用watch动态监听当前应该用什么数据库,从而动态改变BaseUrl.
import RepositoryFactory from "../../repositories/RepositoryFactory";
export default {
methods:{
getUsernames(){
RepositoryFactory(this.currentDatabase)['user'].getAllUserNames().then(res => {
this.usernames = res.data.usernames
})
}
}
}