How to update objects using Cloud Code? - json

I am using Parse Cloud Code for retrieving JSON data from external API. JSON data are updated every 2 min.
To accomplish this, I am using Cloud Job to run my method every 2 minutes to keep data fresh. Also, I am storing whole JSON data to Parse.
When I run this code for the first time everything works well, but... when code runs for second, third or fourth time instead of updating objects it creates the new ones.
How to update objects instead of creating the new ones, when there are some data?
Code:
Parse.Cloud.define("getCars", function(request, response) {
var promise = new Parse.Promise();
var Cars = Parse.Object.extend('Cars');
var query = new Parse.Query(Cars);
query.find().then(function (results){
Parse.Cloud.httpRequest({
method: 'GET',
url: urlLink,
success: function(httpResponse) {
var stations = new Array();
var data = JSON.parse(decodeURIComponent(escape(httpResponse.text))); // utf-8 decode
for (var i = 0; i < data.length; i++) {
var Cars = Parse.Object.extend('Cars'),
car = new Cars(),
content = data[i];
car.set('number', content.number);
car.set('name', content.name);
car.set('address', content.address);
car.set('position', content.position);
car.set('status', content.status);
cars.push(station);
};
Parse.Object.saveAll(cars, {
success: function(objects) {
promise.resolve();
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
promise.reject(error.message);
}
});
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
promise.reject(error.message);
}
});
});
return promise;
});
SOLUTION
I have finally found the solution. Maybe this will be useful for other people who are facing the same problem.
I added a simple if statement which checks query result. If query does not return data, new object is created, otherwise: old object is filled with new information and saved into database.
station = (results == 0) ? new Stations() : results[i];

you are createting new object car = new Cars(), every time.instead find with objectId and in success response you will get ParseObject list(array).
update first parseObject from that list

Related

Pass a random JSON pair into an aframe component

Edit 3: The code is now working across numerous objects (thanks to Noam) and he has also helped in getting the random function working alongside it. I'll update the code in the question once its implemented.
Edit 2: I've taken #Noam Almosnino's answer and am now trying to apply it to an Array with numerous objects (unsuccessfully). Here's the Remix link. Please help!
Edit: I've taken some feedback and found this page which talks about using a JSON.parse function. I've edited the code to reflect the new changes but I still can't figure out exactly whats missing.
Original: I thought this previous answer would help in my attempt to parse a json file and return a random string and its related pair (e.g Title-Platform), but I couldn't get it to work. My goal is to render the output as a text item in my scene. I've really enjoyed working with A-frame but am having a hard time finding documentation that can help me in this regard. I tried using the following modified script to get text from the Json file...
AFRAME.registerComponent('super', { // Not working
schema: {
Games: {type: 'array'},
jsonData: {
parse: JSON.parse,
stringify: JSON.stringify}
},
init: function () {
var el = this.el;
el.setAttribute('super', 'jsonData', {src:"https://cdn.glitch.com/b031cbf1-dd2b-4a85-84d5-09fd0cb747ab%2Ftrivia.json?1514896425219"});
var hugeArray = ["Title", "Platform",...];
const el.setAttribute('super', {Games: hugeArray});
el.setAttribute('position', {x:-2, y:2, z:-3});
}
});
The triggers are also set up in my html to render the text. My code is being worked on through glitch.com, any help will be much appreciated!
To load the json, I think you need to use an XMLHttpRequest (as Diego pointed out in the comments), when that's loaded, you can set the text through setAttribute.
Here's a basic example on glitch:
https://glitch.com/edit/#!/a-frame-json-to-text
On init it does the request, then when done, it set's the loaded json text onto the entity.
AFRAME.registerComponent('json-text-loader', {
schema: {},
init: function () {
var textEntity = document.querySelector('#text');
var url = 'json/text.json';
var request = new XMLHttpRequest();
request.open( 'GET', url, true );
request.addEventListener( 'load', function ( event ) {
var jsonText = JSON.parse( event.target.response )
textEntity.setAttribute("value", jsonText.text)
} );
request.send( null );
}
});
Updated version: https://glitch.com/edit/#!/peppermint-direction
AFRAME.registerComponent('json-text-loader', {
schema: {},
init: function () {
var textEntity = document.querySelector('#text');
var url = 'json/text.json';
var request = new XMLHttpRequest();
request.open( 'GET', url, true );
request.addEventListener( 'load', function ( event ) {
var games = JSON.parse( event.target.response ).games;
// Get a random game from the list
var randomGame = games[Math.floor(Math.random()*games.length)];
// Get the next game if it's available
var nextGame = null
if (games.indexOf(randomGame) < games.length - 1) {
nextGame = games[games.indexOf(randomGame) + 1]
}
// Build the string for the games
var gameInfo = randomGame.Title + '\n' + randomGame.Developer + '\n\n'
if (nextGame != null) {
gameInfo += nextGame.Title + '\n' + nextGame.Developer + '\n'
}
textEntity.setAttribute("value", gameInfo);
var sceneEl = document.querySelector('a-scene');
sceneEl.querySelector('a-box').setAttribute('material', {src:"https://cdn.glitch.com/4e63fbc2-a1b0-4e38-b37a-9870b5594af8%2FResident%20Evil.jpg?1514826910998"});
});
request.send( null );
}
});

