Can an enum return description (string) in GraphQL?
Asked Answered
G

1

6

I'm struggling with my GraphQL API because I need to take advantage of Enums while keeping their full description in the frontend.

In short: I have different states for a product: "Has been sent", "Not sent yet", "Received". So this is the right place to use Enums:

enum ProductState {
  HAS_BEEN_SENT
  NOT_SENT_YET
  RECEIVED
}

But I need to display the proper strings on the frontend ("Has been sent", and not "HAS_BEEN_SENT").

I can't use a simple solution as "replace underscores with spaces and lowercase the string" because my API is not in English but in French (so I have accents and special characters).

Can't an Enum return a string? Or an object? I tried with directives but impossible to get it work...

Actually I don't care how it is written in the database (the uppercase or lowercase form) nor in the GraphQL API. I just need my client to access to the different product states in their "French" form.

Gasket answered 14/5, 2018 at 15:47 Comment(0)
P
7

As far as I know there is only one supported syntax for defining enums in GRAPHQL, which is the one you are using. You cannot associate an enum with a string value.

#NOTE: I would probably use a more descriptive name as opposed to ProductState
enum AllowedProductStatus { 
  HAS_BEEN_SENT
  NOT_SENT_YET
  RECEIVED
}

However, if you use apollo server you can use resolvers to add custom values.

const resolvers = {
  AllowedProductStatus: {
    HAS_BEEN_SENT: "Has been sent", 
    NOT_SENT_YET: "Not sent yet", 
    RECEIVED: "Received"
  }
};

Alternatively, If you simply wants to make it unique you could also use the directive @unique

type Product {
  status: String! @unique
}

Hope it was helpful.

Poppo answered 5/4, 2019 at 0:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.