Query Parameters twitch API - javascript

This query works, but i want to add some optionnals parameters.
Alert.prototype.getUserFollowedChannels = async function (user) {
return new Promise((resolve, reject) =>{
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.twitch.tv/kraken/users/' + user+ '/follows/channels?client_id=' + this.clientId, true);
//xhr.open('GET', 'https://api.twitch.tv/kraken/users/' + user+ '/follows/channels?client_id=' + this.clientId+'?limit=100', true); // try with what i want
xhr.onreadystatechange = function () {
if (xhr.readyState != 4 || xhr.status != 200) return;
var follows = JSON.parse(xhr.responseText);
if (follows) resolve(follows);
else resolve("none");
}
xhr.send();
})
}
There is the doc of my query : https://dev.twitch.tv/docs/v5/reference/users/#get-user-follows

You can use something like query-string

Related

JavaScript helps with conditional syntax

I have a function that calls an API (let's call it API-1) to get the song lyrics.
Since this API sometimes can't find a song in its database, I want to call another API (let's call it API-2) to do the same search.
I need to integrate the code of both APIs inside the function, when the first one doesn't get data.
I tell you some very important information:
In API-1 I must force the data to be fetched as XML and the responseType must be 'document'.
API-2 does not require any of the above conditions, the data is parced as JSON and the responseType it supports is 'text', but does not require it to be set, with 'document' it DOES NOT work, it gives error.
Now I will share the function code for API-1 and then I will share the same function code for API-2.
They both work perfect if I test them independently.
The help I am asking for is to integrate API-2 when API-1 does not fetch data.
Code using API-1
this.refreshLyric = function (currentSong, currentArtist) {
var xhr = new XMLHttpRequest;
xhr.open('GET', proxy_URL + api_URL + 'apiv1.asmx/SearchLyricDirect?artist=' + currentArtistE + '&song=' + ucwords(currentSongE), true);
// ONLY FOR THIS XMLHttpRequest responseType must be empty string or 'document'
xhr.responseType = 'document';
// ONLY FOR THIS XMLHttpRequest force the response to be parsed as XML
xhr.overrideMimeType('text/xml');
xhr.onload = function () {
if (xhr.readyState === xhr.DONE && xhr.status === 200) {
var openLyric = document.getElementsByClassName('lyrics')[0];
var lyric = xhr.responseXML.getElementsByTagName('Lyric')[0].innerHTML;
//check if any data was obtained
if (lyric != '') {
document.getElementById('lyric').innerHTML = lyric.replace(/\n/g, '<br />');
openLyric.style.opacity = "1";
openLyric.setAttribute('data-toggle', 'modal');
} else { /////// HERE INTEGRATE API-2 //////
openLyric.style.opacity = "0.3";
openLyric.removeAttribute('data-toggle');
var modalLyric = document.getElementById('modalLyrics');
modalLyric.style.display = "none";
modalLyric.setAttribute('aria-hidden', 'true');
(document.getElementsByClassName('modal-backdrop')[0]) ? document.getElementsByClassName('modal-backdrop')[0].remove(): '';
}
} else {
document.getElementsByClassName('lyrics')[0].style.opacity = "0.3";
document.getElementsByClassName('lyrics')[0].removeAttribute('data-toggle');
}
};
xhr.send();
}
The same code using API-2
this.refreshLyric = function (currentSong, currentArtist) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
var data = JSON.parse(this.responseText);
var openLyric = document.getElementsByClassName('lyrics')[0];
var lyric = data.mus[0].text;
//check if any data was obtained
if (lyric != '') {
document.getElementById('lyric').innerHTML = lyric.replace(/\n/g, '<br />');
openLyric.style.opacity = "1";
openLyric.setAttribute('data-toggle', 'modal');
} else {
openLyric.style.opacity = "0.3";
openLyric.removeAttribute('data-toggle');
var modalLyric = document.getElementById('modalLyrics');
modalLyric.style.display = "none";
modalLyric.setAttribute('aria-hidden', 'true');
(document.getElementsByClassName('modal-backdrop')[0]) ? document.getElementsByClassName('modal-backdrop')[0].remove(): '';
}
} else {
document.getElementsByClassName('lyrics')[0].style.opacity = "0.3";
document.getElementsByClassName('lyrics')[0].removeAttribute('data-toggle');
}
}
xhttp.open('GET', 'https://api.vagalume.com.br/search.php?apikey=' + API_KEY + '&art=' + currentArtist + '&mus=' + currentSong.toLowerCase(), true);
xhttp.send()
}
The shared codes are of the SAME function (this.refreshLyric), what has to be integrated is only the XMLHttpRequest API.
In the ELSE of line 23 of API-1 I must integrate the code of API-2.
I have already tried it in several ways but I am presented with syntax problems with the IF - ELSE conditionals and errors with the API-2 which is getting the responseType and the MimeType of API-1.
EDIT
FIXED: When API-1 cannot find the lyric, I have created a new function that calls API-2. refreshLyric2(currentSong, currentArtist); :)
this.refreshLyric = function (currentSong, currentArtist) {
var xhr = new XMLHttpRequest;
xhr.open('GET', proxy_URL + api_URL + 'apiv1.asmx/SearchLyricDirect?artist=' + currentArtistE + '&song=' + ucwords(currentSongE), true);
// ONLY FOR THIS XMLHttpRequest responseType must be empty string or 'document'
xhr.responseType = 'document';
// ONLY FOR THIS XMLHttpRequest force the response to be parsed as XML
xhr.overrideMimeType('text/xml');
xhr.onload = function () {
if (xhr.readyState === xhr.DONE && xhr.status === 200) {
var openLyric = document.getElementsByClassName('lyrics')[0];
var lyric = xhr.responseXML.getElementsByTagName('Lyric')[0].innerHTML;
//check if any data was obtained
if (lyric != '') {
document.getElementById('lyric').innerHTML = lyric.replace(/\n/g, '<br />');
openLyric.style.opacity = "1";
openLyric.setAttribute('data-toggle', 'modal');
} else {
//If lyric was not obtained, we call API-2
refreshLyric2(currentSong, currentArtist);
}
} else {
document.getElementsByClassName('lyrics')[0].style.opacity = "0.3";
document.getElementsByClassName('lyrics')[0].removeAttribute('data-toggle');
}
};
xhr.send();
}
refreshLyric2 = function (currentSong, currentArtist) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
var data = JSON.parse(this.responseText);
var openLyric = document.getElementsByClassName('lyrics')[0];
var lyric = data.mus[0].text;
//check if any data was obtained
if (lyric != '') {
document.getElementById('lyric').innerHTML = lyric.replace(/\n/g, '<br />');
openLyric.style.opacity = "1";
openLyric.setAttribute('data-toggle', 'modal');
} else {
openLyric.style.opacity = "0.3";
openLyric.removeAttribute('data-toggle');
var modalLyric = document.getElementById('modalLyrics');
modalLyric.style.display = "none";
modalLyric.setAttribute('aria-hidden', 'true');
(document.getElementsByClassName('modal-backdrop')[0]) ? document.getElementsByClassName('modal-backdrop')[0].remove(): '';
}
} else {
document.getElementsByClassName('lyrics')[0].style.opacity = "0.3";
document.getElementsByClassName('lyrics')[0].removeAttribute('data-toggle');
}
}
xhttp.open('GET', 'https://api.vagalume.com.br/search.php?apikey=' + API_KEY + '&art=' + currentArtist + '&mus=' + currentSong.toLowerCase(), true);
xhttp.send()
}

