1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

GraphQLでレスポンスにCopyright表示を追加

Last updated at Posted at 2018-12-02

やりたいこと=GraphQLのレスポンスにdataだけじゃなく説明とかいろいろ入れたい

Hiroyuki_OSAKIです。
GraphQLを使ってオープンデータを公開しようとしたら、オープンデータでもCopyright表示は必須、という条件をよく見ます。
そうするとどこに書かなければいけないのかというと、やはりAPIの返り値しか思いつきません。
でもGraphQL APIの返り値の形式はデフォルトではdataしか入っていません。

たとえばdata以外にmetaという要素をデフォルトで追記して、その中にcopyrightを入れるのはどうか。

{
  "data": {
    "location": {
      "Japanese": "高知市",
      "Prefecture": "Kōchi",
      "Country": "Japan"
    }
  },
  "meta": { //ここを追加したい
    "data_origin": "Wikipedia",
    "source_url": "https://en.wikipedia.org/wiki/List_of_cities_in_Japan",
    "licence_type": "https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License"
  }
}

どうやれば説明などメタデータを追加できるのでしょうか。

返り値はformatResponseで変更できる

formatResponseでメタデータ(コピーライトなど)を入れてみましょう。
apollo-serverやgraphql-yogaを使えば、server.startのオプションにformatResponseを入れるとよいです。

index.ts
  import { GraphQLServer } from 'graphql-yoga'
  const typeDefs = 'schema.graphql';
  const resolvers = { 
//略
  };

  const formatResponse = (response:any) => {
    var meta = {
      data_origin: "Wikipedia",
      source_url: "https://en.wikipedia.org/wiki/List_of_cities_in_Japan",
      licence_type: "https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License"
    }
    return {
      ...response,
      meta
    }
  }

  const server = new GraphQLServer({ typeDefs, resolvers })
  server.start({port: PORT, formatResponse}, () =>
    console.log(`Your GraphQL server is running now ...`),
  )

結果

お!できました!

{
  "data": {
    "location": { //ここには任意のデータが出ます
      "Japanese": "高知市",
      "Prefecture": "Kōchi",
      "Country": "Japan"
    }
  },
  "meta": { //ここから追加したメタデータが表示。
    "data_origin": "Wikipedia",
    "source_url": "https://en.wikipedia.org/wiki/List_of_cities_in_Japan",
    "licence_type": "https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License"
  }
}
1
1
1

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?