Save data to cache using PHP - javascript

I'm working on an api, which I get the data from the db then display as json. The data is big and increases every second, I manage to lessen the load by saving it in localStorage on first load then just load the latest data on next fetch then add it to the localStorage. My problem is, it reached the max size of data. Is there a way to do it on php?
JS
if(index == 0){
localStorage.setItem("figureChart1-"+aid, JSON.stringify(data));
var arrseries1 = data['B5'];
var arrseries2 = data['B6'];
var datetime = data['datetime'];
} else {
var chart1Json = JSON.parse( localStorage.getItem( 'figureChart1-'+aid ) );
var obj = {};
obj['id'] = chart1Json['id'].concat(data['id']);
obj['datetime'] = chart1Json['datetime'].concat(data['datetime']);
obj['B5'] = chart1Json['B5'].concat(data['B5']);
obj['B6'] = chart1Json['B6'].concat(data['B6']);
localStorage.setItem("figureChart1-"+aid, JSON.stringify(obj));
var arrseries1 = obj['B5'];
var arrseries2 = obj['B6'];
var datetime = obj['datetime'];
}

Related

Put variable name in JSON Array (fetched by an api)

I am very new to Javascript but I will try to put this in convenient way. I am having this api where I am fetching the rank of a crypto (Ripple; currently ranked 7 and is subject to change overtime ), code below:
function myFunction() {
var url = "https://api.coinpaprika.com/v1/coins/xrp-xrp";
var XRPresponse = UrlFetchApp.fetch(url);
var XRPjson = XRPresponse.getContentText();
var XRPdata = JSON.parse(XRPjson);
var XRPrank = XRPdata.rank;
}
Now this is another function for an api where I extract other infos (having 5000+ crytos listed, including ripple)
function myXRP() {
var url = "https://api.coinpaprika.com/v1/tickers";
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json);
var XRP = data[7].symbol;
// Here instead of [7], I need to put the value extracted from XRPrank above so that whenever the rank is changed I get the latest value on data.[].
If someone could please advise.
In JavaScript there are several ways to achieve what you are looking for. The following is an adaptation of your current code with what I think are the minimal changes that you have to do, 1. use return followed by XRPrank 2. Call myFunction from myXRP and replace the data index by XRPrank.
function myFunction() {
var url = "https://api.coinpaprika.com/v1/coins/xrp-xrp";
var XRPresponse = UrlFetchApp.fetch(url);
var XRPjson = XRPresponse.getContentText();
var XRPdata = JSON.parse(XRPjson);
var XRPrank = XRPdata.rank;
return XRPrank; // add this
}
function myXRP() {
var url = "https://api.coinpaprika.com/v1/tickers";
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json);
var XRPrank = myFunction(); // add this
// var XRP = data[7].symbol; instead of this
var XRP = data[XRPrank].symbol; // use this
}
Resources
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions

Session.Create(FlowFile) Transfers with no content

I am trying to build a Excecute Script Processor for Nifi.
It handles a JSON file, splits it and sends it to the next processor, which is an MongoDB writer.
The logic works so far. The main problem is, that I cannot get the processor to create and send a new FlowFile for each new JSON created out of the input JSON. I got it working a bit but unfortunately, all the FlowFiles come out empty. Is there something wrong with the flow (from creation of a new Flow to sending it)?
Here is a code snippet:
var flowFile = session.get();
if (flowFile != null) {
var StreamCallback = Java.type("org.apache.nifi.processor.io.StreamCallback");
var IOUtils = Java.type("org.apache.commons.io.IOUtils");
var StandardCharsets = Java.type("java.nio.charset.StandardCharsets");
try {
flowFile = session.write(flowFile,
new StreamCallback(function (inputStream, outputStream) {
var content = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
var json = JSON.parse(content);
var events = json["events"];
var mongoEvent = "";
var flowFileList = [];
for(var x = 0; x < json["events"].length; x++){
try{
var newFlowFile = session.create();
mongoEvent = constructJSONEvent(x, json); // Here we will receive our new JSON
outputStream.write(mongoEvent.getBytes(StandardCharsets.UTF_8));
session.transfer(newFlowFile, REL_SUCCESS);
}catch(e){
session.transfer(newFlowFile, REL_FAILURE);
}
}
}));
session.transfer(flowFile, REL_SUCCESS);
} catch(e) {
session.transfer(flowFile, REL_FAILURE);
}
}

How to display data from localstorage using handlebars?

In my program i fetch data from console and store it in localstorage and webSQL . Now i want to display the stored data from localstorage using handlebar. I used the following code:
console.log(response); // To get data from console
var offer = JSON.stringify(response);
localStorage.setItem("object",offer); // saved in localstorage
var seasons= localStorage.getItem("object"); // get data from localstorage and saved in variable seasons
var mysource = document.getElementById("detailstemplate").innerHTML;
var mytemplate = Handlebars.compile(mysource);
var myresult = mytemplate(seasons);
document.getElementById("divOffers").innerHTML = myresult;
I used the last 4 lines to display data using handlebars. But it is not working. Please correct the error.Can anyone help with this?
var season = localStorage.getItem("cart");
var season2 = $.parseJSON(season);
var mytemp = $("#mainmenu-template").html(); // Grab the template script
var ourtemp = Handlebars.compile(mytemp); // Compile the template
var resultnew = ourtemp(season2);
$("#divMainMenu").append(resultnew);

How to update multiple fields in Firebase Web?

I have the following code where I want to update some simple values in my Firebase database using the JavaScript, Web SDK.
However, it doesn't run/update my database. What's wrong here?
var dbRef = firebase.database().ref().child('feeds').child(selectedFeed).child('audio');
var uid = dbRef.push().key;
var data = {
"downloadURL": uploadTask.snapshot.downloadURL,
"fileName": file.name,
"timeStamp": selectedDateUnix
};
var updates = {};
updates["mostRecentKey"] = uid;
updates[uid] = data;
dbRef.update(updates).then(function(){
//success
alert("Successfully Uploaded. This is now available to be listened to by your users.");
}).catch(function(error){
//failure
alert(error.message);
});
While it doesn't ever specify in the Firebase docs and actually I felt indicated it wasn't required; You MUST cast your data. For example:
This does not work. Directly accessing the variable.
var myNum = 10;
var data = {};
data["myNum"] = myNum;
This does work, but doesn't allow a dynamic use of a var.
var data = {};
data["myNum"] = 10;
Finally, this works and was my solution using a variable reference. Cast your data.
var myNum = 10;
var data = {};
data["myNum"] = Number(myNum);

Get String Value of Blob Passed to e.parameter in Apps Script