API not responding

The app that I'm working on does not respond with the API address. I only get the ajax responding, but not the weather api that I'm trying to call.
I've tried everything that I could think of with my current knowledge.
let search = document.getElementById("search-bar");
let temp = document.getElementById("temperature");
let input = document.getElementById("input");
let city = document.getElementById("city");
const key = "";
input.addEventListener("keyup", enter);
function enter(event) {
if (event.key==="Enter") {
details();
}
}
function details() {
if (searchInput.value === ""){
} else {
let searchLink = "https://api.openweathermap.org/data/2.5/weather?q={}" + searchInput.value + "&appid=" + key;
httpRequestAsync(searchLink, talk)
}
}
function talk(talking){
let jsonObject = JSON.parse(talking);
city.innerHTML = jsonOject.name;
temp.innerHTML = parseInt(parseInt(jsonObject.main.temp - 273) + "°");
}
function httpRequestAsync(url,callback){
var httpRequest=new XMLHttpRequest();
httpRequest.onreadystatechange = () => {
if (httpRequest.readyState == 4 && httpRequest.status == 200)
callback(httpRequest.responseText);
}
request.open("GET", url, true); // true for asynchronous
request.send();
}
The expected outcome should be the weather api being called and displayed information in the console.
Try replacing last function with this:
function httpRequestAsync(url,callback){
var httpRequest=new XMLHttpRequest();
httpRequest.onreadystatechange = () => {
if (httpRequest.readyState == 4 && httpRequest.status == 200)
callback(httpRequest.responseText);
}
httpRequest.open("GET", url, true); // true for asynchronous
httpRequest.send();
}
I just corrected variable naming

