GraphQL查询的类型定义

查询的类型定义

我会介绍在GraphQL中定义查询类型的方式。

首先,以下是GraphQL可使用的类型。

    • Schema

GraphQLSchema

Definitions

GraphQLScalarType
GraphQLObjectType
GraphQLInterfaceType
GraphQLUnionType
GraphQLEnumType
GraphQLInputObjectType
GraphQLList
GraphQLNonNull

Scalars

GraphQLInt
GraphQLFloat
GraphQLString
GraphQLBoolean
GraphQLID

接下来我会写使用方法。
例如,要获取的数据是

{
  "name": "sample name"
}

如果是类似这样的形式,可以写成如下所示。

import {
  GraphQLObjectType,
  GraphQLString,
} from 'graphql';

const NameType = new GraphQLObjectType({
  name: 'Name',
  fields: {
    name: { type: GraphQLString },
  },
});

export default NameType;

另外,可以通过使用”as”来将GraphQLString命名为任意的类型名称,就像StringType一样。

import {
  GraphQLObjectType as ObjectType,
  GraphQLString as StringType,
} from 'graphql';

const NameType = new ObjectType({
  name: 'Name',
  fields: {
    name: { type: StringType },
  },
});

export default NameType;

只需要一个选项:获得的数据是。

{
  "items": [
    {
      "name": "sample name",
      "age": 20
    },
    {
      "name": "sample name2",
      "age": 30
    }
  ]
}

在嵌套结构的情况下,可以使用GraphQLList来编写。

import {
  GraphQLObjectType as ObjectType,
  GraphQLString as StringType,
  GraphQLInt as IntType,
  GraphQLList as ListType,
} from 'graphql';

const NameType = new ObjectType({
  name: 'NameType',
  fields: {
    name: { type: StringType },
    age: { type: IntType },
  },
});

const NameListType = new ObjectType({
  name: 'NameListType',
  fields: {
    items: {
      type: new ListType(NameType),
      resolve(list) {
        return list.items;
      },
    },
  },
});

export default NameListType;

以下是参考:

参考:

React Starter Kit
graphql/type | API 参考文档

广告
将在 10 秒后关闭
bannerAds