Creating 3 worksheets in one workbook (Excel-JS) problem - javascript

I need a create an one excel file with 3 worksheets. For now I wrote a function which create worksheet and workbook. I have problem because I need write data into workshet in some executed async function. Maybe some code will describe what I have to do.
var Excel = require('exceljs');
const workbook = new Excel.Workbook({
useStyles: true
})
const headers = [
{ header: 'Plik', key: 'path', width: 40 },
{ header: 'Zwierze', key: 'name', width: 12 },
{ header: 'Prawdopodobienstwo(%)', key: 'confidence', width: 24 },
{ header: 'Czas odpowiedzi(s)', key: 'responseTime', width: 20 }
];
workbook.xlsx.writeFile("./excel/Wyniki.xlsx");
setWorkSheet = (name, responses, filename) => {
workbook.xlsx.readFile(filename)
.then(function () {
const worksheet = workbook.addWorksheet(name);
worksheet.columns = headers;
for (let i = 0; i < responses.length; i++) {
worksheet.addRow(responses[i]);
}
worksheet.getRow(1).style.font = { size: 12, name: 'Bahnschrift SemiBold SemiConden' }
worksheet.getRow(1).eachCell((cell) => {
cell.fill = {
type: 'pattern',
pattern: 'solid',
fgColor: { argb: '993399' }
},
cell.style.font = {
color: {
argb: 'ffffff'
},
size: 14,
}
})
worksheet.eachRow((Row, rowNumber) => {
Row.alignment = {
horizontal: 'center',
}
Row.eachCell((Cell, cellNumber) => {
Cell.alignment = {
vertical: 'middle',
horizontal: 'center'
},
Cell.border = {
top: { style: 'double', color: { argb: 'black' } },
left: { style: 'double', color: { argb: 'black' } },
bottom: { style: 'double', color: { argb: 'black' } },
right: { style: 'double', color: { argb: 'black' } }
}
})
})
worksheet.views = [
{ state: 'frozen', xSplit: 1, ySplit: 1, activeCell: 'B2' },
];
return workbook.xlsx.writeFile(`${filename}`)
})
.then(function () {
console.log("Done");
})
.catch(function (err) {
console.log(err)
});
}
And this function for now create a new file with special defined name worksheet. I need execute this function 3 times and after this operations I need to have one file and 3 worksheets. Here are places where I executed this function:
async function Cognitive() {
let tab = [];
for (let i = 0; i < arrayOfFiles.length; i++) {
let x = await cognitive.cognitiveDetectLabels(arrayOfFiles[i]);
tab.push(x)
}
setWorkSheet('Cognitive', tab, "./excel/Wyniki.xlsx");
}
exports.Cognitive = Cognitive;
async function Rekognition() {
let tab = [];
const path = "./csv/Rekognition.csv";
for (let i = 0; i < arrayOfFiles.length; i++) {
let x = await rekognitionFile.callaws(arrayOfFiles[i]);
tab.push(x)
}
setWorkSheet("Rekognition", tab, "./excel/Wyniki.xlsx");
}
exports.Rekognition = Rekognition;
async function Vision() {
let tab = [];
for (let i = 0; i < arrayOfFiles.length; i++) {
let x = await vision.callVision(arrayOfFiles[i]);
tab.push(x)
}
setWorkSheet("Vision", tab, "./excel/Wyniki.xlsx");
}
exports.Vision = Vision;
When I execute one of this async function. File with worksheet always is overwritten.
However, I need to add sheets to one file (3 sheets). Anyone have some ideas about this problem ? Thank you

Related

Async function stops running on await_limit()

