じまろぐ

めめ

GridsomeでGraphCMSのデータを使う

gridsome.server.js

const axios = require('axios')

module.exports = function (api) {
  api.loadSource(async ({ addContentType }) => {
    const res = await axios.get(process.env.GRIDSOME_GRAPHCMS_ENDPOINT, {
      params: {
        query: `query {
          posts {
            id
            title
            slug
            date
            cover {
              thumbnail: url(transformation: {
                image: {
                  resize: {
                    width: 200
                    height: 200
                    fit: crop
                  }
                }
              })
              url
            }
            tags {
              name
            }
            category {
              name
            }
            body {
              html
            }
          }
        }`
      },
      headers:
        {
          Authorization: process.env.GRIDSOME_GRAPHCMS_TOKEN
        }
    })
    const {posts} = res.data.data
    if (posts) {
      const contentType = addContentType({
        typeName: 'Posts',
        route: '/posts/:slug'
      })
      posts.forEach(post => {
        contentType.addNode(post)
      })
    }
  })
}

addNode に追加したやつから自動でschemaを作ってくれて page-query とかから取得できるようになる。