首页 > 解决方案 > 如何:从 2 个 API 获取数据、比较、POST bool

问题描述

我正在做一个需要我做的项目:

  1. 从 API1 获取 ID,将 ID 推送到数组中,然后映射这些 ID,将它们用于第二个 GET 请求,其中 ID 用作 API2 GET 请求的参数,使用 ID 填充数组或 N 表示“不存在” - - 然后调用这个数组:

  2. 一个 POST 请求。这篇文章映射了 GET 请求返回的数组。如果项目不是“N”,它会发布到 API1 并选中:true。如果项目是“N”,它会通过电子邮件告诉我们 API2 缺少该项目。

我希望这个系统每 2 小时自动执行一次 GET 和 POST,所以我使用 setInterval(不确定这是不是最好的主意)。编辑: Cron 工作将是一个更好的解决方案。

我正在使用 NodeJS、Express、Request-Promise、Async/Await。

到目前为止,这是我的一些伪代码:

// Dependencies
const express = require('express');
const axios = require('axios');
const mailgun = require('mailgun-js')({ apiKey, domain });

// Static
const app = express();


app.get('/', (req, res, next) => {
  // Replace setInterval with Cron job in deployment

  // Get All Ids
  const orders = await getGCloud();

  // Check if IDs exist in other API
  const validations = await getProjectManagementSystem(orders);

  // If they exist, POST update to check, else, mailer
  validations.map(id => {
    if (id !== 'n') {
      postGCloud(id);
    } else {
      mailer(id);
    }
  });   
}

// Method gets all IDs
const getGCloud = async () => {
  try {
    let orders = [];
    const response = await axios.get('gCloudURL');
    for (let key in response) {
      orders.push(response.key);
    }
    return orders;
  } catch (error) {
    console.log('Error: ', error);
  }
}

// Method does a GET requst for each ID
const getProjectManagementSystem = async orders => {
  try {
    let idArr = [];
    orders.map(id => {
      let response = await axios.get(`projectManagementSystemURL/${id}`);
      response === '404' ? idArr.push('n') : idArr.push(response)
    })
    return idArr;
  } catch (error) {
    console.log('Error: ', error);
  }
}

const postGCloud = id => {
  axios.post('/gcloudURL', {
    id,
    checked: true
  })
  .then(res => console.log(res))
  .catch(err => console.log(err))
}

const mailer = id => {
  const data = {
    from: 'TESTER <test@test.com>',
    to: 'customerSuppoer@test.com',
    subject: `Missing Order: ${id}`,
    text: `Our Project Management System is missing ${id}. Please contact client.`    
  }

  mailgun.messages().send(data, (err, body) => {
    if (err) {
      console.log('Error: ', err)
    } else {
      console.log('Body: ', body);
    }
  });
}

app.listen(6000, () => console.log('LISTENING ON 6000'));

TL;DR:需要向 API 1 发出 GET 请求,然后向 API 2 发出另一个 GET 请求(使用 API 1 中的 ID 作为参数),然后将数据从第二个 GET 发送到 POST 请求,然后更新 API 1数据或电子邮件客户支持。这是一个自动系统,每两个小时运行一次。

主要问题: 1. 在 get req 中有 setInterval 可以吗?2.我可以让一个GET请求自动调用一个POST请求吗?3. 如果是这样,我如何将 GET 请求数据传递给 POST 请求?

标签: node.jsapiexpressrequestasync-await

解决方案


要使其对您的一次调用和一次调用都有效,您必须执行 Ajax 调用以在另一种方法中获取后期处理的信息。

我希望这行得通。


推荐阅读