きみはねこみたいなにゃんにゃんなまほう

ねこもスクリプトをかくなり

GraphQL Schema Language で Directive を定義する

(=˘ ꒳ ˘=) GraphQL Schema Language 内で Directive を定義する方法を探していたのですが、公式にドキュメントが見つからなかったのでメモしておきます...

directive @myDirective(age: Int) on FIELD

のように Directive を定義できるようです。

import { graphql, buildSchema } from 'graphql'

const schema = buildSchema(`
  directive @myDirective(age: Int) on FIELD
  
  type Query {
    hello: String!
  }
`)

const query = `{ hello @myDirective(age: 12) }`

const rootValue = { hello: 'world' }

graphql(schema, query, rootValue).then(console.log, console.error)

のように実行できます。

見つけた背景

GraphQLDirective を使って定義した後にそれを printSchema するとどうなるか興味本位で試していて見つけました。

import {
  graphql,
  GraphQLSchema,
  GraphQLDirective,
  GraphQLObjectType,
  GraphQLString,
  printSchema,
} from 'graphql'

const myDirective = new GraphQLDirective({
  name: 'myDirective',
  locations: ['FIELD'],
  args: {
    age: { type: GraphQLString },
  },
})

const schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'rootQuery',
    fields: {
      hello: { type: GraphQLString },
    },
  }),
  directives: [myDirective],
})

console.log(printSchema(schema))

これを実行すると

schema {
  query: rootQuery
}

directive @myDirective(age: String) on FIELD

type rootQuery {
  hello: String
}

と表示されます。Directives はてっきり GraphQL Schema Language の対象外かと思っていたのですが定義できたのですね。

私が見つけられていないだけで、公式の記述はどこかにあるのでしょうか。

そして定義ができることと処理を実装できることはまた別なのですよね... Directive の処理をいい感じに定義する方法はあるのでしょうか...