Type-graphql: Advanced enum support

Created on 3 Mar 2018  路  8Comments  路  Source: MichalLytek/type-graphql

Support for enums with descriptions and depreciations.

API Draft

@EnumType({ description: "All posible directions of moves the on grid" })
class DirectionEnumType {
  @EnumValue({ description: "Up to the sky!" })
  Up: string;

  @EnumValue()
  Down: string;

  @EnumValue({ deprecationReason: "Use `Down` instead" })
  Bottom = this.Down;

  @EnumValue() 
  Left: string;

  @EnumValue() 
  Right: string;
}

// we don't use `DirectionEnumType` class on runtime, so only export "real" enum `Direction`
export const Direction = createEnum(DirectionEnumType);


// usage in definitions
@ObjectType()
class Movement {
  @Field(type => Direction)
  direction: Enum<typeof Direction>;
}

// usage in resolvers
const mov = new Movement();
mov.direction = Direction.Right;
mov.direction = "Left";

switch (mov.direction) {
  case Direction.Right:
    console.log("right!");
    break;
  case Direction.Left:
    console.log("left!");
    break;
  // etc.
}

Enhancement Solved

Most helpful comment

Since we have ObjectType(), why don't you simply call it EnumType(), rather than GraphQLEnumType(). Just for the sake of consistency...

All 8 comments

Since we have ObjectType(), why don't you simply call it EnumType(), rather than GraphQLEnumType(). Just for the sake of consistency...

@Veetaha 馃憤 We have InterfaceType() too which we must apply on a class, not an interface.

@bbenoist Because you declare GraphQLInterfaceType and you can't apply decorators on an TS interface?

@MichalLytek Yes I know it's not possible to apply decorators on TS interfaces and I understand why ;)

I was just supporting the idea that we should use a @EnumType decorator in our _end-user_ code, not @GraphQLEnumType as for @InterfaceType - which I didn't know was named GraphQLInterfaceType in the underlying code of type-graphql.

Sorry for the useless noise, I didn't realized that you already agreed with @Veetaha by 馃憤 his comment.

was named GraphQLInterfaceType in the underlying code of type-graphql

graphql-js has all the types prefixed GraphQLScalar, GraphQLObjectType, GraphQLInputObjectType, etc. In the first releases I sticked to that convention but later switched to shorter names. EOT 馃槃

I love this new enum API.

This feature is implemented by #714.

Maybe in v2.0 there will be support for more declarative, class-based approach of defining enums with description and deprecation reasons, like in the first post.

@MichalLytek Thank you for the update. I'm looking forward to v2.0!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

laukaichung picture laukaichung  路  3Comments

memark picture memark  路  3Comments

glentakahashi picture glentakahashi  路  3Comments

MichalLytek picture MichalLytek  路  3Comments

avkonst picture avkonst  路  3Comments