下面我有两个获取请求,第一个请求是一个 oauth 请求并返回一个身份验证令牌,因此我可以运行第二个请求,该请求使用该令牌并从我的无头 cms(squidex)返回内容(Graphql)。
目前,第二个请求仅适用于一个端点,因为 cms 一次只能查询一个模式内容,我如何重构第二个单数请求,以便我可以有多个请求,每个请求都从不同的模式中获取数据,每个请求都创建一个 gatsby 节点。
就像是:
const endpoints = ['endpoint1','endpoint2','endpoint3'];
endpoints.map(endpoint => {
//do all the fetches in here and build a gatsby node for each of them
});
const path = require('path');
require('dotenv').config({
path: `.env.${process.env.NODE_ENV}`,
});
require('es6-promise').polyfill();
require('isomorphic-fetch');
const crypto = require('crypto');
const qs = require('qs');
exports.sourceNodes = async ({ actions }) => {
const { createNode } = actions;
// This is my first request
let response = await fetch(process.env.TOKEN_URI, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: qs.stringify({
grant_type: 'client_credentials',
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
scope: 'squidex-api',
}),
});
let json = await response.json();
// I have to wait for this first request to run the next one
response = await fetch(`${process.env.API_URI}${process.env.END_POINT}`, {
method: 'GET',
headers: {
Authorization: `${json.token_type} ${json.access_token}`,
},
});
// I want to create a loop here an pass an array of different END_POINTS each doing a fetch then returning a response and building a gatsby node like the below.
json = await response.json();
// Process json into nodes.
json.items.map(async datum => {
const { id, createdBy, lastModifiedBy, data, isPending, created, lastModified, status, version, children, parent } = datum;
const type = (str => str.charAt(0).toUpperCase() + str.slice(1))(process.env.END_POINT);
const internal = {
type,
contentDigest: crypto.createHash('md5').update(JSON.stringify(datum)).digest('hex'),
};
const node = {
id,
createdBy,
lastModifiedBy,
isPending,
created,
lastModified,
status,
version,
children,
parent,
internal,
};
const keys = Object.keys(data);
keys.forEach(key => {
node[key] = data[key].iv;
});
await createNode(node);
});
};
此代码取自 gatsby-source-squidex 插件,该插件已不在 github 中。我意识到这是一个独特的问题,但我的大部分麻烦来自链接获取请求。请温柔一点。