const express = require("@runkit/runkit/express-endpoint/1.0.0");
const requestPromise = require('request-promise');
const app = express(exports);
const skyscannerSession = (apiKey, ipAddress, flightOptions) => {
const formBody = Object.assign({}, flightOptions, {
apiKey
});
const requestOptions = {
method: 'POST',
uri: 'http://partners.api.skyscanner.net/apiservices/pricing/v1.0',
form: formBody,
headers: {
Accept: 'application/json',
'X-Forwarded-For': ipAddress,
'Content-Type': 'application/x-www-form-urlencoded'
},
resolveWithFullResponse: true
};
return requestPromise(requestOptions);
};
const skyscannerRequestResults = (apiKey, sessionUrl) => {
const requestOptions = {
uri: `${sessionUrl}?apiKey=${apiKey}`,
json: true
};
return requestPromise(requestOptions);
};
// TODO : You need to extract the data from the itineraries and convert to Chatfuel/Messenger format
// Docs : https://skyscanner.github.io/slate/#polling-the-results
const flightDataToChatfuelMessages = (flightsData) => {
const itineraries = flightsData.Itineraries;
return {itineraries};
};
// TODO: I'm concerned that this is going to respond too slowly for Chatfuel
app.get('/skyscanner', (request, response) => {
const {SKYSCANNER_API_KEY: apiKey} = process.env;
const clientIpAddress = request.ip;
// Pass them all in as request query parameters
const {
country = 'FR',
currency = 'EUR',
locale = 'fr-FR',
originPlace = 'CDG-sky', // You will have to work these out
destinationPlace = 'LOND-sky', // You will have to work these out
outboundDate = '2018-06-30',
inboundDate = '2018-07-30'
} = request.query;
const flightOptions = {
country,
currency,
locale,
originPlace,
destinationPlace,
outboundDate,
inboundDate
};
skyscannerSession(apiKey, clientIpAddress, flightOptions)
.then((sessionResponse) => {
const {headers: {location: sessionUrl}} = sessionResponse;
// TODO : This really needs to be polled multiple times
// However, it looks like it returns most of the results on the first time
return skyscannerRequestResults(apiKey, sessionUrl);
})
.then((flightsData) => {
// TODO: Got the flight data so now need to extract it to the format we need for Chatfuel
response.json(flightDataToChatfuelMessages(flightsData));
})
.catch((error) => {
response.json({messages:[{text: error.message}]});
});
});