2

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

4

1 回答 1

2

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

或者,如果您需要在 Promise 结果进入时一一检查,您可以执行以下操作:

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

希望这有意义并回答您的问题。

于 2020-05-13T17:21:49.473 回答