How to concat two called endpoints to one string and print it in console

My function has to call two endpoints and concat them in one string at the same time. My code is simply a function that is getting two endpoints at the same time and print it in console.
But the same function has to concat them to one string.
I tried to create separated variables contains each call and then simply concat them, but the result hadn't been any different.
I read about it for couple of hours, and I see no, even the smallest tip anywhere.
EDIT: Please mind that each endpoint is an actual array.
function endpointsToOneString() {
const Http = new XMLHttpRequest();
const url = 'https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json';
Http.open("GET", url);
Http.send();
Http.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(Http.responseText)
}
}
const HttpTwo = new XMLHttpRequest();
const urlTwo = 'https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json';
HttpTwo.open("GET", urlTwo);
HttpTwo.send();
HttpTwo.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(Http.responseText)
}
}
}
endpointsToOneString();
In this case you should use Promise feature of javascript.
Here you can learn how to promisify your native XHR. Morever, Here you can find about promise chaining.
I have just added Promise in your code but it needs to be refactored.
Update: From comment, you want your response texts as a plain string. But we are actually getting a JSON array as response. So, we need to parse it using JSON.parse() function to make it an array object. Then we need to use .join() method to join all element of the array into a string. See the code below:
function endpointsToOneString() {
var requestOne = new Promise(function(resolve, reject){
const Http = new XMLHttpRequest();
const url = 'https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json';
Http.open("GET", url);
Http.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(Http.response);
} else {
reject({
status: this.status,
statusText: Http.statusText
});
}
};
Http.onerror = function () {
reject({
status: this.status,
statusText: Http.statusText
});
};
Http.send();
});
var requestTwo = new Promise(function(resolve, reject){
const HttpTwo = new XMLHttpRequest();
const urlTwo = 'https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json';
HttpTwo.open("GET", urlTwo);
HttpTwo.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(HttpTwo.response);
} else {
reject({
status: this.status,
statusText: HttpTwo.statusText
});
}
};
HttpTwo.onerror = function () {
reject({
status: this.status,
statusText: HttpTwo.statusText
});
};
HttpTwo.send();
});
Promise.all([
requestOne,
requestTwo
]).then(function(result){
var response = JSON.parse(result[0]).join();
response += JSON.parse(result[1]).join();
console.log(response);
});
}
endpointsToOneString();
I understand you want to concat the result of two parallel requests. In that case you can use a library like axios. From their docs
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// Both requests are now complete
}));
So for your example:
function getEndpoint1() {
return axios.get('https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json');
}
function getEndpoint2() {
return axios.get('https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json');
}
axios.all([getEndpoint1(), getEndpont2()])
.then(axios.spread(function (resp1, resp2) {
// Both requests are now complete
console.log(resp1 + resp2)
}));
try to have a look on the Promise.all method:
https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
As in this answer you should wrap your XHR in a Promise and then handle resolving of all function call. In this way you can access endpoint results in order.
Here's a working fiddle:
function makeRequest(method, url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = function() {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.response);
} else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function() {
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.send();
});
}
let url1 = 'https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json';
let url2 = 'https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json'
Promise.all([makeRequest('GET', url1), makeRequest('GET', url2)])
.then(values => {
debugger;
console.log(values);
});
https://jsfiddle.net/lbrutti/octys8k2/6/
Is it obligatory for you to use XMLHttpRequest? If not, u had better use fetch, because it returns Promise and with Promise it would be much simpler.
Rather than immediately printing them, save them to local variables, then print them at the end:
function endpointsToOneString() {
let response; // this line here declares the local variable
results = 0; // counts results, successful or not
const Http = new XMLHttpRequest();
const url = 'https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json';
Http.open("GET", url);
Http.send();
Http.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
response = Http.responseText; //save one string
}
if (this.readyState == 4) {
results++;
}
}
const HttpTwo = new XMLHttpRequest();
const urlTwo = 'https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json';
HttpTwo.open("GET", urlTwo);
HttpTwo.send();
HttpTwo.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
response += HttpTwo.responseText // save the other string
}
if (this.readyState == 4) {
results++;
}
}
while(results < 2) {} //loops until both requests finish, successful or not
console.log(response); //print total string
}
endpointsToOneString();
Also, HttpTwo's onreadystatechange function is calling for Http.responseText, rather than HttpTwo.responseText. Fix that as well for best results.
EDIT: Thanks for the tip, Jhon Pedroza!
EDIT: Noah B has pointed out that the above is dirty and inefficient. They are entirely correct. Better version based on their suggestion, credit to them:
function endpointsToOneString() {
let response1 = '', response2 = ''; // this line declares the local variables
const Http = new XMLHttpRequest();
const url = 'https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json';
Http.open("GET", url);
Http.send();
Http.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
response1 = Http.responseText; //save one string
checkResults(response1, response2);
}
}
const HttpTwo = new XMLHttpRequest();
const urlTwo = 'https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json';
HttpTwo.open("GET", urlTwo);
HttpTwo.send();
HttpTwo.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
response2 = HttpTwo.responseText; // save the other string
checkResults(response1, response2);
}
}
}
function checkResults(r1, r2) {
if (r1 != '' && r2 != '') {
console.log(r1 + r2);
}
}
endpointsToOneString();
function endpointsToOneString() {
var response;
const Http = new XMLHttpRequest();
const url = 'https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json';
Http.open("GET", url);
Http.send();
Http.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
response = this.responseText;
HttpTwo.open("GET", urlTwo);
HttpTwo.send();
}
}
const HttpTwo = new XMLHttpRequest();
const urlTwo = 'https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json';
HttpTwo.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
response += this.responseText;
console.log(response);
}
}
}
endpointsToOneString();
check this out. there's just minimal editing to your code.

