簡體   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