简体   繁体   English

执行突变时,ApolloClient 的所有值都会导致 null

[英]ApolloClient all values result to null when performing a mutation

I started using ApolloClient and i must say, the documentation is horrible.我开始使用 ApolloClient,我必须说,文档很糟糕。

My application will use GraphQL, but the login needs to be done using a simple POST request to /login providing the username and password, as formdata.我的应用程序将使用 GraphQL,但登录需要使用对/login的简单POST请求来完成,提供用户名和密码,作为 formdata。

And man, getting that to work has been a complete nightmare.伙计,让它发挥作用是一场彻头彻尾的噩梦。

Since i have to use apollo-link-rest i have to first build my client:由于我必须使用apollo-link-rest我必须首先构建我的客户端:

import ApolloClient from 'apollo-client'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { ApolloLink } from 'apollo-link'
import { createHttpLink } from 'apollo-link-http'
import { onError } from 'apollo-link-error'
import { RestLink } from 'apollo-link-rest'

const cache = new InMemoryCache()

const httpLink = new createHttpLink({
  credentials: 'include',
})

const restLink = new RestLink({
  endpoints: {
    localhost: {
      uri: "http://localhost:8080"
    }
  },
  credentials: 'include'
})

const errorLink = onError(({ graphQLErrors, networkError, operation }) => {
  if (graphQLErrors) {
    graphQLErrors.forEach(({ message, locations, path }) => {
      console.log(`[GraphQL error] Message: ${message}, ${path}`)
    })
  }
  if (networkError) {
    console.log(
      `[Network error ${networkError}] Operation: ${operation.operationName}`
    )
  }
})

export const client = new ApolloClient({
  link: ApolloLink.from([errorLink, restLink, httpLink]),
  cache,
})

then i have my query:然后我有我的查询:

const LOGIN_QUERY = gql`
  mutation doLogin($username: String!, $password: String!, $formSerializer: any) {
    user(input: { username: $username, password: $password})
      @rest(
        path: "/login"
        type: "user"
        method: "POST"
        endpoint: "localhost"
        bodySerializer: $formSerializer
      ) {
        id
        name
      }
  }`

const formSerializer = (data, headers) => {
  const formData = new URLSearchParams()
  for (let key in data) {
    if (data.hasOwnProperty(key)) {
      formData.append(key, data[key])
    }
  }

  headers.set('Content-Type', 'application/x-www-form-urlencoded')

  return { body: formData, headers }
}

I find it utterly crazy that the documentation doesn't have an example of how you send form data, i had to google a lot until i found out how to do it.我发现文档没有关于如何发送表单数据的示例,这完全是疯狂的,我不得不在谷歌上搜索很多,直到我发现如何去做。

and i execute the query in a login component:我在登录组件中执行查询:

  const [doLogin, { data }] = useMutation(LOGIN_QUERY, {
    onCompleted: () => {
      console.log("Success")
    },
    onError: () => {
      console.log("Poop")
    }
  })

  const handleSubmit = (event) => {
    event.preventDefault()
    console.log('logging in...')
    doLogin({
      variables: { username, password, formSerializer },
    })
  }

the server logs me in, returns a session cookie, and a body containing:服务器让我登录,返回一个 session cookie,以及一个包含以下内容的正文:

{
    "data": {
        "user": {
            "id": 1
            "name": "Foobar"
        }
    }
}

When i check the cache state using the ApolloClient google chrome plugin, the cache has:当我使用 ApolloClient google chrome 插件检查缓存 state 时,缓存有:

user:null
    id: null
    name: null

so here are my questions:所以这是我的问题:

  1. Do i need to set a default state?我需要设置默认的 state 吗?
  2. Documentation only show mutations on objects that first have been queried upon, can i only update the cache using a mutation if the object already exists in the cache?文档仅显示首先查询的对象的突变,如果 object 已存在于缓存中,我是否只能使用突变更新缓存?
  3. Do i need to write resolvers for every type?我需要为每种类型编写解析器吗?
  4. And ofc, why do i get null values?而且,为什么我会得到 null 值?
  5. Does all data need to be returned wrapped in a data object, even for rest queries?是否需要将所有数据都包含在data object 中返回,即使对于 rest 查询也是如此?
  6. Must the formSerializer be passed as a variable to the query, because i find that super ugly.必须将formSerializer作为变量传递给查询,因为我觉得那超级难看。

As said before... the ApolloClient documentation is one of the worst documentations i have ever read.如前所述... ApolloClient 文档是我读过的最糟糕的文档之一。 Not user friendly at all.一点都不友好。

According to Response transforming , apollo expects response from REST APIs like the following:根据Response transforming ,apollo 期望来自 REST API 的响应,如下所示:

{
  "id": 1,
  "name": "Apollo"
}

If you cannot control backend, you can use customized response transformer:如果您无法控制后端,您可以使用自定义的响应转换器:

responseTransformer: async response => response.json().then(({data}) => data.data?.user)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM