首页 > 解决方案 > 如何在 GraphQL 中为键值定义枚举

问题描述

如何在 GraphQL 模式中定义枚举键?我期待的响应如下所示

 businessByState: { 
   MO: ["VALUE1", "VALUE2"],
   CA: ["VALUE1", "VALUE3", "VALUE4]
 }

我知道我可以为状态值定义枚举,但仍然想知道如何定义枚举,以便键值只能是 2 个字母的状态缩写?

标签: graphqlapollo-server

解决方案


在 GraphQL 中,必须显式定义 Object 类型的每个字段。例如:

type BusinessByState {
  AL: [String!]!
  AK: [String!]!
  AZ: [String!]!
  # and so on...
}

没有用于基于某些输入(如现有枚举)定义具有相同类型的多个字段的语法。

如果您的 typeDefs 只是一个字符串,您可以使用字符串模板来节省一些输入,假设您有某种状态缩写数组:

const states = ['AL', 'AK', 'AZ', /** and so on **/]
const typeDefs = `
  enum STATES {
    ${states.join('\n')}
  }

  type BusinessByState {
    ${states.map(state => `${state}: [String!]!`).join('\n')}
  }
`

推荐阅读