node.js - 如何从两个不同的 API 获取数据并将它们映射到 expressjs
问题描述
我是 Node Express 的新手。我知道如何在 PHP 中做到这一点,但在 Express JS 中无法理解。
我的问题是,我想从两个或更多不同的 API 中获取 Cars Package,并通过加入他们的响应来创建新的响应。
我正在使用两种不同的 API,一种是 Talixo,另一种是 IWay。
这是他们的示例响应。
来自 talixo 的示例响应
{
"taxis": [],
"limousines": [
{
"luggage": 3,
"seats": 3,
"animals": false,
"wheelchairs": false,
"sport_luggage": 2,
"car_model": "Toyota Prius",
"children_seat_1": "I/II/III: 9 - 36 kg",
"children_seat_2": "I/II/III: 9 - 36 kg",
"id": "34427",
"color": "black",
"booking_category": "economy",
"extended_booking_category": "economy",
"currency_symbol": "€",
"currency_code": "EUR",
"talixo_points": 80,
"vehicle_type": "limo",
"included_waiting_time": 45,
"regular_price": 34.65,
"discount_price": 34.65,
"local_price": "",
"frame_contract": "Integrations",
"tolls_included": true,
"gratuity_included": true,
"search_url": "",
"image_url": "https://static.talixo.de/images/vehicles/economy.png"
},
{
"luggage": 7,
"seats": 6,
"animals": false,
"wheelchairs": false,
"sport_luggage": 2,
"car_model": "VW T5",
"children_seat_1": "I/II/III: 9 - 36 kg",
"children_seat_2": "I/II/III: 9 - 36 kg",
"id": "34429",
"color": "black",
"booking_category": "economy",
"extended_booking_category": "economy_van",
"currency_symbol": "€",
"currency_code": "EUR",
"talixo_points": 80,
"vehicle_type": "limo",
"included_waiting_time": 45,
"regular_price": 46.75,
"discount_price": 46.75,
"local_price": "",
"frame_contract": "Integrations",
"tolls_included": true,
"gratuity_included": true,
"search_url": "",
"image_url": "https://static.talixo.de/images/vehicles/economy_van.png"
},
.......
]
}
来自 iway 的示例响应在这里
{
"result": [
{
"price_uid": "aaecf387-dca1-4070-94e9-03f3a40c394b",
"price": 59.3,
"price_rub": 4420,
"reverse_id": null,
"reverse_price": {
"price": 0
},
"currency": "EUR",
"service_id": 1,
"car_class": {
"car_class_id": 2,
"title": "Standard",
"models": [
"Volkswagen Jetta",
"Skoda Octavia",
"Toyota Previa",
"Audi A4"
],
"photo": "6b6xw3z2m1.png",
"capacity": 3
},
"allowable_subaddress": 3,
"price_subaddress": 59.3,
"price_subaddress_rub": 4420,
"cancellation_time": 6,
"type": 2,
"payed_road": false,
"blackout_date": [],
"allowable_time": 6,
"class_services": [
{
"id": 1,
"title": "Встреча с табличкой",
"value": "Да"
},
{
"id": 2,
"title": "Бесплатное ожидание",
"value": "20"
},
{
"id": 3,
"title": "Дополнительный заезд (зависит от настроек заказчика)",
"value": "Да"
}
],
"id_custom_price": 100003569,
"additional_services": [
{
"id": 7823,
"additional_service_id": 2,
"price": 8.92,
"name": "Детское кресло “от 0 до 1 года”",
"description": null,
"uid": "5d3da41a-fe59-11eb-a2d6-e992f37ca87f",
"slug": "trans.additional_services.infant_seat.name",
"default_include": false,
"currency": "EUR",
"category": "baby_seat",
"type": "infant_seat",
"price_rub": 665
},
{
"id": 7829,
"additional_service_id": 3,
"price": 7.14,
"name": "Детское кресло “от 1 до 3 лет”",
"description": null,
"uid": "88833caf-fe59-11eb-a2d6-e992f37ca87f",
"slug": "trans.additional_services.seat.name",
"default_include": false,
"currency": "EUR",
"category": "baby_seat",
"type": "seat",
"price_rub": 532
},
{
"id": 7835,
"additional_service_id": 4,
"price": 7.14,
"name": "Детское кресло “от 3+ лет”",
"description": null,
"uid": "a988554c-fe59-11eb-a2d6-e992f37ca87f",
"slug": "trans.additional_services.booster.name",
"default_include": false,
"currency": "EUR",
"category": "baby_seat",
"type": "booster",
"price_rub": 532
}
],
"additional_services_revert": [
{
"id": 7823,
"additional_service_id": 2,
"price": 8.92,
"name": "Детское кресло “от 0 до 1 года”",
"description": null,
"uid": "5d3da41a-fe59-11eb-a2d6-e992f37ca87f",
"slug": "trans.additional_services.infant_seat.name",
"default_include": false,
"currency": "EUR",
"category": "baby_seat",
"type": "infant_seat"
},
{
"id": 7829,
"additional_service_id": 3,
"price": 7.14,
"name": "Детское кресло “от 1 до 3 лет”",
"description": null,
"uid": "88833caf-fe59-11eb-a2d6-e992f37ca87f",
"slug": "trans.additional_services.seat.name",
"default_include": false,
"currency": "EUR",
"category": "baby_seat",
"type": "seat"
},
{
"id": 7835,
"additional_service_id": 4,
"price": 7.14,
"name": "Детское кресло “от 3+ лет”",
"description": null,
"uid": "a988554c-fe59-11eb-a2d6-e992f37ca87f",
"slug": "trans.additional_services.booster.name",
"default_include": false,
"currency": "EUR",
"category": "baby_seat",
"type": "booster"
}
],
"is_fast_booking": false,
"flexible_tariff": false,
"flexible_tariff_agreement": true,
"price_id": 3020640,
"minimum_duration": 0,
"start_place": {
"place_id": 7891,
"title": "Undefined",
"type": 6,
"type_title": "Others",
"terminal": [],
"declension_titles": {
"nom": null,
"gen": null,
"acc": null
}
},
"finish_place": {
"place_id": 3372,
"title": "Dubai (center)",
"type": 9,
"type_title": "downtown",
"terminal": [],
"declension_titles": {
"nom": null,
"gen": null,
"acc": null
}
},
"additional_service_info": {
"type_place_start": 6,
"type_place_finish": 6,
"start_city_id": 395
}
},
{
"price_uid": "89d1ea54-38a5-40cf-84fd-ba705e6f31ca",
"price": 103.77,
"price_rub": 7734,
"reverse_id": null,
"reverse_price": {
"price": 0
},
"currency": "EUR",
"service_id": 1,
"car_class": {
"car_class_id": 6,
"title": "Minivan",
"models": [
"Toyota Previa"
],
"photo": "36eg82060g.png",
"capacity": 5
},
"allowable_subaddress": 3,
"price_subaddress": 103.77,
"price_subaddress_rub": 7734,
"cancellation_time": 12,
"type": 2,
"payed_road": false,
"blackout_date": [],
"allowable_time": 12,
"class_services": [
{
"id": 1,
"title": "Встреча с табличкой",
"value": "Да"
},
{
"id": 2,
"title": "Бесплатное ожидание",
"value": "20"
},
{
"id": 3,
"title": "Дополнительный заезд (зависит от настроек заказчика)",
"value": "Да"
}
],
"id_custom_price": 100003571,
"additional_services": [
{
"id": 7820,
"additional_service_id": 2,
"price": 8.92,
"name": "Детское кресло “от 0 до 1 года”",
"description": null,
"uid": "51434503-fe59-11eb-a2d6-e992f37ca87f",
"slug": "trans.additional_services.infant_seat.name",
"default_include": false,
"currency": "EUR",
"category": "baby_seat",
"type": "infant_seat",
"price_rub": 665
},
{
"id": 7826,
"additional_service_id": 3,
"price": 7.14,
"name": "Детское кресло “от 1 до 3 лет”",
"description": null,
"uid": "7db22146-fe59-11eb-a2d6-e992f37ca87f",
"slug": "trans.additional_services.seat.name",
"default_include": false,
"currency": "EUR",
"category": "baby_seat",
"type": "seat",
"price_rub": 532
},
{
"id": 7832,
"additional_service_id": 4,
"price": 7.14,
"name": "Детское кресло “от 3+ лет”",
"description": null,
"uid": "9f932316-fe59-11eb-a2d6-e992f37ca87f",
"slug": "trans.additional_services.booster.name",
"default_include": false,
"currency": "EUR",
"category": "baby_seat",
"type": "booster",
"price_rub": 532
}
],
"additional_services_revert": [
{
"id": 7820,
"additional_service_id": 2,
"price": 8.92,
"name": "Детское кресло “от 0 до 1 года”",
"description": null,
"uid": "51434503-fe59-11eb-a2d6-e992f37ca87f",
"slug": "trans.additional_services.infant_seat.name",
"default_include": false,
"currency": "EUR",
"category": "baby_seat",
"type": "infant_seat"
},
{
"id": 7826,
"additional_service_id": 3,
"price": 7.14,
"name": "Детское кресло “от 1 до 3 лет”",
"description": null,
"uid": "7db22146-fe59-11eb-a2d6-e992f37ca87f",
"slug": "trans.additional_services.seat.name",
"default_include": false,
"currency": "EUR",
"category": "baby_seat",
"type": "seat"
},
{
"id": 7832,
"additional_service_id": 4,
"price": 7.14,
"name": "Детское кресло “от 3+ лет”",
"description": null,
"uid": "9f932316-fe59-11eb-a2d6-e992f37ca87f",
"slug": "trans.additional_services.booster.name",
"default_include": false,
"currency": "EUR",
"category": "baby_seat",
"type": "booster"
}
],
"is_fast_booking": false,
"flexible_tariff": false,
"flexible_tariff_agreement": true,
"price_id": 3020641,
"minimum_duration": 0,
"start_place": {
"place_id": 7891,
"title": "Undefined",
"type": 6,
"type_title": "Others",
"terminal": [],
"declension_titles": {
"nom": null,
"gen": null,
"acc": null
}
},
"finish_place": {
"place_id": 3372,
"title": "Dubai (center)",
"type": 9,
"type_title": "downtown",
"terminal": [],
"declension_titles": {
"nom": null,
"gen": null,
"acc": null
}
},
"additional_service_info": {
"type_place_start": 6,
"type_place_finish": 6,
"start_city_id": 395
}
}
],
"error": null
}
我想从他们的数据中创建自己的响应,例如。
{
'activityid': "",
'availabletime': "",
'carimageurl': "",
'freecanceltime': "",
'freewaittime': "",
'inclusivedesc': "",
'hvreferralid': "",
'hvreferraltype': "",
'maxluggagecount' => "",
'maxpassangerscount': "",
'originprice': "",
'originpriceformatted': "",
'packageId': "",
'serviceproviderid': "",
'serviceprovidername': "Talixo or Iway",
'vehicleid': "",
'carname': "",
'vehicletype': "",
'vehicleremarks': "or Similar",
}
这就是我迄今为止在快递控制器中所做的
const httpStatus = require('http-status');
const pick = require('../utils/pick');
const catchAsync = require('../utils/catchAsync');
const axios = require('axios');
const Talixoapi = 'somekey'
const searchCars = catchAsync(async (req, res) => {
try {
const talixoheaders = {
'Content-Type': 'application/json',
'Partner': Talixoapi
}
const iwayheaders = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}
const payload = {
"start_point": req.body.start_point,
"end_point": req.body.end_point,
"start_time_date": req.body.start_time_date,
"start_time_time": req.body.start_time_time,
"passengers": req.body.passengers,
"sport_luggage": req.body.sport_luggage,
"animals": req.body.animals,
"luggage": req.body.luggage
}
//talixo api request
const { data } = await axios.post(`https://talixo.com/en/mapi/v3/vehicles/booking_query/`, payload, {
headers: talixoheaders
})
//iway api request
const { iwaydata } = await axios.get(`https://sandbox.iway.io/transnextgen/v3/prices?user_id=747853&lang=en¤cy=EUR&start_place_point=24.9178231%2C55.0111167&finish_place_point=25.259478%2C55.3229291`, {
headers: iwayheaders
})
res.json(data)
}
catch (err) {
res.send(err)
}
});
module.exports = {
searchCars
}
我不知道在控制器中下一步该做什么。
到目前为止我所理解的是,我需要通过使用 foreach 为每个结果创建自己的 json 数组,然后合并所有数组。
还有一个问题,我不知道为什么,但是当我使用
const { iwaydata } 或 const { talixodata },它给出空白结果,但是当我使用 const { data } 时,它工作正常。
这就是我遵循@sangam rajpara 的建议到现在为止所做的事情。
const searchCars = catchAsync(async (req, res) => {
try {
const talixoheaders = {
'Content-Type': 'application/json',
'Partner': Talixoapi
}
const iwayheaders = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ***************'
}
const payload = {
"start_point": req.body.start_point,
"end_point": req.body.end_point,
"start_time_date": req.body.start_time_date,
"start_time_time": req.body.start_time_time,
"passengers": req.body.passengers,
"sport_luggage": req.body.sport_luggage,
"animals": req.body.animals,
"luggage": req.body.luggage
}
const { data: talixoData } = await axios.post(`https://talixo.com/en/mapi/v3/vehicles/booking_query/`, payload, {
headers: talixoheaders
})
const { data: iwayData } = await axios.get(`https://sandbox.iway.io/transnextgen/v3/prices?user_id=1863&lang=en¤cy=USD&start_place_point=24.9178231%2C55.0111167&finish_place_point=25.259478%2C55.3229291`, {
headers: iwayheaders
})
const taxiresults = [];
if (talixoData.taxis.length) {
talixoData.taxis.forEach(function (item) {
arrcars = {};
arrcars["carname"] = item.car_model;
arrcars["originprice"] = item.regular_price;
arrcars["packageId"] = item.id;
arrcars["image"] = item.image_url;
arrcars["vendor"] = "Talixo";
arrcars["vehicleremarks"] = "Or Similar";
taxiresults.push(arrcars);
});
}
if (talixoData.limousines.length){
talixoData.limousines.forEach(function (item) {
arrcars = {};
arrcars["carname"] = item.car_model;
arrcars["originprice"] = item.regular_price;
arrcars["packageId"] = item.id;
arrcars["image"] = item.image_url;
arrcars["vendor"] = "Talixo";
arrcars["vehicleremarks"] = "Or Similar";
taxiresults.push(arrcars);
});
}
if (iwayData.result.length) {
iwayData.result.forEach(function (item) {
var imgsrc = "https://iwayex.com/images/cars/";
arrcars = {};
arrcars["carname"] = item.car_class.models[0];
arrcars["originprice"] = item.price;
arrcars["packageId"] = item.price_uid;
arrcars["image"] = imgsrc + item.car_class.photo;
arrcars["vendor"] = "iway Transfers";
arrcars["vehicleremarks"] = "Or Similar";
taxiresults.push(arrcars);
});
}
res.json(taxiresults)
}
catch (err) {
res.send(err)
}
});
解决方案
根据 Axios,您在响应对象的数据键中接收 API 响应数据。
你能做的是。
//talixo api request
const { data: talixoData } = await axios.post(`https://talixo.com/en/mapi/v3/vehicles/booking_query/`, payload, {
headers: talixoheaders
})
//iway api request
const { data: iwayData } = await axios.get(`https://sandbox.iway.io/transnextgen/v3/prices?user_id=747853&lang=en¤cy=EUR&start_place_point=24.9178231%2C55.0111167&finish_place_point=25.259478%2C55.3229291`, {
headers: iwayheaders
})
如果您是 javascript 新手,我所做的是解构对象并重命名关键数据。
推荐阅读
- javascript - JS 命令禁止字母,只允许数字(光盘机器人)
- css - 将边框底部应用于引导程序 4 中的活动项目后,导航项目未在同一行中对齐
- javascript - 如何避免打字稿出现空白
- javascript - 自定义计数器 VueJS
- python - 通过函数参数访问 Python 预定义的数组名称
- google-cloud-platform - 性能设计模式:来自无服务器/云函数/lambda 的 SQL 连接
- mysql - 如何在 SQL 中选择最接近的值,但仅当该值更大时?
- php - 生成PDF
- javascript - 错误堆栈跟踪指向错误的行 - Node.js + Webpack
- r - 将多个图例与拼凑对齐