Skip to content

Commit

Permalink
Fix: graphql composer nested objects (#64)
Browse files Browse the repository at this point in the history
* feat: Fixing query building of nested elements of same type

* feat: Added test case to show the issue
  • Loading branch information
MarcoMuellner authored Oct 25, 2024
1 parent a6fa5e8 commit 4125ad1
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 4 deletions.
3 changes: 1 addition & 2 deletions lib/query-builder.js
Original file line number Diff line number Diff line change
Expand Up @@ -134,10 +134,9 @@ function buildQuerySelection (selection, parent, wrap = true, fragment = undefin
} else if (selection[i].selection) {
fields.add(buildQuerySelection(selection[i].selection, null, selection[i].wrap, selection[i].fragment).selection)
} else if (selection[i].nested) {
fields.add(selection[i].parentField)
for (const nested of selection[i].nested.values()) {
const s = buildSubQuery(nested.query, nested)
fields.add(s.subquery)
fields.add(`${selection[i].parentField} ${s.subquery}`)
for (const i of Object.keys(s.keys)) {
const k = s.keys[i]
keys.set(k.resolverPath + keyId(k), k)
Expand Down
27 changes: 25 additions & 2 deletions test/fixtures/books.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,17 @@ const schema = `
NONFICTION
}
type ChapterData {
title: String
pageCount: Int
}
type Book {
id: ID!
title: String
genre: BookGenre
firstChapter: ChapterData
lastChapter: ChapterData
}
enum BookField {
Expand Down Expand Up @@ -38,12 +45,28 @@ function reset () {
1: {
id: 1,
title: 'A Book About Things That Never Happened',
genre: 'FICTION'
genre: 'FICTION',
firstChapter: {
title: 'The Beginning',
pageCount: 20
},
lastChapter: {
title: 'The End',
pageCount: 25
}
},
2: {
id: 2,
title: 'A Book About Things That Really Happened',
genre: 'NONFICTION'
genre: 'NONFICTION',
firstChapter: {
title: 'Introduction',
pageCount: 15
},
lastChapter: {
title: 'Conclusion',
pageCount: 18
}
}
}
}
Expand Down
28 changes: 28 additions & 0 deletions test/query.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -669,6 +669,34 @@ test('mutations', async (t) => {
message: 'Author not found'
}
}
},

{
name: 'should run a query with multiple nested selections at the same level',
query: `{
getBook(id: 1) {
firstChapter {
title
pageCount
}
lastChapter {
title
pageCount
}
}
}`,
result: {
getBook: {
firstChapter: {
title: 'The Beginning',
pageCount: 20
},
lastChapter: {
title: 'The End',
pageCount: 25
}
}
}
}
]

Expand Down

0 comments on commit 4125ad1

Please sign in to comment.