我有一个基于https://www.apollographql.com/docs/graphql-tools/schema-stitching/
假设我有以下模式(注意,它是为一个示例而构建的,以这种方式构造它是没有意义的)
//First schema
type User {
id
cars: [Car]!
}
type Car {
id
name: String
model: String
}
//Second schema
type Color {
id
name: String
rgb: String
opacity: Int
}
//Defined in Apollo Server
extend type Car {
color: Color
}
和下面的解析器
resolvers: {
Car: {
color: {
fragment: '... on Car { id }',
resolve(parent, args, context, info) {
return delegateToSchema({
schema: secondSchema,
operation: 'query',
fieldName: 'colorByUserAndCarId',
args: {
id: parent.id,
userId: ?
},
context,
info,
});
},
},
},
}
我怎样才能获得userId,它在类型User上,而不是Car上?
当我在寻找答案的时候,我想到了一些解决方案,但我不知道如何让它们发挥作用。。
颜色
部分的汽车
,所以我将有每种颜色的字段直接在汽车,所以我想我会有基于用户的解析器,而不是...?的片段,而在类型Car
上,但到目前为止不起作用。
Car
中,但无论如何我找不到如何获取userId从根目录更改模式和类型不是一个选项,所有修改都需要在Apollo Server中进行。
写问题和潜在的解决方案帮助我更好地理解它是如何工作的,以及如何实现这一点。
我可以为汽车添加一个解析器,就像我为颜色添加解析器一样,当我进入汽车解析器时,“汽车”的对象值已经存在了...父
值看起来像{id:x,car:{...}}
,id
是userId
,所以我可以在我的汽车解析器中执行此操作
let myCar = parent.car;
myCar.userId = parent.id;
return myCar;
当我在我的颜色解析器中时,我将能够执行parent.userId
。