基于vue2,apollo-client 请求封装
安装 apollo 相关插件
npm i apollo-client,apollo-cache-inmemory,apollo-link,apollo-link-http
封装请求
graphql.js
import ApolloClient from 'apollo-client'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { HttpLink } from 'apollo-link-http'
import { onError } from 'apollo-link-error'
import { ApolloLink, from } from 'apollo-link'
import { getToken } from '@/utils/auth'
import { baseURL } from '@/utils/common'
import { Message } from 'element-ui'
import Router from "@/router"
import { removeToken } from '@/utils/auth'
// 定义不同请求地址
const EFORMURI = baseURL + '/eform'
const IOTURI = baseURL + '/iot'
// 后置中间件
const Afterware = new ApolloLink((operation, forward) => {
return forward(operation).map(response => {
// 服务器返回数据
return response
})
})
const errorLink = onError(({ graphQLErrors, networkError }) => {
// 如果存在GraphQL错误
if (graphQLErrors) {
// 遍历所有的GraphQL错误并打印错误信息、位置和路径
graphQLErrors.map(({ message, locations, path }) => {
// 判断message中是否有401 有的话跳转登陆页
if (message.includes('401')) {
let { path } = Router.currentRoute
setTimeout(() => {
removeToken()
Router.replace(`/login?redirect=${path}`).then(() => {
window.location.reload()
})
}, 1000);
}
console.error(
`[GraphQL错误]: 消息: ${message}, 位置: ${locations}, 路径: ${path}`
)
})
// 显示错误消息提示
Message({
message: graphQLErrors[0].message || '错误',
type: 'error'
})
}
// 如果存在网络错误
if (networkError) {
console.log(`[网络错误]: ${networkError}`)
// 显示网络错误消息提示
// Message({
// message: networkError || '错误',
// type: 'error'
// })
}
})
function createHttpLink(uri) {
// 异常处理:确保 getToken 调用的异常能够被捕获并合理处理
let token;
try {
token = getToken();
} catch (error) {
console.error("Error obtaining token:", error);
token = null; // 或者根据具体情况处理
}
const headers = token ? { Authorization: token } : {};
// 添加边界条件检查,确保 token 格式正确,例如非空字符串
if (token && typeof token !== 'string' || token.trim() === '') {
console.error('Invalid token format.');
token = null;
}
return new HttpLink({ uri, headers });
}
// 缓存实例初始化
const cache = new InMemoryCache();
// eform 请求配置,优化代码重构和可维护性
const httpLinkEform = createHttpLink(EFORMURI);
export const clientEform = new ApolloClient({
link: from([Afterware, errorLink, httpLinkEform]),
cache
});
// iot 请求配置,进一步体现代码重构的效益
const httpLinkIot = createHttpLink(IOTURI);
export const clientIot = new ApolloClient({
link: from([Afterware, errorLink, httpLinkIot]),
cache
});
封装接口
eform.graphql
query get_user($input:QNoromal){
get_user(input:$input){
size
total
data{
id
status
sn
name
account
sex
job
dep
email
mobile
admin
tag
type
parent
signature
shifts
}
}
}
mutation update_user($id:String!,$input:EditUser){
update_user(id:$id,input:$input){
isOk,
message
id
}
}
login.js
import { clientEform, clientIot } from '../utils/graphql'
import { login, loads, GetMenu } from './eform.graphql'
// 登陆
export const adminLogin = (params) => clientEform.mutate({
mutation: login,
variables: params
})
// 获取字典
export const getLoads = (params) => clientIot.query({
query: loads,
fetchPolicy: 'network-only',
variables: params
})
// 获取菜单
export const getMenu = (params) => clientEform.query({
query: GetMenu,
fetchPolicy: 'network-only',
variables: params
})