rewrite axios && mock data

This commit is contained in:
Pan 2017-05-15 17:56:45 +08:00
parent 1d05d661bc
commit 5aa22731c8
17 changed files with 137 additions and 204 deletions

View File

@ -1,4 +1,4 @@
import { fetch } from 'utils/fetch'; import fetch from 'utils/fetch';
export function getList() { export function getList() {
return fetch({ return fetch({

View File

@ -1,4 +1,4 @@
import { fetch } from 'utils/fetch'; import fetch from 'utils/fetch';
export function fetchList(query) { export function fetchList(query) {
return fetch({ return fetch({

View File

@ -1,4 +1,4 @@
import { fetch } from 'utils/fetch'; import fetch from 'utils/fetch';
export function loginByEmail(email, password) { export function loginByEmail(email, password) {
const data = { const data = {
@ -19,7 +19,6 @@ export function logout() {
}); });
} }
export function getInfo(token) { export function getInfo(token) {
return fetch({ return fetch({
url: '/user/info', url: '/user/info',

View File

@ -1,28 +1,28 @@
import fetch, { tpFetch } from 'utils/fetch'; // import fetch, { tpFetch } from 'utils/fetch';
export function getToken() { // export function getToken() {
return fetch({ // return fetch({
url: '/qiniu/upload/token', // url: '/qiniu/upload/token',
method: 'get' // method: 'get'
}); // });
} // }
export function upload(data) { // export function upload(data) {
return tpFetch({ // return tpFetch({
url: 'https://upload.qbox.me', // url: 'https://upload.qbox.me',
method: 'post', // method: 'post',
data // data
}); // });
} // }
/* 外部uri转七牛uri*/ // /* 外部uri转七牛uri*/
export function netUpload(token, net_url) { // export function netUpload(token, net_url) {
const imgData = { // const imgData = {
net_url // net_url
}; // };
return fetch({ // return fetch({
url: '/qiniu/upload/net/async', // url: '/qiniu/upload/net/async',
method: 'post', // method: 'post',
data: imgData // data: imgData
}); // });
} // }

View File

@ -1,4 +1,4 @@
import { fetch } from 'utils/fetch'; import fetch from 'utils/fetch';
export function userSearch(name) { export function userSearch(name) {
return fetch({ return fetch({

View File

@ -17,17 +17,8 @@ for (let i = 0; i < count; i++) {
} }
export default { export default {
getList: () => new Promise(resolve => { getList: () => List,
setTimeout(() => { getArticle: () => ({
resolve([200, {
data: List
}]);
}, 100);
}),
getArticle: () => new Promise(resolve => {
setTimeout(() => {
resolve([200, {
data: {
id: 120000000001, id: 120000000001,
author: { key: 'mockPan' }, author: { key: 'mockPan' },
source_name: '原创作者', source_name: '原创作者',
@ -42,8 +33,5 @@ export default {
status: 'published', status: 'published',
tags: [], tags: [],
title: '' title: ''
}
}]);
}, 100);
}) })
}; };

View File

@ -1,5 +1,5 @@
import Mock from 'mockjs'; import Mock from 'mockjs';
import { param2Obj } from 'utils';
const List = []; const List = [];
const count = 100; const count = 100;
@ -21,9 +21,9 @@ for (let i = 0; i < count; i++) {
export default { export default {
getList: config => { getList: config => {
const { importance, type, title, page, limit, sort } = config.params; const { importance, type, title, page, limit, sort } = param2Obj(config.url);
let mockList = List.filter(item => { let mockList = List.filter(item => {
if (importance && item.importance !== importance) return false; if (importance && item.importance !== +importance) return false;
if (type && item.type !== type) return false; if (type && item.type !== type) return false;
if (title && item.title.indexOf(title) < 0) return false; if (title && item.title.indexOf(title) < 0) return false;
return true; return true;
@ -33,21 +33,12 @@ export default {
} }
const pageList = mockList.filter((item, index) => index < limit * page && index >= limit * (page - 1)); const pageList = mockList.filter((item, index) => index < limit * page && index >= limit * (page - 1));
return {
return new Promise(resolve => {
setTimeout(() => {
resolve([200, {
total: mockList.length, total: mockList.length,
items: pageList items: pageList
}]); }
}, 100);
})
}, },
getPv: () => new Promise(resolve => { getPv: () => ({
setTimeout(() => {
resolve([200, {
pvData: [{ key: 'PC网站', pv: 1024 }, { key: 'mobile网站', pv: 1024 }, { key: 'ios', pv: 1024 }, { key: 'android', pv: 1024 }] pvData: [{ key: 'PC网站', pv: 1024 }, { key: 'mobile网站', pv: 1024 }, { key: 'ios', pv: 1024 }, { key: 'android', pv: 1024 }]
}]);
}, 100);
}) })
}; };

View File

@ -1,27 +1,25 @@
import axios from 'axios'; import Mock from 'mockjs';
import MockAdapter from 'axios-mock-adapter';
import loginAPI from './login'; import loginAPI from './login';
import articleAPI from './article'; import articleAPI from './article';
import article_tableAPI from './article_table'; import article_tableAPI from './article_table';
import remoteSearchAPI from './remoteSearch'; import remoteSearchAPI from './remoteSearch';
const mock = new MockAdapter(axios);
// 登录相关 // 登录相关
mock.onPost('/login/loginbyemail').reply(loginAPI.loginByEmail); Mock.mock(/\/login\/loginbyemail/, 'post', loginAPI.loginByEmail);
mock.onPost('/login/logout').reply(loginAPI.logout); Mock.mock(/\/login\/logout/, 'post', loginAPI.logout);
mock.onGet('/user/info').reply(loginAPI.getInfo); Mock.mock(/\/user\/info\.*/, 'get', loginAPI.getInfo)
// 文章相关 // // 文章相关
mock.onGet('/article/list').reply(articleAPI.getList); Mock.mock(/\/article\/list/, 'get', articleAPI.getList);
mock.onGet('/article/detail').reply(articleAPI.getArticle); Mock.mock(/\/article\/detail/, 'get', articleAPI.getArticle);
// table example相关 // // table example相关
mock.onGet('/article_table/list').reply(article_tableAPI.getList); Mock.mock(/\/article_table\/list/, 'get', article_tableAPI.getList);
mock.onGet('/article_table/pv').reply(article_tableAPI.getPv); Mock.mock(/\/article_table\/p/, 'get', article_tableAPI.getPv);
// 搜索相关 // // 搜索相关
mock.onGet('/search/user').reply(remoteSearchAPI.searchUser); Mock.mock(/\/search\/user/, 'get', remoteSearchAPI.searchUser);
mock.onAny().passThrough();
export default mock; export default Mock;

View File

@ -1,3 +1,5 @@
import { param2Obj } from 'utils';
const userMap = { const userMap = {
admin: { admin: {
role: ['admin'], role: ['admin'],
@ -28,36 +30,17 @@ const userMap = {
export default { export default {
loginByEmail: config => { loginByEmail: config => {
const { email } = JSON.parse(config.data); console.log(config)
return new Promise((resolve, reject) => { const { email } = JSON.parse(config.body);
if (userMap[email.split('@')[0]]) { return userMap[email.split('@')[0]];
setTimeout(() => {
resolve([200, {
data: userMap[email.split('@')[0]]
}]);
}, 500);
} else {
reject('账号不正确')
}
})
}, },
getInfo: config => { getInfo: config => {
const { token } = config.params; const { token } = param2Obj(config.url);
return new Promise((resolve, reject) => {
if (userMap[token]) { if (userMap[token]) {
setTimeout(() => { return userMap[token];
resolve([200, {
data: userMap[token]
}]);
}, 100);
} else { } else {
reject('获取失败') return Promise.reject('a');
} }
})
}, },
logout: () => new Promise(resolve => { logout: () => 'success'
setTimeout(() => {
resolve([200, { data: 'success' }]);
}, 100);
})
}; };

View File

@ -1,4 +1,5 @@
import Mock from 'mockjs'; import Mock from 'mockjs';
import { param2Obj } from 'utils';
const NameList = []; const NameList = [];
const count = 100; const count = 100;
@ -12,18 +13,12 @@ NameList.push({ name: 'mockPan' })
export default { export default {
searchUser: config => { searchUser: config => {
const { name } = config.params; const { name } = param2Obj(config.url);
const mockNameList = NameList.filter(item => { const mockNameList = NameList.filter(item => {
const lowerCaseName = item.name.toLowerCase() const lowerCaseName = item.name.toLowerCase()
if (name && lowerCaseName.indexOf(name.toLowerCase()) < 0) return false; if (name && lowerCaseName.indexOf(name.toLowerCase()) < 0) return false;
return true; return true;
}); });
return new Promise(resolve => { return { items: mockNameList }
setTimeout(() => {
resolve([200, {
items: mockNameList
}]);
}, 100);
})
} }
}; };

View File

@ -3,25 +3,32 @@ import { Message } from 'element-ui';
import store from '../store'; import store from '../store';
import router from '../router'; import router from '../router';
export default function _fetch(options) {
return new Promise((resolve, reject) => { const service = axios.create({
const instance = axios.create({ baseURL: process.env.BASE_API
baseURL: process.env.BASE_API,
// timeout: 2000,
headers: { 'X-Ivanka-Token': store.getters.token }
}); });
instance(options)
.then(response => { service.interceptors.request.use(config => {
const res = response.data; // Do something before request is sent
if (res.code !== 20000) { if (store.state.token) {
console.log(options); // for debug config.headers.Token = store.state.token;
Message({ }
message: res.message, return config;
type: 'error', }, error => {
duration: 5 * 1000 // Do something with request error
}); console.log(error); // for debug
// 50014:Token 过期了 50012:其他客户端登录了 50008:非法的token Promise.reject(error);
if (res.code === 50008 || res.code === 50014 || res.code === 50012) { })
service.interceptors.response.use(
response => {
console.log(response)
return response;
},
error => {
console.log('err' + error);// for debug
const code = error.response.data;
if (code === 50008 || code === 50014 || code === 50012) {
Message({ Message({
message: res.message, message: res.message,
type: 'error', type: 'error',
@ -32,40 +39,8 @@ export default function _fetch(options) {
router.push({ path: '/login' }) router.push({ path: '/login' })
}); });
} }
reject(res); return Promise.reject(error);
}
resolve(res);
})
.catch(error => {
Message({
message: '发生异常错误,请刷新页面重试,或联系程序员',
type: 'error',
duration: 5 * 1000
});
console.log(error); // for debug
reject(error);
});
});
} }
)
export function fetch(options) { export default service;
return new Promise((resolve, reject) => {
const instance = axios.create({
timeout: 2000 // 超时
});
instance(options)
.then(response => {
const res = response.data;
resolve(res);
})
.catch(error => {
Message({
message: error,
type: 'error',
duration: 5 * 1000
});
console.log(error); // for debug
reject(error);
});
});
}

View File

@ -110,6 +110,11 @@
})).join('&'); })).join('&');
} }
export function param2Obj(url) {
const search = url.split('?')[1];
return JSON.parse('{"' + decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}')
}
export function html2Text(val) { export function html2Text(val) {
const div = document.createElement('div'); const div = document.createElement('div');
div.innerHTML = val; div.innerHTML = val;

View File

@ -96,8 +96,8 @@
getList() { getList() {
this.listLoading = true; this.listLoading = true;
fetchList(this.listQuery).then(response => { fetchList(this.listQuery).then(response => {
this.list = response.items; this.list = response.data.items;
this.total = response.total; this.total = response.data.total;
this.listLoading = false; this.listLoading = false;
this.olderList = this.list.map(v => v.id); this.olderList = this.list.map(v => v.id);
this.newList = this.olderList.slice(); this.newList = this.olderList.slice();
@ -124,6 +124,7 @@
.drag-handler{ .drag-handler{
width: 30px; width: 30px;
height: 30px; height: 30px;
cursor: pointer;
} }
.show-d{ .show-d{
margin-top: 15px; margin-top: 15px;

View File

@ -237,9 +237,9 @@
}, },
getRemoteUserList(query) { getRemoteUserList(query) {
userSearch(query).then(response => { userSearch(query).then(response => {
if (!response.items) return; if (!response.data.items) return;
console.log(response) console.log(response)
this.userLIstOptions = response.items.map(v => ({ this.userLIstOptions = response.data.items.map(v => ({
key: v.name key: v.name
})); }));
}) })

View File

@ -59,7 +59,6 @@
data() { data() {
return { return {
list: null, list: null,
total: null,
listLoading: true, listLoading: true,
listQuery: { listQuery: {
page: 1, page: 1,
@ -84,11 +83,10 @@
getList() { getList() {
this.listLoading = true; this.listLoading = true;
fetchList(this.listQuery).then(response => { fetchList(this.listQuery).then(response => {
this.list = response.items.map(v => { this.list = response.data.items.map(v => {
v.edit = false; v.edit = false;
return v return v
}); });
this.total = response.total;
this.listLoading = false; this.listLoading = false;
}) })
} }

View File

@ -227,8 +227,8 @@
getList() { getList() {
this.listLoading = true; this.listLoading = true;
fetchList(this.listQuery).then(response => { fetchList(this.listQuery).then(response => {
this.list = response.items; this.list = response.data.items;
this.total = response.total; this.total = response.data.total;
this.listLoading = false; this.listLoading = false;
}) })
}, },

View File

@ -24,7 +24,7 @@
watch: { watch: {
role(val) { role(val) {
this.$store.commit('SET_ROLES', [val]); this.$store.commit('SET_ROLES', [val]);
window.location.reload() this.$router.push({ path: '/permission/index?' + +new Date() });
} }
} }
} }