Get JSON from URL function - NativeScript - json

How to write the http module function to read data from local json file? I am now using this to read the data. I want the function to read the data from this url - http://localhost:8000/app/source.json
var observableModule = require("data/observable");
var source = require("./source.json");
var properties = require("./properties.json");
function HomeViewModel() {
var viewModel = new observableModule.Observable();
viewModel.set("categoricalSource", source.categoricalSource);
viewModel.set("categoryProperty", properties.categoryProperty);
viewModel.set("valueProperty", properties.valueProperty);
return viewModel;
}
module.exports = HomeViewModel;

To access localhost from the Android emulator, refer to Accessing localhost:port from Android emulator
In short - http://10.0.2.2:<hostport> replaces localhost:<hostport>
Refer to the NativeScript docs on http for making http requests. To access http://localhost:8000/app/source.json yours should look like so:
http.getJSON("http://10.0.2.2:8000/source.json").then(function (r) {
//// Argument (r) is JSON!
}, function (e) {
//// Argument (e) is Error!
//console.log(e);
});
And finally, if you need to read a JSON from the application directory, a require should suffice.

Related

How to load data from api if json changes? Watcher on json? Visualizing data with vue-chartjs and axios

I have built charts with vue-chartjs and fetch data from an api with axios. Currently i have a setInterval to load the JSON every 10 seconds. I want to avoid that and load data only if the json changes. How to do that? I tried to set a watcher on this.chart1Data, but did not work.
Here is the codesandbox: https://codesandbox.io/s/vue-chartjs-json-data-rnv2v?file=/src/App.vue
I think what you're looking for are WebSockets:
var socket = new WebSocket(urlToWebsocketServer);
// callback method is called when connection is established
socket.onopen = function () {
console.log("Connection established");
};
// callback method is called when a new websocket messages is received
socket.onmessage = function (messageEvent) {
console.log(messageEvent.data);
};
// callback method is called when there was an error
socket.onerror = function (errorEvent) {
console.log("Error! Connection was closed");
};
socket.onclose = function (closeEvent) {
console.log('Connection closed --- code: ' + closeEvent.code + ' --- reason: ' + closeEvent.reason);
};
I borrowed this code from wikipedia ;)
Edit: There are many tutorials out there. Just use Google. Maybe this one could be helpful

google actions sdk: using third party server to build templated responses

My Google Actions project points to a Google Cloud Function as a webhook. In the google cloud function I am able to create the conversation responses using conv.ask(...).
However, what I am trying to do is: build a generic conversation content framework that resides on another server (also google cloud function) where I would like to compose the response and send it back to the webhook function.
The relevant code in both these servers are like this:
// in the webhook function
app.intent('actions.intent.MAIN', (conv, input) => {
// here I would like to call the second google function by
// passing, say, the input and receiving a response that can
// be passed on to the conv
// something like
// assume request-promise is being used
//
var options = {
method: 'POST',
uri: '..',
body: {...},
json: true
};
rp(options)
.then(resp => {
conv.ask(resp) // this is what I would like to do
});
});
In the second Google Functions server, I am using express as middleware. Here on some logic templated responses get built
const ..
const {
SimpleResponse,
BasicCard,
...
} = require('actions-on-google');
...
const express = require('express');
var app = express();
...
app.post('/main', function(req, res, next) {
// here I would like to compose the response
// and send it to the earlier function
var convresp = new SimpleResponse({...});
..
res.send(convresp);
// this seems to be only sending the json
// and causes the receiving response to give an error
// when applying to conv.ask in the above code
});
Question is: how should the response be sent from the second function so that it can be "pasted" to the conv.ask functionality in the first function?. Thanks

How can we Read a local Json file in a html page without any server

