react-apollo - apolloClient.query 不使用中间件,而做
问题描述
我有一个带有中间件的 apolloclient,它控制台记录一个不记名令牌,因为当我应该进行身份验证时,我并不总是经过身份验证。
出于某种原因,来自 react-apollo 对象的查询似乎<Query />
使用了这个中间件——我看到了我的控制台消息——但是我以编程方式触发的查询:apolloClient.query
不记录任何东西(代码无法做到这一点,控制台日志位于 authLink 中间件的顶部)。
在切换到 apolloclient 之前,我使用 apollo-boost 开始了我的项目,所以我认为切换后可能没有正确设置 node_modules。但是我已经删除并重新安装了纱线,它现在不应该有任何阿波罗助推器的痕迹。
此外,如果我将用于创建的代码复制apolloclient
到我的事务中,使其使用该本地副本而不是全局副本,则中间件会触发。
IE:
export const relayBBNToGraphcool = async () => {
/* BEGIN without this code, WHICH IS ALREADY in the instantiation of apolloClient, the result is `user: null` */
const authLink = setContext(async (req, { headers }) => {
// get the authentication token from local storage if it exists
let getToken = async () => await AsyncStorage.getItem(/*'access_token'*/'graphcool_token')
const token = await getToken()
console.trace('token for connection to graphcool is currently', token, req.operationName)
// return the headers to the context so httpLink can read them
return token
? {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : null,
}
}
: { headers }
})
const httpLink = new HttpLink(config)
const link = ApolloLink.from([/* retryLink, */ authLink, httpLink])
const cache = new InMemoryCache()
// overriding apolloClient in the global scope of this module
const apolloClient = new ApolloClient({
link,
cache
})
/* END */
apolloClient.query({ query: User.self, forceFetch: true })
.then(authneticatedUser => {
console.trace('response', authneticatedUser)
if(authneticatedUser.data.user === null)
throw ('no user')
apolloClient 是从apollo-client而不是apollo-boost配置的。它在 App.js 中附加到其提供程序:
return (
<ApolloProvider client={this.state.apolloClient}>
使用 getApolloClient() 从不同的文件加载——它设置了一个局部变量apolloClient:
var apolloClient //...
export const getApolloClient = () => { // ...
apolloClient = new ApolloClient({
link,
cache
}) //...
return apolloClient
所有对.query或.mutate的调用都是从同一个文件中的导出函数完成的,并且它们使用相同的var apolloClient。我从不实例化一个以上的 apollo 客户端。为什么我的一些查询正在触发中间件,而其他查询却没有?
编辑:
每个请求,使用的实际链接:
// from src: https://github.com/kadikraman/offline-first-mobile-example/blob/master/app/src/config/getApolloClient.js
export const getApolloClient = async () => {
const retryLink = new RetryLink({
delay: {
initial: 1000
},
attempts: {
max: 1000,
retryIf: (error, _operation) => {
if (error.message === 'Network request failed') {
//if (_operation.operationName === 'createPost')
// return true
}
return false
}
}
})
// from: https://www.apollographql.com/docs/react/recipes/authentication.html
const authLink = setContext(async (req, { headers }) => {
// get the authentication token from local storage if it exists
let getToken = async () => await AsyncStorage.getItem(/*'access_token'*/'graphcool_token')
const token = await getToken()
console.trace('token for connection to graphcool is currently', token, req.operationName)
// return the headers to the context so httpLink can read them
return token
? {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : null,
}
}
: { headers }
})
const httpLink = new HttpLink(config)
const link = ApolloLink.from([retryLink, authLink, httpLink])
const cache = new InMemoryCache()
apolloClient = new ApolloClient({
link,
cache
})
try {
await persistCache({
cache,
storage: AsyncStorage
})
} catch (err) {
console.error('Error restoring Apollo cache', err) // eslint-disable-line no-console
}
return apolloClient
}
解决方案
事实证明,这个问题与缓存有关——getApolloClient方法中的这一部分:
try {
await persistCache({
cache,
storage: AsyncStorage
})
} catch (err) {
console.error('Error restoring Apollo cache', err) // eslint-disable-line no-console
}
如果我在将更改应用于发送到 ApolloProvider 的副本之前更改代码以保存 apolloClient,它会起作用,如下所示:
export var apolloClient
// from src: https://github.com/kadikraman/offline-first-mobile-example/blob/master/app/src/config/getApolloClient.js
export const getApolloClient = async () => {
apolloClient = await getRawClient()
try {
await persistCache({
cache,
storage: AsyncStorage
})
} catch (err) {
console.error('Error restoring Apollo cache', err) // eslint-disable-line no-console
}
return apolloClient
}
export const getRawClient = async () => {
const retryLink = new RetryLink({
delay: {
initial: 1000
},
attempts: {
max: 1000,
retryIf: (error, _operation) => {
if (error.message === 'Network request failed') {
//if (_operation.operationName === 'createPost')
// return true
}
return false
}
}
})
// from: https://www.apollographql.com/docs/react/recipes/authentication.html
const authLink = setContext(async (req, { headers }) => {
// get the authentication token from local storage if it exists
let getToken = async () => await AsyncStorage.getItem(/*'access_token'*/'graphcool_token')
const token = await getToken()
console.trace('token for connection to graphcool is currently', token, req.operationName)
// return the headers to the context so httpLink can read them
return token
? {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : null,
}
}
: { headers }
})
const httpLink = new HttpLink(config)
const link = ApolloLink.from([/* retryLink, */ authLink, httpLink])
const cache = new InMemoryCache()
return new ApolloClient({
link,
cache
})
}
然后,我还从这个文件中重构了查询和变异代码,导入了 apolloClient。那行得通……这有点奇怪,但无论如何。
推荐阅读
- python - 如何让令牌在一段时间后过期?(没有 jwt)
- android-studio - 无法在 Android Studio 3.5.1 中创建语言环境 strings.xml
- xml - XSLT拆分字符串,将它们存储在变量中并输出它们
- javascript - Angular 8 - 处理 http 返回的 observable 时的管道问题
- object - 在处理中导入 .dae 文件
- spring - 如何在 Spring 中用另一个 RestController 扩展一个 RestController 的路由?
- c# - Neo4j Cypher 具有属性的最短路径
- sql - MariaDB 更新语句的正确语法
- html - CSS - Div 焦点更改蓝色边框突出显示颜色
- tensorflow - 计算多个张量的损失值