LoginSignup
4
4

More than 5 years have passed since last update.

GraphQL-クエリの型定義

Last updated at Posted at 2018-03-31

クエリの型定義

GraphQLにおけるクエリの型定義の書き方をご紹介します。

まず、GraphQLで使用できる型は以下になります

  • Schema
    • GraphQLSchema
  • Definitions
    • GraphQLScalarType
    • GraphQLObjectType
    • GraphQLInterfaceType
    • GraphQLUnionType
    • GraphQLEnumType
    • GraphQLInputObjectType
    • GraphQLList
    • GraphQLNonNull
  • Scalars
    • GraphQLInt
    • GraphQLFloat
    • GraphQLString
    • GraphQLBoolean
    • GraphQLID

次に使い方を書いていきます。
例えば取得するデータが

{
  "name": "sample name"
}

のような形の場合、次のように書けます。

NameType.js
import {
  GraphQLObjectType,
  GraphQLString,
} from 'graphql';

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

export default NameType;

また、GraphQLString as StringTypeのように、asで繋ぐことで型を任意の名称に出来ます。

NameType.js
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を用いて書くことができます。

NameListType.js
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 Reference

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4