0

Consider the main SWAPI example for the reference implementation: https://github.com/graphql/swapi-graphql

// film.js
import PersonType from './person';

// person.js
import FilmType from './film';

That's all over the place. Are these circular deps an acceptable practice? Are there any good patterns for avoiding this? It seems bad to include problematic practices in the definitive demo for GraphQL.

Joseph Fraley
  • 1,360
  • 1
  • 10
  • 26
  • i think you need to add this in your question ||||| suppose i have `Type A`, `Type B` and `Type C`, `type a` depends upon `type b` and `type b` depends upon `type c` and `type c` depends upon `type a`, will the below answer method work. – parwatcodes Feb 27 '17 at 16:41
  • isnt the 3 dep circle just a special case of the 2 dep circle? – Joseph Fraley Feb 28 '17 at 17:34

1 Answers1

4

In case of GraphQL it is not bad practice, they even prepared a solution for this situation. If you define fields attribute of some type, you can declare it as a function

const User = new GraphQLObjectType({
    name: 'User',
    fields: () => ({
        id: { type: GraphQLID }
        // other attributes
    })
});

graphql-js uses method called resolveThunk in order to handle the fields attributes amongst other, and it's implementation is as follows

function resolveThunk<T>(thunk: Thunk<T>): T {
    return typeof thunk === 'function' ? thunk() : thunk;
}

As you can see, it checks if the thunk (fields in this case) is function. If it is, returns it's result, otherwise returns thunk itself.

piotrbienias
  • 7,201
  • 1
  • 28
  • 33
  • suppose i have `Type A`, `Type B` and `Type C`, `type a` depends upon `type b` and `type b` depends upon `type c` and `type c` depends upon `type a`, will the above method work. – parwatcodes Feb 26 '17 at 08:58