本文介绍了动态生成GraphQL架构支持的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能动态创建GraphQL架构?

Is it possible to dynamically create a GraphQL schema ?

我们将数据存储在mongoDB中,并且有可能出现新字段添加。我们不希望在mongoDB文档中对此新添加的字段进行任何代码更改。

We store the data in mongoDB and there is a possibility of new fields getting added. We do not want any code change to happen for this newly added field in the mongoDB document.

我们有没有办法动态生成架构?

Is there any way we can generate the schema dynamically ?

目前我们正在使用 java 相关项目(,)用于GraphQL开发。

Currently we are using java related projects (graphql-java, graphql-java-annotations) for GraphQL development.

推荐答案

您可以使用,它允许您根据服务类自动生成架构。在你的情况下,它看起来像这样:

You could use graphql-spqr, it allows you auto-generate a schema based on your service classes. In your case, it would look like this:

public class Pojo {

    private Long id;
    private String name;

    // whatever Ext is, any (complex) object would work fine
   private List<Ext> exts;
}

public class Ext {
    public String something;
    public String somethingElse;
}

据推测,您有一个包含业务逻辑的服务类:

Presumably, you have a service class containing your business logic:

public class PojoService {

    //this could also return List<Pojo> or whatever is applicable
    @GraphQLQuery(name = "pojo")
    public Pojo getPojo() {...}
}

要公开此服务,您只需执行以下操作:

To expose this service, you'd just do the following:

GraphQLSchema schema = new GraphQLSchemaGenerator()
                .withOperationsFromSingleton(new PojoService())
                .generate();

然后您可以触发查询,例如:

You could then fire a query such as:

query test {
    pojo {
        id
        name 
        exts {
            something
            somethingElse
        } } }

不需要任何奇怪的包装或自定义代码,也不需要牺牲类型安全性。适用于泛型,依赖注入或您在项目中可能拥有的任何其他爵士乐。

No need for strange wrappers or custom code of any kind, nor sacrificing type safety. Works with generics, dependency injection, or any other jazz you may have in your project.

完全披露:我是 graphql-spqr 。

这篇关于动态生成GraphQL架构支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 15:40