GraphQLで、電脳少女シロちゃんの`オホー報`を取得するスキーマを作ってみる


概要

GraphQLの入門がてら、シロちゃんのオホー報を取得するスキーマを作るまで

オホー報とは

電脳少女シロちゃんが、自身のTwitterにて呟くやんごとなき告知


シロちゃんかわいいよシロちゃん

やってみる

GraphQLサーバー構築

npm init
npm i express express-graphql
vi server.js
server.js
const express = require('express')
const expressGraphQl = require('express-graphql')
const {buildSchema} = require('graphql')

const schema = buildSchema(`
  type Query {
    hoge : String
  }
`)

const app = express()
app.use('/graphql', expressGraphQl({
  schema,
  rootValue : {
   hoge : () => 'hello! graphql!'
  },
  graphiql : true
}))

app.listen(80, () => console.log('running graphql server.'))

node server.jsでGraphQLサーバーが立ち上がります
http://<<ホスト名>>/graphqlにブラウザでアクセスすると、GraphQLサーバー及びGraphQLクライアント(web)アプリが立ち上がっている事が確認出来ます

あっさりGraphQLサーバーが構築出来ましたねexpress-graphqlやりおるマン

シロちゃんのツイートを取得

  • twitter APIにアクセスするための認証情報を設定
authInfo.json
{
  "consumer_key" : "your consumer_key",
  "consumer_secret" : "your consumer_secret",
  "access_token_key" : "your access_token_key",
  "access_token_secret" : "your access_token_secret"
}

  • node moduleのTwitterクライアントでツイートを取得
npm i twitter
twitter.js
const Twitter = require('twitter')
const AuthInfo = require('./authInfo')
const client = new Twitter(AuthInfo)

module.exports.getTweet = ({target}) => {
  const param = {
    screen_name : target, // ★twitterで見かける『@』から始まるアレ
    count : 200
  }

  return new Promise((resolve, reject) => {
    client.get('statuses/user_timeline', param, (error, tweets, response) => {
      if(error) {
        return reject(error, response)
      }

      resolve(tweets, response)
    })
  })
}

const twitter = require('./twitter.js')

twitter
 .getTweet({// ツイート情報取得(最大直近200件)
  target : 'SIROYoutuber' // ★twitterで見かける『@』から始まるアレ
 })
 .then(tweets => console.table(tweets)) // ツイート情報ログ表示(取得に成功した場合)

オホー報を取得するスキーマを定義

server.js
const express = require('express')
const expressGraphQl = require('express-graphql')
const {buildSchema} = require('graphql')

const twitter = require('./twitter/twitter.js')

const schema = buildSchema(`
  type Query {
    ohoHou : [String]
  }
`)

const ohoHou = twitter // ツイート情報(配列、構造体)から【オホー報】を抽出
                .getTweet({target : 'SIROyoutuber'})
                .then(tweets => tweets.map(tweet => tweet.text))
                .then(texts => texts.filter(text => text.match(/【オホー報】/)))

const app = express()
app.use('/graphql', expressGraphQl({
  schema,
  rootValue : { ohoHou },
  graphiql : true
}))

app.listen(80, () => console.log('running graphql server.'))

サーバーをスタート

node server.js

クライアントアプリから『オホー報クエリ』(ohoHou)を発行してみましょう

query
{
 ohoHou
}


無事取得出来ました!

やってみて(技術的な感想)

rootValueの返却値に、Promiseな値をそのまま定義出来てちょっと感動

  • 普通(?)の値はこう
const schema = buildSchema(`
  type Query {
    hogeText : String
  }
`)

const app = express()
/** 
   {
    hogeText
   }
   クエリを発行すると // クエリ
   'hogehoge!'が取得される
**/
app.use('/graphql', expressGraphQl({
  schema,
  rootValue : { 
   hogeText : () => 'hogehoge!'
  },
  graphiql : true
}))
  • Promise型な値はこう引き渡す
const schema = buildSchema(`
  type Query {
    hogeText : String
  }
`)

const app = express()
/** 
   {
    hogeText // クエリ
   }
   クエリを発行すると 
   'Promise hogehoge!'が取得される
**/
app.use('/graphql', expressGraphQl({
  schema,
  rootValue : { 
   hogeText : new Promise((resolve, reject) => resolve('Promise hogehoge!'))
  },
  graphiql : true
}))

javascriptお馴染みである非同期取得した値も、非常に直観的に扱えてgoodです!

やってみて(雑多な感想)

  • 直近200件のツイートからしか取得が出来なかった。twitter apiの仕様(?)なのでどうしようもないんだろうかという若干の消化不良感
    • その辺りもあまり詳しくないので、 ご存知の方はご指摘頂けると幸いです
  • 単純すぎて、GraphQLでやる意味が正直薄い要件だったな、とは思ってる…
  • ただこんなチャチい物でも、実際に手を動かして作ってみる事によって、これがGraphQLか!感を軽く掴めた気がするシロちゃんのオホー報は為になるなぁ!
    • 今回を足掛かりに、次はもっと(GraphQLの旨味を活かせるような)応用的な某かを作りたいと思った
      • GraphQL面白い!

ソース

githubに上げてます