如何在graphQl中使用具有确定值的自定义类型 [英] How to make custom type with definite value in graphQl

查看:97
本文介绍了如何在graphQl中使用具有确定值的自定义类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次使用graphQL,我有两个与此有关的问题.

This is the first time I am using graphQL, I have two questions related to it.

我隐约浏览了文档,并正在构建自己的东西.

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

我的架构看起来像这样

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

在上面的代码段中,在 UserType 内部,我希望我的 GenderType 是男性还是女性.怎么写我的自定义类型,使其只接受值"male"或"female"?

In my above code snippet, Inside UserType I want my GenderType to be either male or female. How would write my custom type such that it only accepts value 'male' or 'female'?

推荐答案

标量类型枚举类型.在您的情况下,您可能希望使用一个枚举,因为您只有一小部分有限的允许值.使用Enum Type将在GraphiQL的文档中显示允许的值.在大多数GraphQL API中,枚举值使用所有大写字母值,但您可以使用 value 属性将 female 值透明地映射到 FEMALE .例如,这将允许您在服务器端将这些值视为小写(我们经常这样做,因为这些值来自我们的postgres是小写的).这里有一些启发性的代码:

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. 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. 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). Here some code for inspiration:

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

这篇关于如何在graphQl中使用具有确定值的自定义类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