简体   繁体   English

如何在graphQl中使用具有确定值的自定义类型

[英]How to make custom type with definite value in graphQl

This is the first time I am using graphQL, I have two questions related to it. 这是我第一次使用graphQL,与此有两个问题。

I have vaguely gone through the docs and was building something of my own. 我隐约地浏览了文档,并正在构建自己的东西。

So, My setup right now is very simple. 因此,我现在的设置非常简单。 In the starting point of my app, I have something like this 在我的应用程序的起点,我有这样的东西

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")
});

And my Schema looks like this 我的模式看起来像这样

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
      }
    })
  })

In my above code snippet, Inside UserType I want my GenderType to be either male or female. 在我上面的代码片段中,“内部UserType我希望我的GenderType是男性还是女性。 How would write my custom type such that it only accepts value 'male' or 'female'? 如何编写我的自定义类型,使其仅接受值“ male”或“ female”?

What you want to do can be achieved with both Scalar Types and Enum Types . 标量类型枚举类型都可以实现。 In your case you probably want to go with an enum because you have a small finite list of allowed values. 在您的情况下,您可能想使用一个枚举,因为您只有一小部分有限的允许值。 Using the Enum Type will show the allowed values in the documentation in GraphiQL. 使用Enum Type将在GraphiQL的文档中显示允许的值。 In most GraphQL APIs Enum values use all capital values but you could use the value property to transparently map the female value to FEMALE . 在大多数GraphQL API中,枚举值使用所有资本值,但您可以使用value属性将female值透明地映射到FEMALE This would for example allow you to treat the values as lower case on the server side (we do this a lot because the values come in lower case from our postgres). 例如,这将允许您在服务器端将这些值视为小写(我们经常这样做,因为值来自我们的postgres小写)。 Here some code for inspiration: 这里有一些启发性的代码:

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

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

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