Skip to content

Commit

Permalink
Support GraphQL fragments (#1536)
Browse files Browse the repository at this point in the history
* Add support for GraphQL fragments

* Add rush change file

* Fix integration test

---------

Co-authored-by: Castro, Mario <mariocs@optum.com>
  • Loading branch information
MarcAstr0 and Castro, Mario authored Jun 13, 2024
1 parent 8304ae5 commit dcd0714
Show file tree
Hide file tree
Showing 3 changed files with 251 additions and 20 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"changes": [
{
"packageName": "@boostercloud/framework-core",
"comment": "Add support for GraphQL fragments",
"type": "patch"
}
],
"packageName": "@boostercloud/framework-core"
}
68 changes: 49 additions & 19 deletions packages/framework-core/src/services/graphql/graphql-generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
import { getLogger } from '@boostercloud/framework-common-helpers'
import {
FieldNode,
FragmentDefinitionNode,
getNamedType,
GraphQLFieldResolver,
GraphQLInputObjectType,
Expand All @@ -27,6 +28,7 @@ import {
GraphQLResolveInfo,
GraphQLSchema,
isObjectType,
Kind,
} from 'graphql'
import { pluralize } from 'inflected'
import { BoosterCommandDispatcher } from '../../booster-command-dispatcher'
Expand Down Expand Up @@ -265,44 +267,72 @@ export class GraphQLGenerator {
* @param {SelectionSetNode} selectionSet - The selection set.
* @param {string[]} path - The current path.
* @param {GraphQLObjectType | any} parentType - The parent type.
* @param {Map<string, FragmentDefinitionNode>} fragments - The fragment definitions.
* @returns {string[]} - The extracted fields.
*/
const extractFields = (
selectionSet: SelectionSetNode,
path: string[] = [],
parentType: GraphQLObjectType | any
parentType: GraphQLObjectType | any,
fragments: Map<string, FragmentDefinitionNode>
): string[] => {
let subFields: string[] = []
if (selectionSet && selectionSet.selections) {
selectionSet.selections.forEach((selection: any) => {
const fieldName = selection.name.value
const field = parentType.getFields()[fieldName]
if (selection.kind === Kind.FIELD) {
const fieldName = selection.name.value
const field = parentType.getFields()[fieldName]

if (!field) {
return
}
if (!field) {
return
}

const fieldType: GraphQLNamedInputType = getNamedType(field.type as GraphQLNamedInputType)
const currentPath = [...path, fieldName]
const fieldType: GraphQLNamedInputType = getNamedType(field.type as GraphQLNamedInputType)
const currentPath = [...path, fieldName]

if (isList(field.type)) {
const elementType = getNamedType(field.type.ofType)
if (isObjectType(elementType)) {
currentPath[currentPath.length - 1] += '[]'
if (isList(field.type)) {
const elementType = getNamedType(field.type.ofType)
if (isObjectType(elementType)) {
currentPath[currentPath.length - 1] += '[]'
}
}
}

if (!selection.selectionSet) {
subFields.push(currentPath.join('.'))
} else {
const nextParentType = isObjectType(fieldType) ? fieldType : parentType
subFields = subFields.concat(extractFields(selection.selectionSet, currentPath, nextParentType))
if (!selection.selectionSet) {
subFields.push(currentPath.join('.'))
} else {
const nextParentType = isObjectType(fieldType) ? fieldType : parentType
subFields = subFields.concat(
extractFields(selection.selectionSet, currentPath, nextParentType, fragments)
)
}
} else if (selection.kind === Kind.FRAGMENT_SPREAD) {
const fragmentName = selection.name.value
const fragment = fragments.get(fragmentName)

if (fragment) {
subFields = subFields.concat(extractFields(fragment.selectionSet, path, parentType, fragments))
}
} else if (selection.kind === Kind.INLINE_FRAGMENT) {
const inlineFragmentType = selection.typeCondition
? info.schema.getType(selection.typeCondition.name.value)
: parentType

if (isObjectType(inlineFragmentType)) {
subFields = subFields.concat(extractFields(selection.selectionSet, path, inlineFragmentType, fragments))
}
}
})
}
return subFields
}

// Collect all fragment definitions
const fragments = new Map<string, FragmentDefinitionNode>()
info.fragments &&
Object.keys(info.fragments).forEach((fragmentName) => {
fragments.set(fragmentName, info.fragments[fragmentName] as FragmentDefinitionNode)
})

info.fieldNodes.forEach((fieldNode: FieldNode) => {
const firstField: string = fieldNode.name.value
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
Expand All @@ -313,7 +343,7 @@ export class GraphQLGenerator {
) as unknown as GraphQLObjectType

if (fieldNode.selectionSet) {
fields = fields.concat(extractFields(fieldNode.selectionSet, [], rootType))
fields = fields.concat(extractFields(fieldNode.selectionSet, [], rootType, fragments))
}
})

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
import { ApolloClient, NormalizedCacheObject, gql } from '@apollo/client'
import { ApolloClient, gql, NormalizedCacheObject } from '@apollo/client'
import { commerce, finance, internet, lorem, random } from 'faker'
import { expect } from '../../helper/expect'
import { waitForIt } from '../../helper/sleep'
Expand Down Expand Up @@ -1704,6 +1704,197 @@ describe('Read models end-to-end tests', () => {
])
})
})

