How can I put special characters in an enum value in apollo graphQL server?

Viewed 1500

I have a problem with the enum type in apollo-graphQL, I'm using apollo-server in nodejs. The problem is that I can't use strings with a value like image/jpeg or svg+xml. It's giving me errors that these values can't be parsed as enums.

Enum values

enter image description here

Can somebody tell me how to fix this ?

1 Answers

Unfortunately, the answer is that you cannot. According to the GraphQL spec, an enum is defined as

Name but not true or false or null

"Name" here refers to this definition, which defines a "Name" with the regular expression

/[_A-Za-z][_0-9A-Za-z]*/

This means that enums (which are defined as "names values") can only have letters, numbers, or underscores, and the first character can't be a number. Additionally, the spec recommends that you use "all caps", which I read to mean "CONSTANT_CASE".

If an enum really is what you want, to follow the recommendation of the spec, you "should" use

enum ImageMimeTypes {
  IMAGE_APNG
  IMAGE_AVIF
  IMAGE_GIF
  IMAGE_JPEG
  IMAGE_PNG
  IMAGE_SVG_XML
  IMAGE_WEBP
}

though I personally like to name my enums as singular constant case, as well -- just so it's less a surprise of what it represents -- so I'd probably call it IMAGE_MIME_TYPE.

Related