prv*_*ist 3 union apollo graphql
我正在使用 graphql union - 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
}
`
Run Code Online (Sandbox Code Playgroud)
旋转变压器
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
folders
询问
{
folders {
name
path
type
children {
... on Folder {
name
path
type
children {
... on Folder {
name
path
type
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我得到的回应
{
"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"
}
]
},
]
}
}
}
Run Code Online (Sandbox Code Playgroud)
响应不应该包含那些空对象,在本例中是作为空对象返回的文件。同样,当我查询文件时,我得到的文件夹是空对象。
在查询返回联合或接口的字段时,您必须为所有可能的类型指定内联片段。在您的查询中,您仅使用该类型的内联片段Folder
。您告诉服务器“如果返回的对象是文件夹,我需要这些字段”。但是,如果对象解析为任何其他类型(例如文件),您最终会得到一个空的选择集,因为您尚未指定该特定类型所需的字段。
{
folders {
name
path
type
children {
... on Folder {
name
path
type
}
... on File {
# whatever your File fields are
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2042 次 |
最近记录: |