0

I have a use case to allow only a certain set of enum values into input for a mutation / display. I'm not quite sure how to best handle this.

Given the following:

import gql from 'graphql-tag';

export default gql`
  enum DayOfWeek {
    MONDAY
    TUESDAY
    WEDNESDAY
    THURSDAY
    FRIDAY
    SATURDAY
    SUNDAY
  }
`;

I'd like to limit the selection values at certain locations of the schema.

I was hoping that I could do something like:

import gql from 'graphql-tag';

export default gql`
  union Weekday = MONDAY | TUESDAY | WEDNESDAY | THURSDAY | FRIDAY
  union Weekend = SATURDAY | SUNDAY

The schema never seems to validate. I've also tried referencing these as DayOfWeek.MONDAY, etc, to no avail.

Is there a way to mimic this functionality?

Scott
  • 9,458
  • 7
  • 54
  • 81

1 Answers1

1

Short answer: no. At the moment, GraphQL only supports using object types for unions and there is no syntax for accessing individual enum values of an existing enum type. You need to explicitly create three separate enum types:

enum Weekday {
  MONDAY
  TUESDAY
  WEDNESDAY
  THURSDAY
  FRIDAY
}

enum Weekend {
  SATURDAY
  SUNDAY
}

enum DayOfWeek {
  MONDAY
  TUESDAY
  WEDNESDAY
  THURSDAY
  FRIDAY
  SATURDAY
  SUNDAY
}
Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
  • Thanks, that was how I read the documentation as well. Any known hooks to help verify that Weekday and Weekend are 'valid'? My best thought currently is writing custom code in the app startup to verify things are in a good state. – Scott Jul 06 '20 at 14:56
  • 1
    You could write a custom validation rule. Example rules can be found [here](https://github.com/graphql/graphql-js/tree/master/src/validation/rules). A brief explanation of the visitor pattern employed by the validation rules can be found [here](https://graphql.org/graphql-js/language/#visit). – Daniel Rearden Jul 06 '20 at 15:11