0no-co / gql.tada

🪄 Magical GraphQL query engine for TypeScript
https://gql-tada.0no.co
MIT License
2.44k stars 34 forks source link

RFC: Allow automatic Enums #311

Closed chamatt closed 1 month ago

chamatt commented 1 month ago

Summary

Enums is a feature of graphql, and for most codebases the enum type is widely used within the codebase for a lot of things.

Let's say we have the following Enum in our graphql schema:

enum AnimalType {
  Dog = "DOG",
  Cat = "CAT",
  Bird = "BIRD"
}

Then we want to use it in our app to perform a calculation:

const getSound = (animalType: AnimalType) => {
    if(animalType === AnimalType.Dog) return "bark"
    if(animalType === AnimalType.Cat) return "meow"
    if(animalType === AnimalType.Bird) return "chirp"
}

But because gql.tada transforms the enums into ("DOG" | "CAT" | "BIRD"), this code no longer works. (Argument of type '"DOG"' is not assignable to parameter of type 'AnimalType'.ts(2345))

And we would either have to refactor it to:

const getSound = (animalType: typeof AnimalType[keyof typeof AnimalType]) => {
    if(animalType === AnimalType.Dog) return "bark"
    if(animalType === AnimalType.Cat) return "meow"
    if(animalType === AnimalType.Bird) return "chirp"
}

Or give up the enum, and grab it directly from a specific graphql query ResultOf<>, which would kill the reusability of a shared function.

I've seem a topic about this, but the solution given was to manually add the enums to the scalars object, but since it's generated by the schema file, someone would have to remember to add/remove an enum everytime a new one is created.

Proposed Solution

Create a configuration to keep enums as is, instead of turning into a string union

kitten commented 1 month ago

Sorry, I'll post the other threads here later that are related to this, but we've explained in other discussions/issues why this isn't done.

tl;dr enums aren't types and we don't generate runtime code. Even if we did, enums are a poor choice for GraphQL enums or in general for API values. Sorry 😅❤️

httpiga commented 1 month ago

image