Skip to content Skip to sidebar Skip to footer

Javascript Circular Dependency In Graphql Code

I am new to Javascript and don't know how to solve this problem. I am creating a GraphQL service to provide query to a database, I would like to define three type: Person, Company

Solution 1:

Normally you wouldn't define a special Relationship type. In GraphQL, relationships among types are defined in the types themselves.

As examples, within your personType, you can have a field called companies, which resolves to a list of companies (companyTypes) that person is part of. In your companyType, you could similarly define a field people that would resolve to a list of personTypes.

This would give you essentially a many-to-many relationship between the two types, which it sounds like is defined in your database.

A personType in this style might look like:

personType=newGraphQLObjectType({name:'Person',fields:()=>({id: {
      type:newGraphQLNonNull(GraphQLInt),
    },companies: {
      type:newGraphQLList(companyType),
      resolve:person=>dbHandler.getAssociatedCompanies(person.id),
      },},}),});

As for circular dependency issues, notice above that rather than using an object literal for fields, you can instead use a function which returns the object, which will not cause any problems (though your linter might complain).

I would definitely suggest reading through the GraphQL Types as well and making sure you've chosen appropriate types for your fields. Once you're comfortable enough you will definitely want to investigate GraphQLInterfaceType, which allows you to define common fields other types can implement. Ultimately it's probably a better route to define your types separately and have them implement an interface rather than having a generic objectType.

Also note that resolveType probably doesn't do what you think it does. From the GraphQL Types: "[resolveType is] a function to determine which type is actually used when the field is resolved." You see that on GraphQL types that can be composed of multiple types, like GraphQLInterfaceType and GraphQLUnionType.

The Star Wars example helped me wrap my head around this stuff.

Solution 2:

Try to restructure your GraphQL endpoints to something like this

type Person: {
  employers: [Company],
  ...personAttributes
}

type Company: {
  employees: [Person],
  ...companyAttributes
}

In the database schema (I guess you're using a relational database) you'll need 3 tables:

  • Persons
  • Companies
  • Relationships

This article explains how to model many-to-many relationships like the one you have.

Note: If one person can only work at one company at a time, the schema is much simpler.

Post a Comment for "Javascript Circular Dependency In Graphql Code"