有没有一种方法可以避免GraqhQL中的循环类型依赖关系? [英] Is there a way to avoid circular type dependencies in GraqhQL?

查看:166
本文介绍了有没有一种方法可以避免GraqhQL中的循环类型依赖关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑参考实现的主要SWAPI示例: https://github.com/graphql/swapi -graphql

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

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

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

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

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

到处都是.这些通报部门是否可以接受?有什么好的方法可以避免这种情况?在GraphQL的最终演示中包含有问题的做法似乎很糟糕.

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.

推荐答案

对于GraphQL来说,这不是一个坏习惯,他们甚至为这种情况准备了解决方案.如果定义某种类型的fields属性,则可以将其声明为函数

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使用名为 resolveThunk 以便处理其他fields属性,其实现如下

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;
}

如您所见,它将检查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.

这篇关于有没有一种方法可以避免GraqhQL中的循环类型依赖关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