繁体   English   中英

如何在解析器中使用 Apollo-Server Graphql 的枚举?

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

环境

  1. 阿波罗服务器
  2. 表示
  3. typescript
  4. 打字机

类型定义 (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.ts)

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

      ...

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

export default resolvers;

问题

我想在resolvers.ts使用 enum 的typeDefs.ts的一部分

我试过了

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

也,但剂量工作。

如何使用在resolvers.tstypeDefs.ts中定义的枚举类型?

请检查!

除了 Schema (typeDef.ts),您还应该在解析器中定义您的枚举。

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;

您可以将其添加为常量(constant.ts),也可以在架构和解析器中使用。 通过这样做,您将来可以在一个地方更改枚举的值。

常量.ts

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

类型定义.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;

现在可以在您的解析器 function 中使用相同的常量。

解析器.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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM