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

Multiple fetch requests, create nodes using gatsby-node (async /await)

下面我有两个获取请求,第一个请求是一个 oauth 请求和 returns 一个身份验证令牌,所以我可以 运行 第二个请求使用该令牌和 returns来自我的无头 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);
  });
};

此代码取自不再包含在 github 中的 gatsby-source-squidex 插件。 我意识到这是一个独特的问题,但我的大部分麻烦都来自链接获取请求。 请温柔一点SO.

首先,顺便说一句,您不必 await response.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.

或者如果你需要一个一个地检查promise的结果,你可以这样做:

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

希望这有道理并能回答您的问题。