I have a class called Stats
which contains the columns secondsPlayed
(number), createdAt
(date) and timeScore
(number)
This class contains thousands of objects but the timeScore
column is empty.
I want to populate the timeScore
column with a formula using the columns secondsPlayed
(number), createdAt
(date) like you would do in Excel. The formula is:
(secondsPlayed*10^8)/(Date.now()-createdAt.getTime())
As you can see the values of the timeScore
column should change every second since Date.now()
and secondsPlayed
are variables that are constantly changing.
Because of this I want to update and repopulate the timeScore
column every 5 minutes. This should happen automatically.
What is the best way to do this? I figured using cloud code to compute and populate the timeScore
column and then just get the timeScore
list with a simple Parse query would be best compared to downloading thousands of objects to each device and computing and updating every 5 minutes client side.
I dont know much about writing cloud code but by reading this guide and this SO question I came up with the following code.
const _ = require("underscore");
Parse.Cloud.define("timeScore", function(request, response) {
const query = new Parse.Query("Stats");
const maxSeconds = (Date.now() - new Date('2017-12-12T06:00:04.022Z').getTime())/1000;
query.lessThan("secondsPlayed", maxSeconds);
query.find().then(function(results) => {
_.each(results, function(result) {
var secondsPlayed = result.get("secondsPlayed") || 0;
var createdAt = result.get("createdAt") || new Date('2017-12-12T06:00:04.022Z');
result.set("timeScore", (secondsPlayed*100000000)/(Date.now()-createdAt.getTime()));
});
return Parse.Object.saveAll(results);
}).then(function(results) {
response.success(results);
}, function(error) {
response.error(error);
})
.catch(() => {
response.error("FAILED");
});
});
I do not know what to do with this code. I dont know how to test it or if it even works. How should I proceed?
Do I need to call it from the xamarin app? I just need the column to be populated and updated every 5 minutes according to the code. I should not need to call the cloud code from the app. I just want to query the timeScore
column from the app. Is this possible?