【发布时间】:2018-10-08 18:52:49
【问题描述】:
我正在做一个需要我做的项目:
从 API1 获取 ID,将 ID 推送到数组中,然后映射这些 ID,将它们用于第二个 GET 请求,其中 ID 用作 API2 GET 请求的参数,用 ID 或 N 填充数组对于“不存在”——然后调用这个数组:
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 请求?
【问题讨论】:
-
这可能有很多错误——但这是我未经测试的思考过程。不完全确定我可以自动化这个系统——这甚至可能吗?
-
您是否尝试过使用 Promise 我希望 Promise 能在这种情况下对您有所帮助
-
是的,您可以为此目的使用 Express 中间件。
-
是的,你可以使用它
-
很好,是的,这会有所帮助
标签: node.js api express request async-await