Byeongin Yoon
Byeongin Yoon

Reputation: 4037

How to use enum of Apollo-Server Graphql in resolver?

Environment

  1. apollo-server
  2. express
  3. typescript
  4. typeorm

Type Definitions (typeDefs.ts)

import { gql } from 'apollo-server-express';

const typeDefs = gql`

  enum Part {
    Hand, Arm, Waist, Bottom
  }

  type PartInfo {
    team: Int,
    tag: String,
    part: Part
  }

  ...

  type Query {
    ...
    hand(team: Int): PartInfo,
    ...
  }

`;
export default typeDefs;

Resolvers (resolvers.ts)

const resolvers = {
  Query: {
    ...
    hand: async (parent, args, context, info) => {
      const { team } = args;

      ...

      return {
        team,
        tag: "handTag",
        part: Part.hand
      }
    }
    ...
  },
};

export default resolvers;

Problem

I want to use enum Part of typeDefs.ts at resolvers.ts

I tried

return {
    team,
    tag: "handTag",
    part: "Hand"
}

also, but dosent work.

How to use enum type which is defined in typeDefs.ts at resolvers.ts ?

check please!

Upvotes: 1

Views: 1139

Answers (2)

Deepak Kumar
Deepak Kumar

Reputation: 162

You can add this as a constant(constant.ts) which can be used in schema and resolver as well. By doing so, you can change the values of the enum in one place in the future.

Constants.ts

 export const Parts = {
                    Hand: "hand",
                    Arm: "arm",
                    Waist: "waist",
                    Bottom: "bottom"
                  }
// values based on your requirements 

TypeDefs.ts

import { gql } from 'apollo-server-express';
import { Parts } from './constants'; // your relative file path


const typeDefs = gql`

  enum Part {
    ${Object.keys(Parts).join(" ")}
  }

  ...
`;
export default typeDefs;

Now the same constant can be used in your resolver function.

Resolver.ts

import { Parts } from './constants'; // your relative file path
    
const resolvers = {
  Query: {
    ...
    hand: async (parent, args, context, info) => {
      const { team } = args;

      ...

      return {
        team,
        tag: "handTag",
        part: Parts.hand
      }
    }
    ...
  },
};

export default resolvers;

Upvotes: 1

yeeharn
yeeharn

Reputation: 41

Besides Schema (typeDef.ts), you should also define your enum in resolver.

const resolvers = {
  Query: {
    ...
    hand: async (parent, args, context, info) => {
      const { team } = args;

      ...

      return {
        team,
        tag: "handTag",
        part: Part.hand
      }
    }
    ...
  },
  Part: {
    Hand: Part.hand
  }
};

export default resolvers;

Upvotes: 1

Related Questions