Невозможно сохранить данные в слое gatsby graphql при создании исходного плагина - PullRequest
1 голос
/ 24 июня 2019

Я пытаюсь получить все видео канала YouTube, сгруппированные по плейлисту. Итак, сначала я выбираю все плейлисты, а затем снова загружаю соответствующие видео.

const fetch = require("node-fetch")
const queryString = require("query-string")

module.exports.sourceNodes = async (
  { actions, createNodeId, createContentDigest },
  configOptions
) => {
  const { createNode } = actions

  // Gatsby adds a configOption that's not needed for this plugin, delete it
  delete configOptions.plugins

  // plugin code goes here...
  console.log("Testing my plugin", configOptions)

  // Convert the options object into a query string
  const apiOptions = queryString.stringify(configOptions)
  const apiUrl = `https://www.googleapis.com/youtube/v3/playlists?${apiOptions}`

  // Helper function that processes a content to match Gatsby's node structure
  const processContent = content => {
    const nodeId = createNodeId(`youtube--${content.id}`)
    const nodeContent = JSON.stringify(content)
    const nodeData = Object.assign({}, content, {
      id: nodeId,
      parent: null,
      children: [],
      internal: {
        type: `tubeVideo`,
        content: nodeContent,
        contentDigest: createContentDigest(content)
      }
    })
    return nodeData
  }

  return fetch(apiUrl)
    .then(res => res.json())
    .then(data => {
      data.items.forEach(item => {
        console.log("item", item.id)
        //fetch videos of the playlist
        let playlistApiOption = queryString.stringify({
          part: "snippet,contentDetails",
          key: "AIzaSyDPdlc3ctJ7yodRZE_GfbngNBEYbdcyys8",
          playlistId: item.id,
          fields: "items(id,snippet(title,description,thumbnails),contentDetails)"
        })
        let playlistApiUrl = `https://www.googleapis.com/youtube/v3/playlistItems?${playlistApiOption}`
        fetch(playlistApiUrl)
          .then(res => res.json())
          .then(data => {
            data.items.forEach(video => {
              console.log("videos", video)
              // Process the video data to match the structure of a Gatsby node
              const nodeData = processContent(video)
              //  console.log(nodeData)
              // Use Gatsby's createNode helper to create a node from the node data
              createNode(nodeData)
            })
          })
      })
    })
}

Здесь создаются узлы для отдельных видео. Но не могу запросить эти узлы из хранилища graphql. то есть. данные не сохраняются в хранилище graphql

1 Ответ

0 голосов
/ 25 июня 2019

edit: Подожди, я просто понимаю, что это внутри цикла.Ваш sourceNodes не ждет разрешения извлечения внутри вашего цикла.В этом случае вам придется использовать что-то вроде Promise.all для разрешения каждого элемента в цикле.Код обновлен, чтобы отразить это.

  return fetch(apiUrl)
    .then(res => res.json())
    .then(data => {
      return Promise.all(
        data.items.map(item => {
          /* etc. */
          return fetch(playlistApiUrl)
            .then(res => res.json())
            .then(data => {
              data.items.forEach(video => {
                /* etc. */
                createNode(nodeData)
              })
            })
        )
      })
    })

Проверьте синтаксис async/await, это может упростить поиск проблем такого типа.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...