rishi
rishi

Reputation: 1842

Return different value for GraphQL enum in GraphQL-java

I am having following enum in the application.

public enum State {
    Started("newly started"),
    Hold("hold on"),
    Running("still running"),
    Stop("just stopped");

    private String value;

    State(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }
}

I have GraphQL schema as well for the same. I am using GraphQL-java library not GraphQL-spqr or GraphQL-java-tools. When I am returning this enum, it's name is being returned but I want to return it's assigned value i.e. "still running" for Running enum, "just stopped" for Stop enum etc. Is there any way in GraphQL-java?

Thanks in advance

Upvotes: 3

Views: 6568

Answers (2)

Vsevolod Golovanov
Vsevolod Golovanov

Reputation: 4206

You can map your GraphQL enums to Java enums however you'd like by providing custom mapping.
But GraphQL won't allow your enum values to have spaces. So you can either have enums without spaces, or you can declare your state fields as a String.

Or you could provide those strings as descriptions of enum values.

GraphQLEnumType.newEnum()
    .name("State")
    .value("Started", State.Started, "newly started")
    // ...
    .build();

Or via SDL:

enum State {
    "newly started"
    Started
}

Those descriptions can be queried with:

query {
  __type(name: "State") {
    enumValues {
      name
      description
    }
  }
}

Upvotes: 0

Daniel Rearden
Daniel Rearden

Reputation: 84687

it's name is being returned but I want to return it's assigned value

This is by design. From the spec:

Enums are not references for a numeric value, but are unique values in their own right. They may serialize as a string: the name of the represented value.

Enum values are serialized as their names. You may be able to provide an additional value that can be used internally during execution, but this value will not be used in the response.

Upvotes: 1

Related Questions