GraphQL SPQR扩展输入对象的变异参数

时间:2018-08-16 08:52:32

标签: java graphql graphql-java graphql-spqr

能够扩展现有类型非常出色,因为它可以 代码的模块化和特权分离。我已经找到了有关如何在查询中扩展对象输出的好例子(见下文),但没有扩展给定对象具有的输入内容的好方法。

为便于说明,我们假设有一个类User

class User {
    String firstName;
    String lastName;
}

如果声明一个bean,我们可以进行如下查询:

/**
 * This is valid and can be invoked using
 * query {
 *     user(id=1) {
 *         firstName
 *         lastName
 *     }
 * }
 */
@GraphQLQuery(name = "user")
public User getUser(@GraphQLArgument(name = "id") long id) {

}

然后在另一个bean bean中,我们可以扩展User

    /**
     * <<this currently works>>
     * So now this query becomes valid
     * query {
     *     user(id=1) {
     *        firstName
     *        lastName
     *        address {    <-- this is not a top level, but extends User
     *            streetNam
     *        }
     *     }
     * }
     */
    @GraphQLQuery(name = "address")
    public Address getUserAddress(@GraphQLContext User) {

    }

对于突变,我们可以定义:

    /**
     * <<this currently works>>
     * This can be invoked using:
     * mutation {
     *     addUser(user :{
     *         firstName: "John"
     *         lastName: "Smith"
     *      })
     *      fistName
     * }
     */
     @GraphQLMutation(name = "addUser")
     public User addUser(@GraphQLArgument(name = "user") User user) {

     }

现在,我正尝试以添加address的方式添加查询内容,但添加User的输入参数。 在某些bean中仍然声明了以下内容。

    /**
     * << this is what I am trying to achieve>>
     * I want to be able to invoke the following query and not having to declare 'Address' inside of 'User' class.
     * mutation {
     *  addUser(user :{
     *      firstName: "John"
     *      lastName: "Smith"
     *      address: {    <-- being able to pass address as argument now, and be part of user.
     *          streetName: "1 str"
     *      }
     *      })
     *        fistName
     *  }
     */
    // e.g. something like ...
    @GraphQLInputField(name = "address")
    public void addAddressToUser(@GraphQLContext User user, @GraphQLArgument Address address) {

    }

1 个答案:

答案 0 :(得分:0)

我想出了一种当前可以执行此操作的方法,但这需要一些努力。
我正在使用GraphQL-SPQR 0.9.8(几天之内就会发布)。您可以在0.9.7中实现相同的目标,但它的人机工程学要少一些。

@Test
public void testSchema() {
    GraphQLSchema schema = new GraphQLSchemaGenerator()
            // Ignore extra fields (like "address") when deserializing
            .withValueMapperFactory(JacksonValueMapperFactory.builder()
                    .withConfigurers(conf -> conf.getObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false))
                    .build())
            .withInputFieldBuilders((conf, defaults) -> defaults.prepend(new UserInputBuilder(defaults.getFirstOfType(JacksonValueMapper.class))))
            .withArgumentInjectors(new UserInjector())
            .withOperationsFromSingleton(new TestService())
            .generate();

    GraphQL exe = GraphQL.newGraphQL(schema).build();
    ExecutionResult result = exe.execute("{user(in: {name: \"A. Man\", address: {type: \"home\", street: {name: \"Fakestreet\", number: 123}}}) {name, street {number}}}");
}


public class TestService {

    @GraphQLQuery //or mutation, no difference
    public User user(User in) {
        return in;
    }
}

// Redefines how User objects are deserizalized
public static class UserInjector extends InputValueDeserializer {

    @Override
    public Object getArgumentValue(ArgumentInjectorParams params) {
        User user = (User) super.getArgumentValue(params);
        Map<?, ?> rawInput = (Map<?, ?>) params.getInput();
        Address address = params.getResolutionEnvironment().valueMapper.fromInput(rawInput.get("address"), GenericTypeReflector.annotate(Address.class));
        // Preprocess the address in any way you need, here I just extract the street
        user.setStreet(address.getStreet());
        return user;
    }

    @Override
    public boolean supports(AnnotatedType type) {
        return GenericTypeReflector.isSuperType(User.class, type.getType());
    }
}

//Redefines the way User input type is mapped
public static class UserInputBuilder implements InputFieldBuilder {

    private final InputFieldBuilder original;

    public UserInputBuilder(InputFieldBuilder original) {
        this.original = original;
    }

    @Override
    public Set<InputField> getInputFields(InputFieldBuilderParams params) {
        Set<InputField> fields = original.getInputFields(params);
        // Add the extra "address" field you want
        fields.add(new InputField("address", "User's home address", GenericTypeReflector.annotate(Address.class), null, null));
        return fields;
    }

    @Override
    public boolean supports(AnnotatedType type) {
        return GenericTypeReflector.isSuperType(User.class, type.getType());
    }
}

public class User {

    private String name;
    private Street street;

    public User(String name, Street street) {
        this.name = name;
        this.street = street;
    }

    public String getName() {
        return name;
    }

    public Street getStreet() {
        return street;
    }

    @GraphQLIgnore //can be filtered out in a different way, without touching this class
    public void setStreet(Street street) {
        this.street = street;
    }
}

public class Address {

    private Street street;
    private String type;

    public Address(Street street, String type) {
        this.street = street;
        this.type = type;
    }

    public Street getStreet() {
        return street;
    }

    public String getType() {
        return type;
    }
}

也就是说,在Jackson(或Gson,无论您使用什么)中注册自定义解串器,而跳过自定义ArgumentInjector,可能会更容易。