I'm trying to run this async function code, but for some reason it will stop running after await _limit(), not sure what am I doing wrong.
Basically I'm trying to go to a specific image dir, do something for each image and then update some meta-tags into some other dir that contains json files. The code will basically stop working after await_limit()
const path = require("path");
const basePath = process.cwd();
const fs = require("fs");
const { RateLimit } = require('async-sema');
const { fetchWithRetry } = require(`${basePath}/utils/fetchWithRetry.js`);
const { LIMIT } = require(`${basePath}/src/config.js`);
const _limit = RateLimit(LIMIT);
const allMetadata = [];
const regex = new RegExp("^([0-9]+).png");
async function main() {
console.log("Starting upload of images...");
const files = fs.readdirSync(`${basePath}/build/images`);
files.sort(function(a, b){
return a.split(".")[0] - b.split(".")[0];
});
for (const file of files) {
try {
if (regex.test(file)) {
const fileName = path.parse(file).name;
let jsonFile = fs.readFileSync(`${basePath}/build/json/${fileName}.json`);
let metaData = JSON.parse(jsonFile);
if(!metaData.file_url.includes('https://')) {
console.log(`code executes until here`);
await _limit()
const url = "https://api.nftport.xyz/v0/files";
const formData = new FormData();
const fileStream = fs.createReadStream(`${basePath}/build/images/${file}`);
formData.append("file", fileStream);
const options = {
method: "POST",
headers: {Authorization: 'my API key here'},
body: formData,
};
const response = await fetchWithRetry(url, options);
metaData.file_url = response.ipfs_url;
metaData.image = response.ipfs_url;
fs.writeFileSync(
`${basePath}/build/json/${fileName}.json`,
JSON.stringify(metaData, null, 2)
);
console.log(`${response.file_name} uploaded & ${fileName}.json updated!`);
} else {
console.log(`${fileName} already uploaded.`);
}
allMetadata.push(metaData);
}
} catch (error) {
console.log(`Catch: ${error}`);
}
}
fs.writeFileSync(
`${basePath}/build/json/_metadata.json`,
JSON.stringify(allMetadata, null, 2)
);
}
main();```
///config.js file starts here
const basePath = process.cwd();
const { MODE } = require(`${basePath}/constants/blend_mode.js`);
const { NETWORK } = require(`${basePath}/constants/network.js`);
const network = NETWORK.eth;
// General metadata for Ethereum
const namePrefix = "name of collection here";
const description = "description of collection here";
const baseUri = "ipfs://NewUriToReplace";
const solanaMetadata = {
symbol: "YC",
seller_fee_basis_points: 1000, // Define how much % you want from secondary market sales 1000 = 10%
external_url: "https://www.youtube.com/c/hashlipsnft",
creators: [
{
address: "address here",
share: 100,
},
],
};
// If you have selected Solana then the collection starts from 0 automatically
const layerConfigurations = [
{
growEditionSizeTo: 10, // With Cap
layersOrder: [
{ name: "Background" },
{ name: "Short" },
{ name: "Body" },
{ name: "Neckchain" },
{ name: "Tshirt" },
{ name: "Hoodie" },
{ name: "Facial Expression" },
{ name: "Beard" },
{ name: "Piercing" },
{ name: "Glasses" },
{ name: "Cap" },
],
},
];
const shuffleLayerConfigurations = false;
const debugLogs = false;
const format = {
width: 2000,
height: 3000,
smoothing: false,
};
const gif = {
export: false,
repeat: 0,
quality: 100,
delay: 500,
};
const text = {
only: false,
color: "#ffffff",
size: 20,
xGap: 40,
yGap: 40,
align: "left",
baseline: "top",
weight: "regular",
family: "Courier",
spacer: " => ",
};
const pixelFormat = {
ratio: 20 / 128,
};
const background = {
generate: true,
brightness: "80%",
static: false,
default: "#000000",
};
const extraMetadata = {
external_url: "external url here"
};
const rarityDelimiter = "#";
const uniqueDnaTorrance = 10000;
const preview = {
thumbPerRow: 5,
thumbWidth: 50,
imageRatio: format.height / format.width,
imageName: "preview.png",
};
const preview_gif = {
numberOfImages: 5,
order: "ASC", // ASC, DESC, MIXED
repeat: 0,
quality: 100,
delay: 500,
imageName: "preview.gif",
};
module.exports = {
format,
baseUri,
description,
background,
uniqueDnaTorrance,
layerConfigurations,
rarityDelimiter,
preview,
shuffleLayerConfigurations,
debugLogs,
extraMetadata,
pixelFormat,
text,
namePrefix,
network,
solanaMetadata,
gif,
preview_gif,
};
const AUTH = "API here";
const LIMIT = 2;

I got error in react while using normal javascript

i am working on react-flow, and my task is to transform the following data => `
`const configObj = {
name: "Dataset",
nodeChild: {
type: "schema",
nodeConfiguration: {
sid1: {
name: "Schema 1",
nodeChild: {
type: "dashboard",
nodeConfiguration: {
did1: {
name: "Dashboard 1"
}
}
}
},
sid2: {
name: "Schema 2",
nodeChild: {
type: "dashboard",
nodeConfiguration: {
did2: {
name: "Dashboard s1",
},
did3: {
name: "Dashboard 3"
}
}
}
}
}
}
}` to this ->
const elements = [
{
id: '1',
type: 'input', // input node
data: { label: 'Input Node' },
position: { x: 250, y: 25 },
},
// default node
{
id: '2',
// you can also pass a React component as a label
data: { label: <div>Default Node</div> },
position: { x: 100, y: 125 },
},
{
id: '3',
type: 'output', // output node
data: { label: 'Output Node' },
position: { x: 250, y: 250 },
},
// animated edge
{ id: 'e1-2', source: '1', target: '2', animated: true },
{ id: 'e2-3', source: '2', target: '3' },
];
`
not exactly but according to data1 so i prepare a code for it and it is working well in node environment but the moment i try it on react it shows some errorenter image description here here is my code
const configObj = {
name: "Dataset",
onClick: true,
nodeChild: {
type: "schema",
nodeConfiguration: {
sid1: {
name: "Schema 1",
nodeChild: {
type: "dashboard",
nodeConfiguration: {
did1: {
name: "Dashboard 1"
}
}
}
},
sid2: {
name: "Schema 2",
nodeChild: {
type: "dashboard",
nodeConfiguration: {
did2: {
name: "Dashboard s1",
nodeChild: {
type: "ritik",
nodeConfiguration: {
ri1: {
name: "Ritik",
}
}
}
},
did3: {
name: "Dashboard 3"
}
}
}
}
}
},
}
let count =1;
let dataConfig = []
const recursion = (obj, level,type) => {
let objData = {}
for(let j in obj){
if(j !== 'nodeChild' && j !== 'nodeParent'){
if(j === 'name'){
objData= {
...objData,
label: obj[j]
}
}else {
objData= {
...objData,
[j]: obj[j]
}
}
}
}
let idd = count
dataConfig = [...dataConfig, {id: count, data: objData, type, level, parentID}]
count++;
if('nodeChild' in obj){
const {nodeConfiguration, type} = obj.nodeChild
for(let val in nodeConfiguration){
recursion(nodeConfiguration[val], level+1, type, parentID = idd)
}
}
if('nodeParent' in obj){
const {nodeConfiguration, type} = obj.nodeParent
for(let val in nodeConfiguration){
recursion(nodeConfiguration[val], level-1, type)
}
}
}
recursion(configObj, level=0, type='root', parentID=1)
let edges = []
for(let i=1; i<dataConfig.length; i++){
let e = {
id: `e${dataConfig[i].id}-${dataConfig[i].parentID}`,
source: `${dataConfig[i].parentID}`, target: `${dataConfig[i].id}`, animated: true
}
edges = [
...edges,
e
]
}
let finalDataSet = []
let x=650, y=25;
let flag = false;
for(let i in dataConfig){
let element = {}
for(let key in dataConfig[i]){
if(key !== 'parentID'){
if(key === 'type'){
let k = dataConfig[i][key]
if(k === 'schema' || k === 'root'){
element = {
...element,
[key]: 'input'
}
}else {
element = {
...element,
[key]: 'output'
}
}
}else {
element = {
...element,
[key]: dataConfig[i][key]
}
}
}
}
element = {
...element,
position: { x, y }
}
// console.log(i)
finalDataSet = [
...finalDataSet,
element
]
y += 75;
if(!flag){
x = 25;
}
x = flag ? x+155 : x
flag = true
}
for(let i =0; i<edges.length; i++){
finalDataSet = [
...finalDataSet,
edges[i]
]
}
const DataSET = finalDataSet
export default DataSET
this code is perfectly working on local nodejs but the same code pops errors on react.js can any one help me on this
It's the recursion(configObj, level=0, type='root', parentID=1) calls that are causing trouble. You think that level=0 is saying to pass 0 to the level parameter but javascript doesn't recognize that syntax. It thinks that level is some variable you forgot to define. Hence the is not defined error.
To fix the issue, just do something like recursion(configObj, 0, 'root', 1) instead.

Error: Highcharts error #13: www.highcharts.com/errors/13/ in Reactjs

I am trying to use High-charts in reactjs and I am new to both these. In the beginning, everything was fine but now I am unable to solve this error.
The following is my code:
Array.prototype.contains = function (v) {
for (var i = 0; i < this.length; i++) {
if (this[i] === v) return true;
}
return false;
};
Array.prototype.unique = function () {
var arr = [];
for (var i = 0; i < this.length; i++) {
if (!arr.contains(this[i])) {
arr.push(this[i]);
}
}
return arr;
}
export default class Chart extends React.Component {
constructor(props) {
super(props);
this.state = {
installs: [],
isLoaded: false,
}
this.state = {
filteredData: [],
isLoadedFilteredData: false,
showChart: true
}
this.state = {
options: {}
}
}
componentDidMount() {
// setInterval(() => {
fetch('xyz)
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
installs: json,
});
});
}
getFilteredData = async (operatingSystem, applicationServer, database, cloud, serverRelease) => {
fetch(`xyz`)
.then(res => res.json())
.then(json => {
// console.log(json);
this.setState({
isLoadedFilteredData: true,
filteredData: json,
}, console.log("getFilteredData called ... "));
});
}
handleChange = ({ altered, name, text, value }) => {
const nextFormValue = {
[name]: {
text,
value,
altered
}
};
this.setState({ ...this.state, ...nextFormValue }, () =>
console.log("handleChange()", this.state),
);
};
render() {
const { isLoaded, installs } = this.state;
const { isLoadedFilteredData, filteredData } = this.state;
if (!isLoaded) {
return <p>Loading...</p>;
}
else {
var arrayOS = []
var arrayApp = []
var arrayDB = []
var arrayCloud = []
var arrayServerRelease = []
for (var i = 0; i < installs.length; i++) {
arrayOS.push(this.state.installs[i].object.hardwareStackDetails.operatingSystem)
arrayApp.push(this.state.installs[i].object.hardwareStackDetails.applicationServer)
arrayDB.push(this.state.installs[i].object.hardwareStackDetails.database)
arrayCloud.push(this.state.installs[i].object.cloud)
arrayServerRelease.push(this.state.installs[i].object.serverRelease)
}
var operatingSystemTemp = arrayOS.unique();
var applicationServerTemp = arrayApp.unique();
var dataBaseTemp = arrayDB.unique();
var cloudTemp = arrayCloud.unique();
var serverReleaseTemp = arrayServerRelease.unique();
arrayOS = []
arrayApp = []
arrayDB = []
arrayCloud = []
arrayServerRelease = []
for (var i = 0; i < operatingSystemTemp.length; i++) {
arrayOS.push({
text: operatingSystemTemp[i],
value: operatingSystemTemp[i]
})
}
for (var i = 0; i < applicationServerTemp.length; i++) {
arrayApp.push({
text: applicationServerTemp[i],
value: applicationServerTemp[i]
})
}
for (var i = 0; i < dataBaseTemp.length; i++) {
arrayDB.push({
text: dataBaseTemp[i],
value: dataBaseTemp[i],
})
}
for (var i = 0; i < cloudTemp.length; i++) {
arrayCloud.push({
text: cloudTemp[i],
value: cloudTemp[i]
})
}
for (var i = 0; i < serverReleaseTemp.length; i++) {
arrayServerRelease.push({
text: serverReleaseTemp[i],
value: serverReleaseTemp[i]
})
}
if (isLoadedFilteredData){
if(filteredData.length === 0) {
console.log("filteredData")
mapNew = new Map();
labelMap = {};
xlabels = []
seriesDataValue = []
Highcharts.chart('container', {
title: {
text: ''
},
subtitle: {
// text: 'Source: thesolarfoundation.com'
},
xAxis: {
categories: xlabels
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
series: seriesDataValue,
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}]
}
}
);
}
else {
console.log(filteredData)
var mapNew = new Map();
var labelMap = {};
var xlabels = []
var seriesDataValue = []
for (var j = 0; j < filteredData.length; j++) {
if (filteredData[j].object.status === "PASS") {
var date1 = moment(filteredData[j].object.creationTime);
var date2 = moment(filteredData[j].object.updationTime);
var ms = moment(date2, "DD/MM/YYYY HH:mm:ss").diff(moment(date1, "DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
// var s = d.format("hh:mm:ss");
console.log(ms)
console.log(d.hours())
var timeInhrs = d.hours()
if (mapNew.has(filteredData[j].object.clientBuild)) {
// timeInhrs = ((timeInhrs + mapNewInnerTemp.get(this.state.kuch[j].object.clientBuild)));
console.log(this.state.filteredData[j].object.clientBuild + " " + timeInhrs);
mapNew.set(this.state.filteredData[j].object.clientBuild, timeInhrs);
} else {
console.log(this.state.filteredData[j].object.clientBuild + " " + timeInhrs);
mapNew.set(this.state.filteredData[j].object.clientBuild, timeInhrs);
labelMap[this.state.filteredData[j].object.clientBuild] = 0; ///
//count = count + 1;
}
}
}
console.log(mapNew)
for (var key in labelMap) {
xlabels.push(key);
}
console.log(xlabels)
var dataValue = [] // array
for (const entry of mapNew.entries()) {
console.log(entry)
for (var key in labelMap) {
if (key === entry[0]) {
dataValue.push(entry[1])
}
}
}
console.log(dataValue)
seriesDataValue.push(
{
data: dataValue,
})
console.log(seriesDataValue)
var elementExists = document.getElementById("container");
if(elementExists === null){
let div = document.createElement("div");
div.id="container";
div.id="select"
document.body.appendChild(div);
}
Highcharts.chart('container',
xAxis: {
categories: xlabels
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
series: seriesDataValue,
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}]
}
}
);
}
}
return (
<div>
<div id="container"> </div>
</div>
);
}
}
}
The above error gets vanished after the page gets refreshed .
The error results from the fact that you create a chart before a div element with the 'container' id is created.
However, to avoid such problems I recommend you to use officially supported Highcharts wrapper for React: https://www.npmjs.com/package/highcharts-react-official

How to clear the vue warn when I use vue-slider-component?

The issue detail:
1. I implement the feature with the vue-slider-component module, but that has a lot of warnings when I move the dots on the slider.
2. I know that the reason is that I used v-for to point to an object that will change, but I do not know how to fix this issue.
the following link is my test site:
https://jsfiddle.net/ncwv84x9/
enter image description here
My codes:
code1 (Html)
<div id="app">
<div class="box" v-for="(item,index) in columnvalue">
<label>{{item.text}}</label>
<input v-model="value[index]" />
</div>
<hr />
<br />
<vue-slider v-model="value" :order="false" :tooltip="'always'" :process="false" :marks="marks" :width="600">
<template slot="tooltip" slot-scope="{index}">
<div>{{getText(index)}}</div>
</template>
</vue-slider>
</div>
JavaScript + Vue:
new Vue({
el: '#app',
components: {
VueSlider: window['vue-slider-component']
},
data: function() {
return {
// collect the all values
columnvalue: [],
// stored disease value
pet_name: [{
text: 'dog',
index: 0
},
{
text: 'cat',
index: 1
}
],
// stored drug value
feeder_name: [{
text: 'Sam',
index: 0
}],
// from age filter
age: [
65, 100
],
test: "",
value: [],
process: dotsPos => [
[dotsPos[0], dotsPos[1], {
backgroundColor: 'pink'
}],
[dotsPos[1], dotsPos[2], {
backgroundColor: 'blue'
}],
[dotsPos[2], dotsPos[3], {
backgroundColor: 'black'
}],
],
after: {},
relations: [],
marks: {
'0': {
label: 'start',
margin: '0 0 0 10px'
},
'100': {
label: 'end',
labelStyle: {
left: '100%',
margin: '0 0 0 10px',
top: '50%',
transform: 'translateY(-50%)'
}
}
}
}
},
created: function() {
//vue instance 被 constructor 建立後,在這裡完成 data binding
let tmpArray = this.pet_name.concat(this.feeder_name);
let tmpValueArray = [];
for (i = 0; i < tmpArray.length; i++) {
tmpArray[i].index = i;
tmpValueArray.push(0);
}
this.columnvalue = tmpArray;
this.value = tmpValueArray;
},
methods: {
getText(index) {
const ani = this.columnvalue.find((v) => v.index == index).text;
this.after = {
...this.after,
[ani]: this.value[index]
}
return ani;
},
getNodeRelation() {
const indexs = this.after;
let result = [];
let result2 = [];
let placement = [];
for (obj in indexs) {
placement.push([obj, indexs[obj]]);
}
placement.sort(function(a, b) {
/* console.log(a[1]) */
return a[1] - b[1];
})
for (i = 0; i < placement.length; i++) {
if (i + 1 >= placement.length) {
break;
}
let distance = placement[i + 1][1] - placement[i][1];
let predicate = "";
if (distance > 0) {
predicate = "after";
} else if (distance == 0 && placement[i + 1][1] == 0) {
predicate = "hasUse";
} else {
predicate = "same";
}
let source = {
label: placement[i][0],
index: i
};
let target = {
label: placement[i + 1][0],
index: i
};
// store the 4-tuple reprsentations about slider
result2.push({
source: source,
target: target,
type: predicate,
days: distance
});
}
/* this.relations = "{\"relation\":" + JSON.stringify(result2)+"}" */
;
this.relations = JSON.stringify(result2);
},
getAllFilters() {
let vm = this;
let beginHas = true;
if (vm.relations.length == 0) {
vm.getNodeRelation();
beginHas = false;
}
let result = {
age: vm.age,
disease_name: vm.disease_name,
drug_name: vm.drug_name,
relation: vm.relations
};
if (!beginHas) {
vm.relations = [];
}
this.test = JSON.stringify(result);
}
},
})
I get a infinite loop error which disappears when I remove this section in getText()
this.after = {
...this.after,
[ani]: this.value[index]
}
This is because there is some reactivity triggered and re-renders the dom, which calls that function, which renders the dom and so on...

Restrucutre JSON data

I'm fetching data from an API and I'm trying to restucture the data. I want the data te be structed in a type of JSON way. Like shown below.
I have tried alot but I find it very hard to do because for each methode and the for loops used.
How can I go about doing this? Any help would be greatly appricated!
I want to make and change the output of the program to this type of json structure:
[
{ id: 'bitcoin',
x: [1571695345012, 1571699061041, 1571702676146, 1571706278232, 1571709762429],
y: [8222.065325961827, 8192.012381921422, 8220.91853113097, 8192.5487839435, 8184.743590188011]
}
{ id: 'ethereum',
x: [1571695472168, 1571699049447, 1571702639502, 1571706279834, 571709827389],
y: [174.5266477952419, 173.6409574561425, 174.35449608806442, 173.9800501560514, 173.99298281578433]
}
{ id: 'ripple',
x: [1571695472168, 1571699049447, 1571702639502, 1571706279834, 571709827389],
y: [0.2926270710439499, 0.29225262544982944, 0.2922858993183195, 0.29169629356590593, 0.2926150467160304]
}
]
This is the output I go right now:
[ { id: 'bitcoin' },
{ x: 1571695345012 },
{ x: 1571699061041 },
{ x: 1571702676146 },
{ x: 1571706278232 },
{ x: 1571709762429 },
{ y: 8222.065325961827 },
{ y: 8192.012381921422 },
{ y: 8220.91853113097 },
{ y: 8192.5487839435 },
{ y: 8184.743590188011 },
{ id: 'ethereum' },
{ x: 1571695472168 },
{ x: 1571699049447 },
{ x: 1571702639502 },
{ x: 1571706279834 },
{ x: 1571709827389 },
{ y: 174.5266477952419 },
{ y: 173.6409574561425 },
{ y: 174.35449608806442 },
{ y: 173.9800501560514 },
{ y: 173.99298281578433 },
{ id: 'ripple' },
{ x: 1571695366383 },
{ x: 1571699042366 },
{ x: 1571702671612 },
{ x: 1571706274116 },
{ x: 1571709875603 },
{ y: 0.2926270710439499 },
{ y: 0.29225262544982944 },
{ y: 0.2922858993183195 },
{ y: 0.29169629356590593 },
{ y: 0.2926150467160304 } ]
The code used:
//Initialize unirest
var unirest = require("unirest");
//Combined array
var JSONApiData = ['bitcoin', 'ethereum', 'ripple'];
var ApiSparkline = []; // *** Should this really be a module global??
function unirestp(...args) {
return new Promise((resolve, reject) => {
unirest(...args).end(res => {
if (res.error) {
reject(res.error);
} else {
resolve(res.body);
}
});
});
}
async function request() {
console.log("waiting for the sparkline data...");
// Runs the API requests in parallel
const data = await Promise.all(JSONApiData.map(id =>
unirestp("GET", `https://api.coingecko.com/api/v3/coins/${id}/market_chart?vs_currency=usd&days=7`)
));
// Promise.all guarantees that the result array is in the same order as the input array, so
// we can rely on that when mapping the reults
data.forEach((id, index) => {
const {prices} = data[index];
ApiSparkline.push({id: JSONApiData[index]});
for (let j = 0; j < 5; ++j) { // *** What if `prices` doesn't have 5 entries?
ApiSparkline.push({x:prices[j][0]});
}
for (let j = 0; j < 5; ++j) { // *** What if `prices` doesn't have 5 entries?
ApiSparkline.push( {y:prices[j][1]});
}
});
// Show object
console.log(ApiSparkline);
}
//Call request function
request()
.then(() => {
// Done
})
.catch(error => {
console.log(error)
// Handle/report error
});
You would only want to call ApiSparkline.push once per API call (ie forEach)
//Initialize unirest
const unirest = require("unirest");
//Combined array
const JSONApiData = ['bitcoin', 'ethereum', 'ripple'];
function unirestp(...args) {
return new Promise((resolve, reject) => {
unirest(...args).end(res => {
if (res.error) {
reject(res.error);
} else {
resolve(res.body);
}
});
});
}
async function request() {
console.log("waiting for the sparkline data...");
// Runs the API requests in parallel
const data = await Promise.all(JSONApiData.map(id =>
unirestp("GET", `https://api.coingecko.com/api/v3/coins/${id}/market_chart?vs_currency=usd&days=7`)
));
// Promise.all guarantees that the result array is in the same order as the input array, so
// we can rely on that when mapping the reults
const ApiSparkline = [];
data.forEach((result, index) => {
const { prices } = result;
const id = JSONApiData[index];
const x = prices.map(([xItem, yItem]) => xItem);
const y = prices.map(([xItem, yItem]) => yItem);
ApiSparkline.push({
id,
x,
y
});
});
return ApiSparkline;
}
//Call request function
request()
.then(ApiSparkline => {
console.log(ApiSparkline);
})
.catch(error => {
console.log(error)
// Handle/report error
});

Categories