在GraphQL的响应中添加版权声明

我想要的东西是,在GraphQL的响应中不仅包含数据,还包含说明和其他各种信息。

我叫大崎博之。
当我试图使用GraphQL来公开开放数据时,我经常看到开放数据也必须包含版权声明的条件。
那么,如果要写在哪里,我只能想到将其写在API的返回结果中。
但是GraphQL API的默认返回格式中只包含”data”而已。

比如说,除了数据外,我们默认添加一个名为元数据的元素,其中包含版权信息,这样做怎么样呢?

{
  "data": {
    "location": {
      "Japanese": "高知市",
      "Prefecture": "",
      "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,可以将formatResponse作为server.start的选项进行配置。

  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": "",
      "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"
  }
}
bannerAds