Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

consuming API JSon calls through TVJS-tvOS

I am trying to play with tvOS, and I have small question regarding handling json call. I have to get some data through an API, let's say for sake of test that I am calling this link

http://query.yahooapis.com/v1/public/yql?q=select%20item%20from%20weather.forecast%20where%20location%3D%223015%22&format=json

I tried to use this function with some modification

function getDocument(url) {
  var templateXHR = new XMLHttpRequest();
  templateXHR.responseType = "json";
  templateXHR.open("GET", url, true);
  templateXHR.send();
  return templateXHR;
}

but didn't work out. Any hints or help ?

If I need to use NodeJS, how can I do that ?

like image 483
user3378649 Avatar asked Sep 13 '15 19:09

user3378649


1 Answers

This is one that I got working. It's not ideal in many respects, but shows you something to get started with.

function jsonRequest(options) {

  var url = options.url;
  var method = options.method || 'GET';
  var headers = options.headers || {} ;
  var body = options.body || '';
  var callback = options.callback || function(err, data) {
    console.error("options.callback was missing for this request");
  };

  if (!url) {
    throw 'loadURL requires a url argument';
  }

  var xhr = new XMLHttpRequest();
  xhr.responseType = 'json';
  xhr.onreadystatechange = function() {
    try {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          callback(null, JSON.parse(xhr.responseText));
        } else {
          callback(new Error("Error [" + xhr.status + "] making http request: " + url));
        }
      }
    } catch (err) {
      console.error('Aborting request ' + url + '. Error: ' + err);
      xhr.abort();
      callback(new Error("Error making request to: " + url + " error: " + err));
    }
  };

  xhr.open(method, url, true);

  Object.keys(headers).forEach(function(key) {
    xhr.setRequestHeader(key, headers[key]);
  });

  xhr.send();

  return xhr;
}

And you can call it with the following example:

jsonRequest({
  url: 'https://api.github.com/users/staxmanade/repos',
  callback: function(err, data) {
    console.log(JSON.stringify(data[0], null, ' '));
  }
});

Hope this helps.

like image 154
Jason Jarrett Avatar answered Sep 21 '22 01:09

Jason Jarrett