apollo-link-state 添加具有默认值的字段以键入

apollo-link-state add field with default value to type

这是我要实现的目标: 我有一个 graphql API 端点 returns 我是这样的项目对象(删除了不相关的字段):

{
  "data": {
    "Project": {
      "id": "cjp4b84wkochq0167gpu8oa7h",
      "requests": [
        {
          "id": "cjpbb6jcdpwj00167y4acl5a1",
          "__typename": "Request"
        },
        {
          "id": "cjpbbhlaxpwlx01675jzfyb0j",
          "__typename": "Request"
        },
        {
          "id": "cjpbbifg7pwmg0167s0ob1bm6",
          "__typename": "Request"
        },
      ],
      "__typename": "Project"
    }
  }
}

我想使用 apollo-link-state 向所有这些 Request 对象添加客户端字段,如下所示:

{
  "data": {
    "Project": {
      "id": "cjp4b84wkochq0167gpu8oa7h",
      "requests": [
        {
          "id": "cjpbb6jcdpwj00167y4acl5a1",
          "expanded": false,
          "__typename": "Request"
        },
        {
          "id": "cjpbbhlaxpwlx01675jzfyb0j",
          "expanded": false,
          "__typename": "Request"
        },
        {
          "id": "cjpbbifg7pwmg0167s0ob1bm6",
          "expanded": false,
          "__typename": "Request"
        },
      ],
      "__typename": "Project"
    }
  }
}

这将允许我从呈现这些请求的组件中删除本地状态。问题是,当我为我的 ApolloClient clientState 定义默认值时,如下所示:

const client = new ApolloClient({
  clientState: {
    defaults: {
      Project: {
        __typename: 'Project',
        requests: [{ __typename: 'Request', expanded: false }],
      },
    },
  },
});

Apollo 将其添加为新的 Project 对象,而不是将其添加到现有对象(具有 id)中:

ROOT_QUERY
  Project: Project
    requests: [Request]
      0:
        expanded: false
  Project({"id":"cjp4b84wkochq0167gpu8oa7h"}): Project
    ▾Project:cjp4b84wkochq0167gpu8oa7h

当我给它 id 时,它会将 "hi" 字段添加到正确的项目,但请求仍然缺少扩展字段。显然,提供 id 仅适用于特定项目。

const client = new ApolloClient({
  clientState: {
    defaults: {
      'Project({"id":"cjp4b84wkochq0167gpu8oa7h"})': {
        __typename: 'Project',
        hi: true,
        requests: [{ __typename: 'Request', expanded: false }],
      },
    },
  },
});

ROOT_QUERY
  Project({"id":"cjp4b84wkochq0167gpu8oa7h"}): Project
    ▾Project:cjp4b84wkochq0167gpu8oa7h
      hi: true
      requests: [Request]
        0:▾Request:cjpbb6jcdpwj00167y4acl5a1
          ...unrelated fields
        1:▾Request:cjpbbhlaxpwlx01675jzfyb0j
        2:▾Request:cjpbbifg7pwmg0167s0ob1bm6

我也试过像这样在 clientState 对象上使用 typeDefs 字段:

typeDefs: [`
  schema {
    query: RootQuery
  }

  type RootQuery {
    Project($id: ID): Project
  }

  type Project {
    id: ID!
    requests: [Request]
  }

  type Request {
    id: ID!
    expanded: Boolean
  }
`],

但这似乎并没有改变缓存中的任何内容,我不知道我是否可以像这样给它一个默认值。

也许我误解了 apollo-link-state 的工作原理(或者甚至 graphql 的工作原理)任何能指出我正确方向的答案都值得赞赏。在 graphql 或 apollo 方面,我是一个初学者。

您需要为您的 clientState 配置提供客户端解析器。

const clientState = {
  resolvers: {
    Project {
      expanded: () => false
    }
  }
}

然后像这样将它传递给 ApolloClient

const apolloClient = new ApolloClient({ clientState });