【问题标题】:How to make custom type with definite value in graphQl如何在graphQl中制作具有确定值的自定义类型
【发布时间】:2019-12-06 14:26:11
【问题描述】:

这是我第一次使用 graphQL,我有两个相关的问题。

我已经模糊地浏览了这些文档,并且正在构建自己的东西。

所以,我现在的设置非常简单。在我的应用程序的起点,我有这样的东西

const express = require('express')
const app = express();
const graphqlHTTP = require("express-graphql")
const schema = require('./schema/schema')

app.use("/graphql", graphqlHTTP({
  schema: schema
}));

app.get('/', (req, res) => {
  res.json({"message": "Welcome to EasyNotes application. Take notes quickly. Organize and keep track of all your notes."});
});


//Listen to specific post 
app.listen(4000, () => {
  console.log("Listening for request on port 4000")
});

我的 Schema 看起来像这样

const graphql = require("graphql")

const { 
  GraphQLObjectType, 
  GraphQLString, 
  GraphQLSchema,
  GraphQLList,
  GraphQLID,
  GraphQLNonNull,
  GraphQLInt
  } = graphql


const GenderType = new GraphQLObjectType({
  name: 'Gender',
  fields: () => ({
    male: {

    }
  })
})


  const UserType = new GraphQLObjectType({
    name: 'User', // Importance of Name here
    fields: () => ({
      id: {
        type: GraphQLID
      },
      name: {
        type: GraphQLString
      },
      gender: {
        type: GenderType // Create custom type for it later
      }
    })
  })

在我上面的代码 sn-p 中,在 UserType 内部,我希望我的 GenderType 是男性或女性。如何编写我的自定义类型以使其仅接受值“男性”或“女性”?

【问题讨论】:

    标签: javascript node.js graphql


    【解决方案1】:

    Scalar TypesEnum Types 都可以实现您想要做的事情。在您的情况下,您可能想要使用枚举,因为您有一个小的有限允许值列表。使用枚举类型将在 GraphiQL 的文档中显示允许的值。在大多数 GraphQL API 中,枚举值使用所有大写值,但您可以使用value 属性将female 值透明地映射到FEMALE。例如,这将允许您在服务器端将值视为小写(我们经常这样做,因为值以小写来自我们的 postgres)。这里有一些灵感代码:

    const GenderType = new GraphQLEnumType({
      name: 'Gender',
      values: {
        FEMALE: {
          value: 'female'
        },
        MALE: {
          value: 'male'
        }
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-04
      • 1970-01-01
      • 2017-09-18
      • 2021-08-31
      • 2016-10-21
      • 2021-04-07
      • 2021-05-17
      • 2020-04-20
      相关资源
      最近更新 更多