Reputation: 451
I'm using graphql union - union FolderOrFile = Folder | File
. When I query for only folders I get array containing folder objects with empty objects that are basically the file objects.
TypeDefs
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
}
`
Resolvers
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
query
{
folders {
name
path
type
children {
... on Folder {
name
path
type
children {
... on Folder {
name
path
type
}
}
}
}
}
}
Response I get
{
"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"
}
]
},
]
}
}
}
The response shouldn't have those empty objects which in this case is for files being returned as empty object. Similarly when I query for file I get folders as empty objects.
Upvotes: 3
Views: 2237
Reputation: 84697
You have to specify inline fragments for all the possible types when querying a field that returns a union or interface. In your query, you are only using an inline fragment for the Folder
type. You're telling the server "if the returned object is a Folder, I want these fields". But if the object resolves to any other type, like File, you end up with an empty selection set because you have not specified which fields you want for that particular type.
{
folders {
name
path
type
children {
... on Folder {
name
path
type
}
... on File {
# whatever your File fields are
}
}
}
}
Upvotes: 5