这是我要完成的工作: 我有一个graphql API端点,可以向我返回一个这样的Project对象(删除了不相关的字段):
{
"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,我非常新手。
答案 0 :(得分:2)
您需要为clientState配置提供客户端解析器。
const clientState = {
resolvers: {
Project {
expanded: () => false
}
}
}
然后将其像这样传递到您的ApolloClient中
const apolloClient = new ApolloClient({ clientState });