1

能够扩展现有类型非常棒,因为它允许代码模块化和权限分离。我找到了关于如何在查询中扩展对象输出的好例子(见下文),但没有很好的方法来扩展给定对象的输入。

为了这个例子,假设我们有一个 class 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) {

    }
4

1 回答 1

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,无论您使用什么)中注册自定义反序列化器并跳过 custom 可能会更容易ArgumentInjector

于 2018-08-16T18:01:35.107 回答