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); } }