const parseString = require('xml2js').parseString; import fetch from 'node-fetch'; import { Result } from '../types'; type Response = { body: string; tokenValue: string; }; const fetchData = ({ body, tokenValue }: Response): Promise => { return new Promise((resolve, reject) => { if (!body || !tokenValue) { reject(new Error('Error with credentials')); } else { fetch('https://lite.realtime.nationalrail.co.uk/OpenLDBWS/ldb11.asmx', { method: 'POST', headers: { 'Content-Type': 'text/xml', }, body: ` ${tokenValue} ${body} `, }) .then(response => response.text()) .then(response => response.replace(/(<\/?)(\w*:)/gm, '$1')) .then(response => { parseString(response, (error: Error, result: any) => { if (error) { return reject(error); } else { return resolve(result.Envelope.Body[0]); } }); }) .catch((err: Error) => { // console.error("Error returned from fetch", err); return reject(err); }); } }); }; export default fetchData;