Is there a way to avoid circular type dependencies in GraqhQL?

我只是一个虾纸丫 提交于 2019-12-12 02:14:37

问题


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.



来源:https://stackoverflow.com/questions/42447255/is-there-a-way-to-avoid-circular-type-dependencies-in-graqhql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!