Created
August 21, 2024 19:39
-
-
Save sbilello/6fcb1cc21dabc0626b79fdd386f330e6 to your computer and use it in GitHub Desktop.
Draft Dependency Check Validator
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 characters
| 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); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment