2

有没有办法在运行中全局捕获和修改响应?我可以为下面的一个查询执行此操作,但我想为所有查询执行此操作。

apollo: {
    post: {
        query: Post,
        update(data) {
            return data.map(item => Object.assign(item, {foo: 'bar'})
        }
    }
}

这个问题被简化了,但在幕后我想对所有对象应用一个构造函数(类)......

我正在使用 nuxt-apollo。我在 clientConfig 或其他地方搜索了一种方法,因此该解决方案可能与 apollo 相关...

谢谢你的建议!

编辑:好的,我发现使用 apollo-link 可以做到这一点,但我无法修改响应。这里的代码:

const constructorMiddleware = new ApolloLink((operation, forward) => {
    return forward(operation).map(response => {
      Object.keys(response.data).map(key => {
        if (!Array.isArray(response.data[key])) return;
        const newResponse = response.data[key].map(item => {
          return item.__typename === 'post'
            ? Object.assign(item, { foo: 'bar' })
            : item
        })
        console.log(newResponse)
        response.data[key] = newResponse
      })
      return response
    })
  })

我可以foo: bar在 newResponse 中看到,但是 nuxt-apollo 返回的 graphql 不包含这个 newResponse,只有原始的。ApolloLink 是否覆盖响应?阿波罗缓存会改变这一点吗?

编辑 2:我尝试链接链接,并且构造函数中间件的 newResponse 在下一个链接中很好。所以问题似乎来自 nuxt-apollo,或者更多 vue-apollo ......

4

0 回答 0