I want to read a local Json file from a html page. But I am not able to read the local Json file in HTML page that work for chrome and IE.
Is there is any way to do it without using any web server.
Let's say you have,
index.html & sample.json in the same folder,
you can do this,
$http.get('sample.json').then(function(response) {
console.log(response);
});
of course you will need to run this from a controller, stand alone or in a directive, etc.
I found this solution on the web, i didn't try it but according to the comments it should work
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'my_data.json', true); // Replace 'my_data' with the path to your file
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
The function above will create a new instance of a XMLHttpRequest and load asynchronously the contents of my_data.json. I have gone with asynchronous but you can change the argument to false if you want a synchronous load. Thankfully all modern browsers support the native JSON.parse method. Remember our anonymous callback? here's how you use it.
function init() {
loadJSON(function(response) {
// Parse JSON string into object
var actual_JSON = JSON.parse(response);
});
}``
http://codepen.io/KryptoniteDove/post/load-json-file-locally-using-pure-javascript
Create a JSON file named sample.json in a translation folder .Then in controllers use the below code to get the values present in JSON file
$http.get('translation/sample.json').success(function(response){
console.log(response);
});
or
$.getJSON('translation/sample.json', function(data){
console.log(data);
});

How can I use ngCordova File api to save JSON?

I'm trying to save JSON data in my Ionic app to the local device storage. I would like to use the ngCordova File plugin. I can't seem to find any tutorials or example apps that use the exact methods they have in the docs.
Has anyone used this plugin before to save JSON data? How did you do it?
ngCordova takes away a lot of the ugliness of writing files using the file writer API.
This example has been adapted from the docs, and uses writeFile(path, file, data, replace) where the path is defined by cordova.file.DIRECTORY_TYPE, file is a string name for the file, data is the string representation of the data (so we will use JSON.stringify()). Replace is a boolean that will simply erase the existing contents of the file.
//Write using cordova.file.dataDirectory, see File System Layout section for more info
var json = {"test": "hello world"}
$cordovaFile.writeFile(cordova.file.dataDirectory, "hello.json", JSON.stringify(json), true)
.then(function (success) {
// success
}, function (error) {
// error
console.log(error); //error mappings are listed in the documentation
});
For a controller, supposing we are using controllerAs syntax it could look something like this:
angular.controller("...",['$cordovaFile' function ($cordovaFile) {
var vm = this;
vm.writeFile = function (fileName) {
ionic.Platform.ready(function(){
// will execute when device is ready, or immediately if the device is already ready.
var json = {"test": "hello world"}
$cordovaFile.writeFile(cordova.file.dataDirectory, "hello.json", JSON.stringify(json), true)
.then(function (success) {
// success
}, function (error) {
// error
console.log(error); //error mappings are listed in the documentation
});
});
};
});

How to log JSON HTTP Responses using Winston/Morgan

I'm using Winston and Morgan for all the back-end logging in Sails.js and I need to be able to log the responses from HTTP get requests. I need to log them in a file. My logFile currently takes shows all the http requests but it does not show the responses. I have searched all the options for Morgan and Winston and can't find a way/option to do this. I was just wondering if any of you had any advice on how to accomplish this?
Thanks!
You can write a middleware function for ExpressJS that will log the body once a response is sent. Basing it off of Node's http module to see how Connect (and therefore Express) manages the response body (which is a stream): you can hook into the two methods that write to that stream to grab the chunks and then concat/decode them to log it. Simple solution and could be made more robust but it shows the concept works.
function bodyLog(req, res, next) {
var write = res.write;
var end = res.end;
var chunks = [];
res.write = function newWrite(chunk) {
chunks.push(chunk);
write.apply(res, arguments);
};
res.end = function newEnd(chunk) {
if (chunk) { chunks.push(chunk); }
end.apply(res, arguments);
};
res.once('finish', function logIt() {
var body = Buffer.concat(chunks).toString('utf8');
// LOG BODY
});
next();
}
And then set it before any routes are assigned in the main app router:
app.use(bodyLog);
// assign routes
I would assume you could also use this as an assignment for a variable in Morgan but I haven't looked into how async variable assignment would work.