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

时间:2018-07-14 09:19:39

标签: graphql

我有以下猫鼬模式:

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字段的值在数据库中。 如何有条件地动态确定架构中的字段类型?

1 个答案:

答案 0 :(得分:0)

我没有立即确定类型,而是重新构建了代码,如下所示:

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中,我应用逻辑来确定resolve的{​​{1}}方法中的帐户类型,然后从逻辑中构造自定义对象以匹配author