这里有两种选择。
声明一个接口作为返回的类型,并确保每个associateTypes都扩展了该接口。在所有这些类型上都有公共字段的情况下,这是一个好主意。
它看起来是这样的:
interface associateType {
id: ID
department: Department
employees: [Employee]
}
type associateAccountingType implements associateType {
id: ID
department: Department
employees: [Employee]
accounts: [Account]
}
type associateArtDirectorType implements associateType {
id: ID
department: Department
employees: [Employee]
projects: [Project]
}
如果您没有任何公共字段,或者出于某种原因希望这些类型不相关,则可以使用联合类型。该声明要简单得多,但需要为查询的每个字段使用一个片段,因为引擎假设这些类型没有公共字段。
union associateType = associateAccountingType | associateArtDirectorType | associateAccountExecType
更重要的是如何实现一个解析器,它将告诉您的graphql服务器和客户机实际的具体类型是什么。对于apollo,您需要在联合/交互类型上提供__resolveType函数:
{
associateType: {
__resolveType(associate, context, info) {
return associate.isAccounting ? 'associateAccountingType' : 'associateArtDirectorType';
},
}
},
associate
参数将是从父解析程序返回的实际对象。
context
是您的常用上下文对象,并且
info
保存查询和模式信息。