繁体   English   中英

GraphQL-有条件地确定架构中字段的类型

[英]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域来解决,以AdminEmployee取决于价值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 ,我将逻辑应用于authorresolve方法中确定帐户类型,然后从逻辑中构造自定义对象,以匹配AuthorType

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM