how to call api recursively until nested stack keys are finished - javascript

here is my question how to call api recursively untill nested data stack keys are finished
here is my full explaination in image
i found this relatable code for recursion api call at this post recursive api call
function callFW() {
d3.json(url, async function(data) {
Tree["uid"] = data.request.uid
Tree["hid"] = data.firmware.meta_data.hid
Tree["size"] = data.firmware.meta_data.size
Tree["children"] = [];
await BuildTree(data.firmware.meta_data.included_files,Tree["children"]);
console.log(Tree)
})
}
async function BuildTree(included_files, fatherNode) {
if (included_files.length > 0) {
let promises = included_files.map( item => {
let url = endpoint + "file_object/" + item + "?summary=true";
return axios.get(url)
});
const results = await Promise.all(promises);
for(let response of results){
var node = {}
node["uid"] = response.data.request.uid
node["hid"] = response.data.file_object.meta_data.hid
node["size"] = response.data.file_object.meta_data.size
node["children"] = []
fatherNode.push(node)
await BuildTree(response.data.file_object.meta_data.included_files, node["children"]);
};
}
};
this is im using custom useRecurseFetch for getting post api result
but i have no idea how to change this code for recursive api call
import React from 'react';
import qs from 'qs';
import axios from 'axios';
const useRecurseFetch = query => {
const [status, setStatus] = React.useState('idle');
const [result, setResult] = React.useState([]);
const [findClass, setFindClass] = React.useState([]);
// console.log(passVariable);
var data;
data = qs.stringify({
query: `http://www.blabla{ ${query}/category}`,
});
// eslint-disable-next-line no-undef
var Grant = process.env.REACT_APP_GRANT;
// eslint-disable-next-line no-undef
var Client = process.env.REACT_APP_CLIENT;
// eslint-disable-next-line no-undef
var Key = process.env.REACT_APP_KEY;
// eslint-disable-next-line no-undef
var Auth = process.env.REACT_APP_AUTH;
// eslint-disable-next-line no-undef
var Query = process.env.REACT_APP_QUERY;
const queryCall = React.useCallback(
async token => {
if (!token) {
return;
} else {
setStatus('Loading');
var config = {
method: 'POST',
url: `${Query}`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization:
token.data.token_type + ' ' + token.data.access_token,
},
data: data,
};
axios(config)
.then(response => {
setResult(response.data.results.bindings);
let originalResult = response.data.results.bindings
.filter(ek => ek.class !== undefined && ek)
.map(el => el.obj.value);
setFindClass(originalResult);
setStatus('success');
})
.catch(function (error) {
setStatus('error');
});
}
},
[data]
);
React.useEffect(() => {
const authInitiate = () => {
var data = qs.stringify({
grant_type: `${Grant}`,
client_id: `${Client}`,
client_secret: `${Key}`,
});
var config = {
method: 'POST',
url: `${Auth}`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
data: data,
};
axios(config)
.then(response => {
queryCall(response);
})
.catch(function (error) {
console.log(error);
});
};
authInitiate();
}, [queryCall]);
return [status, result, findClass];
};
export default useRecurseFetch;
please any one can help me out with this code, im unable to figure out whats going in this code
anyhelp is really saved my day and really so appreciatable
here i called useRecurseFetch custom function in app.js
const [loadingStatus, mainData, addDataToPostItemArray] = useRecurseFetch(
`<kk:cat>`
);
please any one can help me out please im stuck with this process of calling api

Related

trying to call an external endpoint inside a jira issue panel app

