Skip to content

Instantly share code, notes, and snippets.

@sbilello
Created August 21, 2024 19:39
Show Gist options
  • Select an option

  • Save sbilello/6fcb1cc21dabc0626b79fdd386f330e6 to your computer and use it in GitHub Desktop.

Select an option

Save sbilello/6fcb1cc21dabc0626b79fdd386f330e6 to your computer and use it in GitHub Desktop.

Revisions

  1. sbilello revised this gist Aug 21, 2024. No changes.
  2. sbilello created this gist Aug 21, 2024.
    67 changes: 67 additions & 0 deletions gistfile1.txt
    Original 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);
    }
    }