[英]GraphQL-"Unknown argument \"country\" on field \"allNews\" of type \"Query\".",
[英]GraphQL- conditionally determine the type of a field in a schema
我有以下貓鼬模式:
const MessageSchema = new Schema({
author: {
account:{
type:String,
enum:['employee','admin'],
},
id: String,
}
//other fields
})
然后在我的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
}
})
})
正如在本評論表示AuthorType
,我需要的account
域來解決,以Admin
或Employee
取決於價值account
場在數據庫中。 如何有條件地動態確定架構中的字段類型?
我沒有立即確定類型,而是重新構建了代碼,如下所示:
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},
})
})
由於我需要的AuthorType
只是作者的用戶名和個人資料圖片,因此員工和管理員都具有這些字段,這些字段我傳遞給AuthorType
。 在MessageType
,我將邏輯應用於author
的resolve
方法中確定帳戶類型,然后從邏輯中構造自定義對象,以匹配AuthorType
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.