Node.js - Store and retrieve PDF to MySQL as BLOB using pdfkit

I am having trouble storing a PDF content to MySQL as BLOB and retrieving it back from MySQL and stream it to front end using Node.JS.
I am able to save something to the DB (but not sure if I am saving the correct PDF content in the right manner). When I retrieve the pdf data, it does not open in PDF reader. I tried writing the retrieved data to a file and it also does not seem to work. Clear that either I am not storing the correct data to MySQL or I am not retrieving it in the correct way.
Could someone please help me out if you have come across similar scenario.
Code has been attached for your reference.
Many thanks.
var PDFDocument = require('pdfkit');
var doc = new PDFDocument;
var buffers = [];
doc.on('data', function(buff) {
buffers.push(buff);
});
doc.on('end', function () {
var queryToExec = "insert pdf_contents SET ? ";
var values = {
id : 0,//Auto Incrementing column
pdf: buffers.toString()
};
mysqlConnection.query(queryToExec, values, function(err, rows) {
if(!err) {
console.log("Stored to db successfully");
var selQuery = "select pdf from pdf_contents order by id desc limit 1"
mysqlConnection.query(selQuery, function(err_2, rows_2) {
if(!err_2) {
var myPdfDoc = rows_2[0].pdf;
console.log("Retrieved successfully, but pdf could not be opened!");
} else {
console.log("Error : ", err_2.toString());
}
});
} else {
console.log("Error : ", err.toString());
}
});
});
doc.addPage().text('Some text...', 100, 100);
doc.end();

Nodejs read JSON data from a http request chunk

I am using Jira API's to get data on single tickets. I have successfully setup a http GET request to the server and can display the data to the console however I ideally need to get certain properties from the data which is in JSON format.
When I try to read the properties I just get undefined.
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk); // This displays the JSON
console.log('endSTATUS: ' + chunk.id); // This shows up undefined
});
The data is in this format from jira API for reference.
The first console log in the res successfully displays all the data from the chunk.
The second one is:
endSTATUS: undefined
Try to get the body after the data stream finish. Like this:
var body = '';
response.on('data', function(d) {
body += d;
});
response.on('end', function() {
// Data reception is done, do whatever with it!
var parsed = JSON.parse(body);
console.log('endSTATUS: ' + parsed.id);
});
Make sure you are parsing the response data as JSON. I think you may want something like var data = JSON.parse(chunk);, and reference the chunk data as data.value.
res.on('data', function (chunk) {
var data = JSON.parse(chunk);
console.log('BODY: ' + data);
console.log('endSTATUS: ' + data.id);
});

Select specific data in JSON output

