1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
| const axios = require('axios'); const moment = require('moment'); const { Parser } = require('json2csv'); const fs = require('fs');
let head = []; ... let timer = null; let duration = 60000; let token = ''; let apiURL = 'put API URL'; let appID = 'put API ID'; let appSecret = 'put API Code'; let startTime = moment().format(); let grabMiniute = 3; let endTime = moment(startTime).add(grabMiniute, 'minutes');
async function getToken() { let res = await axios({ methos: 'GET', url: `${apiURL}/api/auth?appId=${appID}&appSecret=${appSecret}` }); token = res.data.data; }
async function requestAPI(apiMethod, apiURL, retryFunc) { try { return await axios({ method: apiMethod, url: apiURL, headers: { AccessToken: token, System: appID } }); } catch(error) { if (error.message.indexOf('401') > -1) { await getToken(); retryFunc(); } } }
async function getHead() { let res = await requestAPI('GET', `${apiURL}/api/Head`, getHead); if (res) { head = head.concat(res.data); } console.log('head', head.length); }
...
async function getAllData() { await getToken();
console.log(`----- ${grabMiniute} minutes left -----`);
getHead(); getFeeder(); getNozzle();
grabMiniute = grabMiniute - 1; }
function writeFile(data, fileName) { fs.writeFile(fileName, data, 'utf8', function (err) { if (err) { console.log(`An error occured while writing ${fileName}.`); return console.log(err); }
console.log(`${fileName} has been saved.`); }); }
function saveFile() { try { const fieldsHead = [columnA, ...]; const fieldsFeeder = [columnA, ...]; const fieldsNozzle = [columnA, ...]; const parserHead = new Parser({ fieldsHead }); const parserFeeder = new Parser({ fieldsFeeder }); const parserNozzle = new Parser({ fieldsNozzle }); const csvFeeder = parserFeeder.parse(feeder); const csvHead = parserHead.parse(head); const csvNozzle = parserNozzle.parse(nozzle);
console.log(`----- SAVE FILES -----`); writeFile(csvHead, 'Head.csv'); writeFile(csvFeeder, 'Feeder.csv'); writeFile(csvNozzle, 'Nozzle.csv'); } catch (err) { console.error('saveFile ERROR: ', err); } }
getAllData();
timer = setInterval(() => { let now = moment().format(); if(moment(now).isBefore(endTime)) { getAllData(); } else { clearInterval(timer); saveFile(); } }, duration);
|