From 3dd77c7f1265b908e4e8655e0ec23290394401f0 Mon Sep 17 00:00:00 2001 From: Anton Medvedev Date: Sun, 1 Dec 2024 22:27:31 +0100 Subject: [PATCH] Fix non-null list fields queries --- src/generate.ts | 20 +++++++++++++------- src/index.test.ts | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 7 deletions(-) diff --git a/src/generate.ts b/src/generate.ts index 2e393fa..8df248f 100644 --- a/src/generate.ts +++ b/src/generate.ts @@ -1,4 +1,5 @@ import { + GraphQLOutputType, GraphQLType, isEnumType, isListType, @@ -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 { diff --git a/src/index.test.ts b/src/index.test.ts index e243c49..24fa78d 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -11,6 +11,8 @@ const schema = buildSchema(` type Query { User(login: String!): User + Users: [User!] + NonNullUsers: [User!]! } type User { @@ -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 + }> +}`) +})