Created
August 21, 2024 19:39
-
-
Save sbilello/6fcb1cc21dabc0626b79fdd386f330e6 to your computer and use it in GitHub Desktop.
Revisions
-
sbilello revised this gist
Aug 21, 2024 . No changes.There are no files selected for viewing
-
sbilello created this gist
Aug 21, 2024 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,67 @@ import { buildSchema, visit, Kind, GraphQLError, GraphQLObjectType, GraphQLList } from 'graphql'; const schemaString = ` type User { id: ID! name: String! friends: [User!]! } type Query { user(id: ID!): User allUsers: [User!]! } `; const schema = buildSchema(schemaString); const visitedTypes = new Set(); function detectCircularReferences(type, fieldPath = []) { if (visitedTypes.has(type.name)) { throw new GraphQLError( `Circular reference detected for type "${type.name}" at field path: ${fieldPath.join(".")}` ); } visitedTypes.add(type.name); if (type instanceof GraphQLObjectType) { const fields = type.getFields(); for (const fieldName in fields) { const field = fields[fieldName]; const fieldType = field.type; detectCircularReferences(fieldType.ofType || fieldType, [ ...fieldPath, fieldName, ]); } } if (type instanceof GraphQLList) { detectCircularReferences(type.ofType, [...fieldPath, "[]"]); } visitedTypes.delete(type.name); } try { const queryType = schema.getQueryType(); detectCircularReferences(queryType); console.log('No circular references detected in the schema.'); } catch (error) { if (error instanceof GraphQLError) { console.error(error.message); } else { console.error('An unexpected error occurred:', error); } }