js xml response return undifined

Please I need help !
To begin I don't speaking very well english sorry for the mistakes
So I'm tryng to receive a JSON Object with this code :
function uhttp(url){
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
console.log(xhr.response)
return xhr.response;
}
};
xhr.send();
console.log('exit')
};
but when I use the function https like this :
`
( ()=>{
var perso =uhttp('bd.php?table=charac')
for (var i = 0; i < perso.lenght; i++) {
document.getElementbyID('container').append('<ul>'+perso[i].nom+'</ul>')
}
})()
`
perso he's undifined...
here the console of index.html
I've the impression that we'are exit the function before that whe receive the resonse and that is why the function return a null
Of course before to ask my question I'have make some research but no one working in my case....
Thank you for yours anwsers
It happens because you aren't returning value from uhttp() function but from anonymous function (xhr.onload).
In order to access this value after the AJAX call is over use promises:
function uhttp(url){
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
return;
}
reject();
};
xhr.onerror = function() {
reject()
};
xhr.send();
})
}
And use it like so:
uhttp('bd.php?table=charac').then(function(result) {
var person = result;
for (var i = 0; i < perso.lenght; i++) {
document.getElementbyID('container').append('<ul>'+perso[i].nom+'</ul>');
}
}).catch(function() {
// Logic on error
});

Direct upload string to s3 from bootstrap modal not working

I observed a very strange behavior. If I set a button from web to upload string to S3, it works fine. But if I set a button from web to bring up a bootstrap modal, then from this modal I set a button to upload the string, it doesn't work.
Frontend is like below in both cases. The difference is whether clicking to run function 'saveToAWS' from web or from modal as 2-step-process, the latter returns xhr.status as 0.
function saveToAWS() {
var file = new File([jsonStr], "file.json", { type: "application/json" });
var xhr = new XMLHttpRequest();
var fn=file.name;
var ft = file.type;
xhr.open("GET", "/sign_s3_save?file-name=" + fn + "&file-type=" + ft);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
console.log('signiture returned')
save_file(file, response.signed_request, response.url);
}
else {
alert("Could not get signed URL.");
}
}
};
xhr.send();
}
function save_file(file, signed_request, url) {
var xhr = new XMLHttpRequest();
xhr.open('PUT', signed_request);
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log('200');
}
else {
alert('cannot upload file');
}
}
};
xhr.send(file);
}
Backend as Node.js, in order to get a signed URL:
app.get('/sign_s3_save', isLoggedIn, function (req, res) {
var fileName = req.query['file-name'];
var fileType = req.query['file-type'];
aws.config.update({ accessKeyId: AWS_ACCESS_KEY, secretAccessKey: AWS_SECRET_KEY });
var s3 = new aws.S3();
var ac = req.user._id;
var timenow = Date.now().toString();
var fileRename = ac + '/json/' + timenow + '.json';
var s3_params = {
Bucket: S3_BUCKET,
Key: fileRename,
Expires: 60,
ContentType: fileType,
ACL: 'public-read'
};
s3.getSignedUrl('putObject', s3_params, function (err, data) {
if (err) {
console.log(err);
}
else {
var return_data = {
signed_request: data,
url: 'https://' + S3_BUCKET + '.s3.amazonaws.com/' + fileRename
};
res.write(JSON.stringify(return_data));
res.end();
}
});
});
Any suggestion, please?

Categories

Resources