I've created a function that does a http request and then saves some data from the JSON output.
$scope.addMovie = function() {
'http://api.themoviedb.org/3/movie/206647?api_key=a8f7039633f2065942cd8a28d7cadad4&append_to_response=releases'
// Search for release dates using the ID.
var base = 'http://api.themoviedb.org/3/movie/';
var movieID = $(event.currentTarget).parent().find('.movieID').text()
var apiKey = 'a8f7039633f2065942cd8a28d7cadad4&query='
var append_to_response = '&append_to_response=releases'
var callback = 'JSON_CALLBACK'; // provided by angular.js
var url = base + movieID + '?api_key=' + apiKey + append_to_response + '&callback=' + callback;
$http.jsonp(url,{ cache: true}).
success(function(data, status, headers, config) {
if (status == 200) {
// $scope.movieListID = data.results;
$scope.movieListID = data;
console.log($scope.movieListID);
createMovie.create({
title: $scope.movieListID.original_title,
release_date: $scope.movieListID.release_date,
image: $scope.movieListID.poster_path
}).then(init);
} else {
console.error('Error happened while getting the movie list.')
}
})
};
This function saves the title, release date en posterpath and that works fine. The problem is that it only saves one release_date while the JSON output has a lot more, but I don't know how to acces that.
This is a example of the JSON output I request
It has a release_date, which I save now, but it also has more information,
releases":{
"countries":[
{"certification":"","iso_3166_1":"GB","primary":true,"release_date":"2015-10-26"},
{"certification":"","iso_3166_1":"US","primary":false,"release_date":"2015-11-06"},
{"certification":"","iso_3166_1":"NL","primary":false,"release_date":"2015-11-05"},
{"certification":"","iso_3166_1":"BR","primary":false,"release_date":"2015-11-05"},
{"certification":"","iso_3166_1":"SE","primary":false,"release_date":"2015-11-04"},
{"certification":"","iso_3166_1":"IE","primary":false,"release_date":"2015-10-26"},
How would I go about saving the release date for the NL release?
You just need to iterate through the countries array, and check if the country code matches the one you wish to retrieve. For your example with 'NL':
var releaseNL;
for (var i = 0; i < $scope.movieList.releases.countries.length; i++) {
var release = $scope.movieList.releases.countries[i];
if (release['iso_3166_1'] == 'NL') {
releaseNL = release;
}
}
This is just one of many ways to do this (e.g. you could use angular.forEach, wrap it inside a function, etc.), but this should give you an idea.
Remark: I noticed you have been asking a lot of very basic questions today, which you could easily answer yourself with a bit more research. E.g. this question is not even AngularJS related, but just a simple JavaScript task. So maybe try to show a bit more initiative next time! ;)

How to retrieve the data from database using Indexed DB

I have an existed database. I'm trying to retrieve the data from database using indexedDB but i'm unable to get the data from database.
var data = [];
// creating or opening the database
var db;
var request = window.indexedDB.open("database");
request.onerror = function(event) {
console.log("error: ");
};
request.onsuccess = function(event) {
db = request.result;
console.log("success: "+ db);
};
request.onupgradeneeded = function(event) {
var db = event.target.result;
var objectStore = db.createObjectStore("Subject", {keyPath: "id"});
for (var i in data) {
objectStore.add(data[i]);
}
}
function readAll() {
var objectStore = db.transaction("Subject").objectStore("Subject");
console.log(objectStore);
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
alert("Name for id " + cursor.key + " is " + cursor.value.Subject);
cursor.continue();
}
else {
alert("No more entries!");
}
};
}
Thanks in Advance.
You're pretty close.
var data = [];
I'll presume that you actually have some data somewhere, and that it indeed has an id attribute since you're specifying that as your index key e.g.
var data = [{id: 'foo' }, { id: 'bar' } ];
Now here:
var objectStore = db.createObjectStore("Subject", {keyPath: "id"});
for (var i in data) {
objectStore.add(data[i]);
}
(Careful with for..in and arrays)
I don't think you're actually adding any data here, which is one reason why you can't read it. To add data to an object store, try to first create a read/write transaction first and then get your reference to the object store and add your object.
var trans = db.transaction(["Subject"], "readwrite").objectStore("Subject");
Note the usage of an array as the first argument to transaction() and "readwrite" as the second param. (Some examples use the IDBTransaction.READ_WRITE constant but this doesn't seem to work with recent versions of Webkit.)
var objectStore = db.transaction("Subject").objectStore("Subject");
Try this instead:
var trans = db.transaction( [ "Subject" ] );
, objectStore = trans.objectStore( "Subject" );
objectStore.openCursor( IDBKeyRange.lowerBound(0) ).onsuccess = function(event) {..}
I did encountered the same error once. it occurs because at times the onSuccess is executed even before the result data is returned. So you should check if result data is empty.
To solve the issue try using oncomplete instead of onSuccess and also use Jquery indexedDB plugin. The plugin requires certin code changes but has more consistent implementation of indexedDB.
See http://nparashuram.com/jquery-indexeddb/