LoginSignup
4
2

More than 5 years have passed since last update.

GraphQLでpixivのランキング取得するAPI

Last updated at Posted at 2017-09-08

graphqlの練習がてらexpressでpixivのランキングを返すgraphql APIサーバを書いてみました。
ここで遊べます。

デモ

https://gyazo.com/9738386ac8554007cc5ec8aba5bfcde2

akameco/graphql-pixiv-api

実装は、expressにexpress-graphqlミドルウェアを与えるだけです。
引数のオプションのgraphiqlというのはデモのアレですね。
すごく出来がいいです。

const graphqlHTTP = require('express-graphql')

app.use(
  '/graphql',
  graphqlHTTP({
    schema,
    rootValue: resolver,
    graphiql: true,
  })
)

あとは、引数にgraphqlのbuildSchemaで作成したスキーマを与えます。

const { buildSchema } = require('graphql')

const schema = buildSchema(`
type User {
  id: Int
  name: String
  account: String
  profileImageUrls: ProfileImageUrls
}
type ProfileImageUrls {
  medium: String
}
type Tag {
  name: String
}
type ImageUrls {
  squareMedium: String
  medium: String
  large: String
}
enum Mode {
  day
  week
  month
  day_male
  day_female
  week_original
  week_rookie
}
type MetaSinglePage {
  originalImageUrl: String
}
type Illust {
  id: Int
  title: String
  type: String
  caption: String
  tags: [Tag]!
  imageUrls: ImageUrls
  width: Int
  height: Int
  totalBookmarks: Int
  user: User
  tools: [String]
  metaSinglePage: MetaSinglePage
}
type Query {
  ranking(mode: Mode = "mode"): [Illust!]!
}
`)

module.exports = schema

非常に手軽ですね。
スキーマを除けば30行に満たないコードです。

書いた感じ、ルーティングを考えずに型だけを考えればいいので、気持ち実装のコストが低く、もしかすると普通にAPI書くより高速に作れるかもしれないという気持ちもしてきます。

気持ち

まだ良く見てないですが、flowとかtypescriptと型を共有したい場合どう書くのでしょうかね。
そのあたりの実装について知見がある人は、是非教えて下さい。
また、何か議論があれば、コメント欄またはtwitterまでお願いします。

注意

pixivから返却されるjsonについては、まあ非公開なので、完全なスキーマを書いてません。
こういうラッパする場合は、リクエストからgraphqlの型を自動生成するのが王道っぽい感じがします。
このあたりも今後の課題といった感じですね。

4
2
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
2