Maintainable way to create multiple different Inputs
See original GitHub issueI’m trying to figure out how to create multiple different inputs from one Java class. Suppose I have a Car
class
@Data
public class Car {
private long ID;
private String brand;
private String model;
}
with three mutations: addCar
to add a new Car
, updateCar
to update a Car
and deleteCar
to delete a Car
. Using graphql-spqr I can write something like:
@GraphQLMutation
public Car addCar(Car car) {
...
}
@GraphQLMutation
public Car updateCar(Car car) {
...
}
@GraphQLMutation
public boolean deleteCar(Car car) {
...
}
This will result more or less in the following schema:
type Mutation {
addCar(car: CarInput) : Car
updateCar(car: CarInput) : Car
deleteCar(car: CarInput) : Boolean
}
type Car {
ID: Long
brand: String
}
type CarInput {
ID: Long
brand: String
}
However, the addCar
mutation does not need a CarInput
with an ID field, the deleteCar
only requires a CarInput
with an ID (it is easier to just use the ID as only input of the mutation but this is as an example). If for example the brand of the Car
can only be set at initialization, the CarInput
of the update should not include the brand.
I know I can create different inputs by extending the Car
class and then overriding the getters and setters and adding the @GraphQLIgnore
annotation, but with multiple different Inputs and more fields in the class, it quickly becomes cumbersome to create classes for each Input and overriding the getters and setters. Especially with a lot of fields in the base class. Also, changing fields in the base class takes a lot more time and is more error prone. My question is if there is an easier way to achieve multiple Inputs while keeping the java to a minimum?
Issue Analytics
- State:
- Created 5 years ago
- Reactions:2
- Comments:16 (7 by maintainers)
Top GitHub Comments
I am afraid I am still not following, most likely due to lack of documentation and examples, so I am probably misusing things. This is also the first project I am trying to do with GraphQL so this is all very new to me and I might be misunderstanding basic things…
Would you mind posting a simple example of how you would reuse the model object as input (take the above
Car
example) without making another DTO (UpdateCar
CreateCar
) or listing multiple@GraphQLArgument
parameters (requires copying fields from model)? Using onlyCar
as input parameter, but requiring id field for update and ignoring id for create?That is what I am trying to do, only one object model for all operations…
For similar purpose I’m using class inheritance, that way I can easily unify Query and Mutation classes. Example:
Of course it’s possible to have additional input classes for insert/update/delete (with @GraphQLIgnore adjusted fields), but it’s a little bit overkill IMO 😃 Generates schema like this: