[英]GraphQL- conditionally determine the type of a field in a schema
I have the following mongoose schema: 我有以下猫鼬模式:
const MessageSchema = new Schema({
author: {
account:{
type:String,
enum:['employee','admin'],
},
id: String,
}
//other fields
})
Then in my graphql-schemas
file, I have the following schema types: 然后在我的
graphql-schemas
文件中,我具有以下架构类型:
const MessageType = new GraphQLObjectType({
name: 'Message',
fields: () => ({
account: {
type: AuthorType,
//resolve method
},
id: {type: GraphQLString},
})
})
const AuthorType= new GraphQLObjectType({
name: 'Author',
fields: () => ({
account: {
type://This will either be AdminType or EmployeeType depending on the value of account in db (employee or admin),
//resolve method code goes here
}
})
}) })
As indicated in the comments of AuthorType
, I need the account
field to resolve to Admin
or Employee
depending on the value of the account
field in the database. 正如在本评论表示
AuthorType
,我需要的account
域来解决,以Admin
或Employee
取决于价值account
场在数据库中。 How do I conditionally determine the type of a field in a schema on the fly? 如何有条件地动态确定架构中的字段类型?
Instead of determining the type on the fly, I restructured my code as shown below: 我没有立即确定类型,而是重新构建了代码,如下所示:
const MessageType = new GraphQLObjectType({
name: 'Message',
fields: () => ({
id:{type:GraphQLString},
author: {
type: AuthorType,
async resolve(parent, args) {
if (parent.author.account === 'guard') {
return await queries.findEmployeeByEmployeeId(parent.author.id).then(guard => {
return {
username: `${guard.first_name} ${guard.last_name}`,
profile_picture: guard.profile_picture
}
})
} else if (parent.author.account === 'admin') {
return {
username: 'Administrator',
profile_picture: 'default.jpg'
}
}
}
},
//other fields
})
})
const AuthorType = new GraphQLObjectType({
name: 'Author',
fields: () => ({
username: {type: GraphQLString},
profile_picture: {type: GraphQLString},
})
})
Since all I need from the AuthorType
is the author's username and profile picture, both employee and administrator have these fields, which I pass to AuthorType
. 由于我需要的
AuthorType
只是作者的用户名和个人资料图片,因此员工和管理员都具有这些字段,这些字段我传递给AuthorType
。 In MessageType
, I apply the logic to determine account type in the resolve
method of author
, then construct custom object out of the logic, to match AuthorType
. 在
MessageType
,我将逻辑应用于author
的resolve
方法中确定帐户类型,然后从逻辑中构造自定义对象,以匹配AuthorType
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.