我正在尝试为API创建盖茨比源插件,该API要求通过客户端凭据身份验证服务对每个请求进行有效的访问令牌。
基于Gatsby源插件教程,我将如何首先保护auth令牌,然后再将其传递给我的API请求。
我在这里转圈,希望能对您有所帮助。
const fetch = require("node-fetch")
const queryString = require("query-string")
const axios = require("axios")
const oauth = require('axios-oauth-client')
exports.sourceNodes = (
{ actions, createNodeId, createContentDigest },
configOptions
) => {
const { createNode } = actions
// Gatsby adds a configOption that's not needed for this plugin, delete it
delete configOptions.plugins
// Helper function that processes a photo to match Gatsby's node structure
const processPhoto = photo => {
const nodeId = createNodeId(`pixabay-photo-${photo.id}`)
const nodeContent = JSON.stringify(photo)
const nodeData = Object.assign({}, photo, {
id: nodeId,
parent: null,
children: [],
internal: {
type: `PixabayPhoto`,
content: nodeContent,
contentDigest: createContentDigest(photo),
},
})
return nodeData
}
const getClientCredentials = oauth.client(axios.create(), {
url: "https://api.example.com/oauth2/token",
grant_type: 'client_credentials',
client_id: "9939492",
client_secret: "XXXXXX",
scope: "CMS",
});
const auth = getClientCredentials();
const options = {
headers: { 'Authorization': 'Bearer ' + auth.access_token }
}
// Convert the options object into a query string
const apiOptions = queryString.stringify(configOptions)
// Join apiOptions with the Pixabay API URL
const apiUrl = `https://pixabay.com/api/?${apiOptions}`
// Gatsby expects sourceNodes to return a promise
return (
// Fetch a response from the apiUrl
fetch(apiUrl, options)
// Parse the response as JSON
.then(response => response.json())
// Process the response data into a node
.then(data => {
// For each query result (or 'hit')
data.hits.forEach(photo => {
// Process the photo data to match the structure of a Gatsby node
const nodeData = processPhoto(photo)
// Use Gatsby's createNode helper to create a node from the node data
createNode(nodeData)
})
})
)
}