我正在尝试获取按播放列表分组的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存储中
答案 0 :(得分:0)
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
语法,这可能会使查找此类问题更加容易。