多个获取请求,使用 gatsby-node (async /await) 创建节点



下面我有两个获取请求,第一个请求是一个 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 中。 我意识到这是一个独特的问题,但我的大部分麻烦都来自链接获取请求。 请温柔一点。

首先,顺便说一句,您不必awaitresponse.json((,因为在此之前您已经等待了响应。

如果我正确理解了您的问题,您想运行一堆这些请求,然后查看它们的结果。

我可能会创建一个 promise 数组和 Promise.All(( 该数组,例如

const endpoints = [/* enrpoint1, endpoint2 ... endpointN */];
const promiseArray = endpoints.map(endpoint => fetch(`${process.env.API_URI}${endpoint}`, {
method: 'GET',
headers: {
Authorization: `${json.token_type} ${json.access_token}`,
},
}));
const promiseResults = await Promise.all(promiseArray) // returns an array of all your promise results and rejects the whole thing if one of the promises rejects.

或者,如果您需要在承诺结果出现时逐个检查它们,您可以执行以下操作:

for await ( let result of promiseArray){
console.log(result.json()) // this is each response 
}

希望这是有道理的,并回答你的问题。

最新更新