使用 graphql union return 一个包含一些空对象的数组

Using graphql union return an array with some empty objects

我正在使用 graphql 联合 - union FolderOrFile = Folder | File。当我仅查询文件夹时,我得到包含文件夹对象的数组,其中空对象基本上是文件对象。

类型定义

const typeDefs = gql`
    union FolderOrFile = Folder | File
    type Folder {
        name: String
        path: String
        type: String
        children: [FolderOrFile]
    }
    type File {
        name: String
        path: String
        content: String
        type: String
        size: Int
        ext: String
        createdAt: String
    }
    type Query {
        folders: Folder
    }
`

解析器

const resolvers = {
    FolderOrFile: {
        __resolveType: obj => {
            if (obj.type === "file") {
                return 'File'
            }
            if (obj.type === "folder") {
                return 'Folder'
            }
        },
    },
    Query: {
        folders: async () => {
            const data = await folders
                .getFolder('./filesystem')
                .then(response => response)
            const appendData = await {
                name: 'Folder',
                path: './filesystem',
                type: 'folder',
                children: data,
            }
            return appendData
        }
    }
}

folders查询

{
  folders {
    name
    path
    type
    children {
      ... on Folder {
        name
        path
        type
        children {
          ... on Folder {
            name
            path
            type
          }
        }
      }
    }
  }
}

我收到回复

{
  "data": {
    "folders": {
      "name": "Folder",
      "path": "./filesystem",
      "type": "folder",
      "children": [
        {
          "name": "Dishes",
          "path": "./filesystem/Dishes",
          "type": "folder",
          "children": [
            {},
            {},
            {
              "name": "Non Vegetarian",
              "path": "./filesystem/Dishes/Non Vegetarian",
              "type": "folder"
            },
            {
              "name": "Vegetarian",
              "path": "./filesystem/Dishes/Vegetarian",
              "type": "folder"
            }
          ]
        },
      ]
    }
  }
}

响应不应包含那些空对象,在本例中,这些空对象是作为空对象返回的文件。同样,当我查询文件时,我得到的文件夹是空对象。

在查询 returns 联合或接口的字段时,您必须为 所有 可能的类型指定内联片段。在您的查询中,您只使用 Folder 类型的内联片段。您正在告诉服务器 "if the returned object is a Folder, I want these fields"。但是,如果该对象解析为任何其他类型,如文件,您最终会得到一个空的选择集,因为您没有为该特定类型指定您想要的字段。

{
  folders {
    name
    path
    type
    children {
      ... on Folder {
        name
        path
        type
      }
      ... on File {
        # whatever your File fields are
      }
    }
  }
}