Is there a way to avoid circular type dependencies

2019-09-11 19:33发布

问题:

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.

回答1:

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.