I'm using this code to get a blob passed to a function:
function submit(e){
var arrayBlob = e.parameter.arrayBlob;
Logger.log("arrayBlob #2 = " + arrayBlob.getDataAsString());
This is the error I get:
Execution failed: TypeError: Can not find getDataAsString function in
the Blob object.'arrayBlob'
How do I get the string value of this blob?
Here is my code:
function showList(folderID) {
var folder = DocsList.getFolderById(folderID);
var files = folder.getFiles();
var arrayList = [];
for (var file in files) {
file = files[file];
var thesesName = file.getName();
var thesesId = file.getId();
var thesesDoc = DocumentApp.openById(thesesId);
for (var child = 0; child < thesesDoc.getNumChildren(); child++){
var thesesFirstParagraph = thesesDoc.getChild(child);
var thesesType = thesesFirstParagraph.getText();
if (thesesType != ''){
var newArray = [thesesName, thesesType, thesesId];
arrayList.push(newArray);
break;
}
}
}
arrayList.sort();
var result = userProperties.getProperty('savedArray');
arrayList = JSON.stringify(arrayList);
var arrayBlob = Utilities.newBlob(arrayList);
Logger.log("arrayBlob #1 = " + arrayBlob.getDataAsString()); // Here it`s OK
var mydoc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication().setWidth(550).setHeight(450);
var panel = app.createVerticalPanel()
.setId('panel');
panel.add(app.createHidden('arrayBlob', arrayBlob));
var label = app.createLabel("Selecione os itens desejados").setStyleAttribute("fontSize", 18);
app.add(label);
arrayList = JSON.parse(arrayList);
panel.add(app.createHidden('checkbox_total', arrayList.length));
for(var i = 0; i < arrayList.length; i++){
var checkbox = app.createCheckBox().setName('checkbox_isChecked_'+i).setText(arrayList[i][0]);
Logger.log("arrayList[i][0] = " + arrayList[i][0]);
Logger.log("arrayList[i] ====> " + arrayList[i]);
panel.add(checkbox);
}
var handler = app.createServerHandler('submit').addCallbackElement(panel);
panel.add(app.createButton('Submit', handler));
var scroll = app.createScrollPanel().setPixelSize(500, 400);
scroll.add(panel);
app.add(scroll);
mydoc.show(app);
}
function submit(e){
var arrayBlob = e.parameter.arrayBlob;
Logger.log("arrayBlob #2 = " + arrayBlob.getDataAsString());
// Continues...
}
I'd like the solution worked with more than one user simultaneous using the script.
Update:
Add a global variable OUTSIDE of any function:
var arrayBlob = Utilities.newBlob("dummy data");
function showList(folderID) {
Code here ....
};
Check that the code has access to the blob:
function submit(e){
Logger.log("arrayBlob.getDataAsString(): " + arrayBlob.getDataAsString());
//More Code . . .
}
This solution eliminates the need of embedding a hidden element in the dialog box with a value of the blob.
You won't need this line:
panel.add(app.createHidden('arrayBlob', arrayBlob));
There are other changes I'd make to the code, but I simply want to show the main issue.
Old Info:
In the function showList(), the method getDataAsString() works on the blob named arrayBlob.
Logger.log("arrayBlob #1 = " + arrayBlob.getDataAsString()); // Here it`s OK
In the function, submit(), the same method does not work.
var arrayBlob = e.parameter.arrayBlob;
In the function showList(), the code is assigning a newBlob to the variable arrayBlob. So arrayBlob is available to have the getDataAsString() method used on it.
var arrayBlob = Utilities.newBlob(arrayList);
In the function, submit(), you are trying to pass the arrayBlob blob variable into the submit() function, and reference it with e.parameter.
If you put a Logger.log() statement in the submit() function.
function submit(e){
Logger.log('e: ' + e);
Logger.log('e.parameter` + e.parameter);
var arrayBlob = e.parameter.arrayBlob;
Those Logger.log statements should show something in them. If there is nothing in e.parameter, then there is nothing for the .getDataAsString() to work on.
It looks like you are putting the arrayBlob into a hidden panel.
panel.add(app.createHidden('arrayBlob', arrayBlob));
But when the object is getting passed to the submit(e) function, the arrayBlob might not be getting put into that object.
So, what I'm saying is, the:
Logger.log("arrayBlob #2 = " + arrayBlob.getDataAsString());
Line may be perfectly good, but there is no arrayBlob there to work on. This hasn't fixed your problem, but do you think I'm understanding part of what is going on?
I'm not sure why you are using Blob's here at all, you could simply work with JSON instead.
However, if you have a reason to use Blobs, you can pass the JSON data through your form and create the Blob in your handler, as the modified code below does:
function showList(folderID) {
var folder = DocsList.getFolderById(folderID);
var files = folder.getFiles();
var arrayList = [];
for (var file in files) {
file = files[file];
var thesesName = file.getName();
var thesesId = file.getId();
var thesesDoc = DocumentApp.openById(thesesId);
for (var child = 0; child < thesesDoc.getNumChildren(); child++){
var thesesFirstParagraph = thesesDoc.getChild(child);
var thesesType = thesesFirstParagraph.getText();
if (thesesType != ''){
var newArray = [thesesName, thesesType, thesesId];
arrayList.push(newArray);
break;
}
}
}
arrayList.sort();
var result = UserProperties.getProperty('savedArray');
//get JSON data pass through form.
var arrayBlob = JSON.stringify(arrayList);
var mydoc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication().setWidth(550).setHeight(450);
var panel = app.createVerticalPanel()
.setId('panel');
//include JSON Data in the form.
panel.add(app.createHidden('arrayBlob', arrayBlob));
var label = app.createLabel("Selecione os itens desejados").setStyleAttribute("fontSize", 18);
app.add(label);
panel.add(app.createHidden('checkbox_total', arrayList.length));
for(var i = 0; i < arrayList.length; i++){
var checkbox = app.createCheckBox().setName('checkbox_isChecked_'+i).setText(arrayList[i][0]);
Logger.log("arrayList[i][0] = " + arrayList[i][0]);
Logger.log("arrayList[i] ====> " + arrayList[i]);
panel.add(checkbox);
}
var handler = app.createServerHandler('submit').addCallbackElement(panel);
panel.add(app.createButton('Submit', handler));
var scroll = app.createScrollPanel().setPixelSize(500, 400);
scroll.add(panel);
app.add(scroll);
mydoc.show(app);
}
function submit(e){
var arrayBlob = Utilities.newBlob(e.parameter.arrayBlob);
Logger.log("arrayBlob #2 = " + arrayBlob.getDataAsString());
// Continues...
}
In the method you were using originally, the Blob itself was never included in the form, you were simply passing the string "Blob" around.
This is because the function createHidden(name, value); expects two strings as parameters, so it calls ".toString()" on the arrayBlob object, which returns the string "Blob".

Categories

Resources