context('query with fragments', () => {
const mockCartId: string = random.uuid()
const mockProductId: string = random.uuid()
const mockQuantity: number = random.number({ min: 1 })

beforeEach(async () => {
// provisioning a cart
await client.mutate({
variables: {
cartId: mockCartId,
productId: mockProductId,
quantity: mockQuantity,
},
mutation: gql`
mutation ChangeCartItem($cartId: ID!, $productId: ID!, $quantity: Float!) {
ChangeCartItem(input: { cartId: $cartId, productId: $productId, quantity: $quantity })
}
`,
})
})

it('should retrieve expected cart', async () => {
const fragment = gql`
fragment cartItemDetails on CartItem {
productId
quantity
}
`
const queryResult = await waitForIt(
() => {
return client.query({
variables: {
cartId: mockCartId,
},
query: gql`
query CartReadModel($cartId: ID!) {
CartReadModel(id: $cartId) {
id
cartItems {
...cartItemDetails
}
}
}
${fragment}
`,
})
},
(result) => result?.data?.CartReadModel != null
)

const cartData = queryResult.data.CartReadModel

expect(cartData.id).to.be.equal(mockCartId)
expect(cartData.cartItems).to.have.length(1)
expect(cartData.cartItems[0]).to.deep.equal({
__typename: 'CartItem',
productId: mockProductId,
quantity: mockQuantity,
})
})

it('should retrieve list of items', async () => {
const fragment = gql`
fragment cart on CartReadModel {
id
cartItems {
productId
quantity
}
}
`
const limit = 1
let cursor: Record<'id', string> | undefined = undefined

for (let i = 0; i < limit; i++) {
const queryResult = await waitForIt(
() => {
return client.query({
variables: {
filterBy: { id: { eq: mockCartId } },
},
query: gql`
query ListCartReadModels($filterBy: ListCartReadModelFilter) {
ListCartReadModels(filter: $filterBy) {
items {
...cart
}
cursor
}
}
${fragment}
`,
})
},
(result) => result?.data?.ListCartReadModels?.items.length === 1
)

const currentPageCartData = queryResult.data.ListCartReadModels.items

cursor = queryResult.data.ListCartReadModels.cursor

if (cursor) {
if (process.env.TESTED_PROVIDER === 'AZURE' || process.env.TESTED_PROVIDER === 'LOCAL') {
expect(cursor.id).to.equal((i + 1).toString())
} else {
expect(cursor.id).to.equal(currentPageCartData[0].id)
}
}
expect(currentPageCartData).to.be.an('array')
expect(currentPageCartData.length).to.equal(1)
expect(cursor).to.not.be.undefined
expect(currentPageCartData[0].id).to.be.equal(mockCartId)
expect(currentPageCartData[0].cartItems).to.have.length(1)
expect(currentPageCartData[0].cartItems[0].productId).to.equal(mockProductId)
}
})

it('should apply modified filter by before hooks', async () => {
// We create a cart with id 'before-fn-test-modified', but we query for
// 'before-fn-test', which will then change the filter after two "before" functions
// to return the original cart (id 'before-fn-test-modified')
const variables = {
cartId: 'before-fn-test-modified',
productId: beforeHookProductId,
quantity: 1,
}
await client.mutate({
variables,
mutation: gql`
mutation ChangeCartItem($cartId: ID!, $productId: ID!, $quantity: Float!) {
ChangeCartItem(input: { cartId: $cartId, productId: $productId, quantity: $quantity })
}
`,
})
const queryResult = await waitForIt(
() => {
return client.query({
variables: {
cartId: 'before-fn-test',
},
query: gql`
query CartReadModel($cartId: ID!) {
CartReadModel(id: $cartId) {
id
cartItems {
productId
quantity
}
}
}
`,
})
},
(result) => result?.data?.CartReadModel != null
)

const cartData = queryResult.data.CartReadModel

expect(cartData.id).to.be.equal(variables.cartId)
})

it('should return exceptions thrown by before functions', async () => {
try {
await waitForIt(
() => {
return client.query({
variables: {
cartId: throwExceptionId,
},
query: gql`
query CartReadModel($cartId: ID!) {
CartReadModel(id: $cartId) {
id
cartItems {
productId
quantity
}
}
}
`,
})
},
(_) => true
)
} catch (e) {
expect(e.graphQLErrors[0].message).to.be.eq(beforeHookException)
expect(e.graphQLErrors[0].path).to.deep.eq(['CartReadModel'])
}
})
})
})

describe('projecting two entities', () => {
Expand Down

0 comments on commit dcd0714

Please sign in to comment.