In my code, when I try to call an external endpoint from the Jira issue panel app, I get a log "try" and the fetch doesn't happen.
I would appreciate it, if someone could help me.
Thanks in advance!
import ForgeUI, {
IssuePanel,
useProductContext,
useEffect,
} from "#forge/ui";
import { url } from "./constants";
import API, { fetch } from "#forge/api";
const Panel = () => {
const productContext = useProductContext();
const fetchTaskItems = async (issueID) => {
const requestOptions = {
method: "GET",
mode: "cors",
headers: { "Content-Type": "application/json" },
};
try {
console.log("try");
const res = await fetch(
url + `experience/task/item/${issueID}`,
requestOptions
);
console.log(res);
} catch (err) {
console.log(err.message);
}
};
useEffect(() => {
const currentIssueId = productContext.platformContext.issueKey;
console.log("Current issue ID:", currentIssueId);
fetchTaskItems(currentIssueId);
}, []);
You can import userAction from ForgeUI
import ForgeUI, {useAction} from "#forge/ui";
Then call your fetchTaskItems like this
const [req] = useAction(
(value) => value,
async () => await fetchTaskItems()
);
let me know if it works,

400 "Bad Request" error when using Thunder Client (Postman) API

I am using the Thunder Client app for VS code to use an API to save the user's data. The API is okay but there is something wrong with my code because I keep getting a 400 "Bad Request" error when I try to send the data to the API. I think the problem might be an array in my code and that is not being sent correctly.
const form = document.querySelector('.form');
const refresh = document.querySelector('.refresh-button');
export const scores = [];
renderScores();
// event listener
form.addEventListener('submit', (e) => {
e.preventDefault();
saveScore();
renderScores();
});
refresh.addEventListener('click', (e) => {
e.preventDefault();
getScores();
renderScores();
});
function renderScores() {
const scoreList = document.querySelector('.result-list');
scoreList.innerHTML = '';
scores.forEach((score) => {
const li = document.createElement('li');
li.innerHTML = `${score.user} : ${score.score}`;
scoreList.appendChild(li);
});
}
async function getScores() {
const savedScores = 'https://us-central1-js-capstone-backend.cloudfunctions.net/api/games/Zl4d7IVkemOTTVg2fUdz/scores/';
const recievedScores = await fetch(savedScores);
const api = await recievedScores.json();
const scores = api.result;
renderScores(scores);
}
async function saveScore() {
const user = document.querySelector('.fullname').value;
const score = document.querySelector('.thescore').value;
const newScore = {
user,
score,
};
scores.push(user, score);
await fetch('https://us-central1-js-capstone-backend.cloudfunctions.net/api/games/Zl4d7IVkemOTTVg2fUdz/scores/', {
method: 'POST',
body: JSON.stringify({
newScore
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
});
getScores();
}
Hey guys I changed my code a little and now I am not getting an error but when I refresh my page I lose all the data

React Native how to get only some data from api

Given url Data==> need to get only Karnataka state details
[{"id":1,"title":"TELANGANA","image":"url","stateCode":"TS"},{"id":4,"title":"TAMILNADU","image":"url","stateCode":"TN"},{"id":3,"title":"KARNATAKA","image":"url","stateCode":"KN"},{"id":2,"title":"ANDHRA","image":"url","stateCode":"AP"}]
Here code to get data===>
const [states, setStates] = useState([]);
useEffect(() => {
handleGetStates()
}, []);
const handleGetStates = async () => {
let values = {
url: `url`,
method: 'get',
}
try {
const response = await axios(values)
setStates(response.data)
console.log(response.data,'response');
} catch (error) {
// handle error
console.log(error);
}
};
You can filter on the array returned from the API:
...
const response = await axios( values );
setStates( response.data.filter(state => state.title === 'KARNATAKA' );
// result: [ {"id":3,"title":"KARNATAKA","image":"url","stateCode":"KN"} ]
...
This will loop through the response and only keep states that have a title of "KARNATAKA"
You can use an array filter method
const {data} = await axios(values);
const result = data?.filter(el=>el.stateCode==='KN')

UI update with GET method

I'm working on a project to get the api from openweathermap using node js & express & then update the UI.
I'm trying to update the UI of the page with the GET data, but it does not work. it prints undefined instead of the required values.
it works and gets the api from openweathermap on the terminal & console.
any help would be appreciated!
/* Global Variables */
const date = document.getElementById('date').value;
const temp = document.getElementById('temp').value;
// Create a new date instance dynamically with JS
let d = new Date();
let newDate = d.getMonth()+'.'+ d.getDate()+'.'+ d.getFullYear();
//baseURL & apiKey
const baseURL = `http://api.openweathermap.org/data/2.5/weather?zip=`;
const apiKey = `&appid=...`;
//event listener when user clicks generate button
const button = document.getElementById('generate');
button.addEventListener('click', performAction);
//event listener function
function performAction(event) {
const zip = document.getElementById('zip').value;
const feelings = document.getElementById('feelings').value;
getData(baseURL, zip, apiKey)
.then(function (data) {
console.log(data);
postData('/add', {date: newDate, temp: data.main.temp, feelings: feelings});
updateUI();
})
};
//function to fetch api data
const getData = async (baseURL, zip, apiKey) => {
const res = await fetch(baseURL+zip+apiKey)
try {
const data = await res.json();
return data;
console.log(data);
}catch(error) {
console.log("error", error);
}
}
// user input post data function
const postData = async (url = '', data = {}) => {
const response = await fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
});
try {
const newData = await response.json();
}catch (error) {
console.log("error", error);
}
};
//updating UI
const updateUI = async () => {
const request = await fetch('/all');
try{
const allData = await request.json();
document.getElementById('date').innerHTML = allData.date;
document.getElementById('temp').innerHTML = allData.temp;
document.getElementById('content').innerHTML = allData.content;
}catch(error){
console.log("error", error);
}
}

How can I access the response headers of a request that is piped to a feedparser

I am trying to parse an RSS feed using request js and feedparser-promised libraries. I am able to parse the feed using the below code.
import Bottleneck from 'bottleneck';
const feedparser = require('feedparser-promised');
const limiter = new Bottleneck({
maxConcurrent: 1,
minTime: 333,
});
const httpOptions = {
uri: val.sourcefeedurl,
resolveWithFullResponse: true,
method: 'GET',
pool: false,
headers: {
'If-None-Match': val.etag,
'If-Modified-Since': val.LastModified,
Connection: 'keep-alive',
ciphers: 'DES-CBC3-SHA',
},
};
const response = await limiter.schedule(() => feedparser.parse(httpOptions));
But since I use the feedparser-promised library I am not able to cache the etag and Last Modified from the response headers.
I tried modifying feedparser-promised like this
'use strict';
const request = require('request');
const feedParser = require('./feedParser');
const parse = (requestOptions, feedparserOptions) => {
const metaData = {};
return new Promise((resolve, reject) => {
request.get(requestOptions).on('error', reject).on('response', async resp => {
if (resp.statusCode === 304) {
reject('Source not modified');
} else if (resp.statusCode === 200) {
metaData.etagin = await resp.headers.etag;
metaData.LastModifiedin = await resp.headers['last-modified'];
metaData.LastModifiedLocal = await resp.headers['last-modified'];
// console.log(metaData);
}
}).pipe(feedParser(feedparserOptions).on('error', reject).on('response', resolve));
});
};
module.exports = {
parse
};
Below is the feedParser file
'use strict';
const FeedParserStream = require('feedparser');
module.exports = (feedparserOptions, metaData) => {
// console.log(metaData, 'herre');
const parsedItems = [];
const feedparser = new FeedParserStream(feedparserOptions);
// console.log(feedparser);
feedparser.on('readable', () => {
// console.log(resp);
let item;
while (item = feedparser.read()) {
parsedItems.push(item);
}
return parsedItems;
}).on('end', function next() {
this.emit('response', parsedItems);
});
return feedparser;
};
So my question is how do I return the response headers along with the parsedItems (as in the code) while resolving the promise.
Help is very much appreciated.
Pass the metaData on end like
'use strict';
const FeedParserStream = require('feedparser');
module.exports = (feedparserOptions, metaData) => {
// console.log(metaData, 'herre');
const parsedItems = [];
const feedparser = new FeedParserStream(feedparserOptions);
// console.log(feedparser);
feedparser.on('readable', () => {
// console.log(resp);
let item;
while (item = feedparser.read()) {
parsedItems.push(item);
}
return parsedItems;
}).on('end', function next() {
this.emit('response', { parsedItems, metaData });
});
return feedparser;
};
and your feed-parser promised as
'use strict';
const request = require('request');
const feedParser = require('./feedParser');
const parse = (requestOptions, feedparserOptions) => {
const metaData = {};
return new Promise((resolve, reject) => {
request.get(requestOptions).on('error', reject).on('response', async resp => {
if (resp.statusCode === 304) {
reject('Source not modified');
} else if (resp.statusCode === 200) {
metaData.etagin = await resp.headers.etag;
metaData.LastModifiedin = await resp.headers['last-modified'];
metaData.LastModifiedLocal = await resp.headers['last-modified'];
// console.log(metaData);
}
}).pipe(feedParser(feedparserOptions, metaData).on('error', reject).on('response', resolve));
});
};
module.exports = {
parse
};

Categories

Resources