Skip to content

Commit

Permalink
Fix non-null list fields queries
Browse files Browse the repository at this point in the history
  • Loading branch information
antonmedv committed Dec 1, 2024
1 parent 51c56d9 commit 3dd77c7
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 7 deletions.
20 changes: 13 additions & 7 deletions src/generate.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
GraphQLOutputType,
GraphQLType,
isEnumType,
isListType,
Expand Down Expand Up @@ -79,18 +80,23 @@ function generateSelector(s: Selector, depth = 0, nonNull = false): string {
return generateType(s.type)
}

const code =
generateFields(s, depth) +
generateFragments(s) +
generateInlineFragments(s, depth - 1)

if (isNonNullType(s.type)) {
return wrapInArray(s.type.ofType, code)
}

return (
generateArray(s, depth) +
wrapInArray(s.type, code) +
(isNullableType(s.type) && !nonNull ? ' | null' : '')
)
}

function generateArray(s: Selector, depth: number): string {
const code =
generateFields(s, depth) +
generateFragments(s) +
generateInlineFragments(s, depth - 1)
return isListType(s.type) ? 'Array<' + code + '>' : code
function wrapInArray(t: GraphQLOutputType | undefined, code: string) {
return isListType(t) ? `Array<${code}>` : code
}

function generateFragments(s: Selector): string {
Expand Down
34 changes: 34 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ const schema = buildSchema(`
type Query {
User(login: String!): User
Users: [User!]
NonNullUsers: [User!]!
}
type User {
Expand Down Expand Up @@ -151,3 +153,35 @@ test('inline interfaces', () => {
expect(code).includes('barks: boolean | null\n')
expect(code).includes('meows: boolean | null\n')
})

test('query with list', () => {
const source = new Source(`
query Nullable {
Users {
name
}
}
`)
const code = transpile(schema, source)
expect(code).includes(`{
Users: Array<{
name: string | null
}> | null
}`)
})

test('query with non-null list', () => {
const source = new Source(`
query NonNullable {
NonNullUsers {
name
}
}
`)
const code = transpile(schema, source)
expect(code).includes(`{
NonNullUsers: Array<{
name: string | null
}>
}`)
})

0 comments on commit 3dd77c7

Please sign in to comment.