Skip to content

fix: create correct types for lists #87

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions src/create-schema-customization/__tests__/build-types.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,4 +203,30 @@ describe(`Build objectType`, () => {
})
})
})

it(`creates correct types for lists`, () => {
const gatsbyNodeDefs = createGatsbyNodeDefinitions([
{
remoteTypeName: `Category`,
queries: `{
categories {
optionalListOfOptionalType
optionalListOfRequiredType
requiredListOfOptionalType
requiredListOfRequiredType
}
}`,
},
])
const context = createTestContext({ gatsbyNodeDefs })
const categoryDef = buildTypeDefinition(context, `Category`)
const categoryFields = (categoryDef as GatsbyGraphQLObjectType).config.fields

expect(categoryFields).toMatchObject({
optionalListOfOptionalType: { type: `[TestApiCategory]` },
optionalListOfRequiredType: { type: `[TestApiCategory!]` },
requiredListOfOptionalType: { type: `[TestApiCategory]!` },
requiredListOfRequiredType: { type: `[TestApiCategory!]!` },
})
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ type Category implements Named {
id: ID!
entries: [Entry]
displayName: String!

optionalListOfOptionalType: [Category]
optionalListOfRequiredType: [Category!]
requiredListOfOptionalType: [Category]!
requiredListOfRequiredType: [Category!]!
}

type Guest implements Entry & Named {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,17 +169,23 @@ function toGatsbyType(
* i.e. wrapType(`JSON`, myRemoteListOfJSONType) => `[JSON]`
*/
function wrap(typeName: string, remoteType: GraphQLType): string {
let wrappedType = typeName
const wrappingTypes: GraphQLType[] = []
let currentRemoteType = remoteType
while (isWrappingType(currentRemoteType)) {
if (isListType(currentRemoteType)) {
wrappedType = `[${wrappedType}]`
}
if (isNonNullType(currentRemoteType)) {
wrappingTypes.push(currentRemoteType)
currentRemoteType = currentRemoteType.ofType
}

let wrappedType = typeName
for (const wrappingType of wrappingTypes.reverse()) {
if (isNonNullType(wrappingType)) {
wrappedType = `${wrappedType}!`
}
currentRemoteType = currentRemoteType.ofType
if (isListType(wrappingType)) {
wrappedType = `[${wrappedType}]`
}
}

return wrappedType
}

Expand Down