In meteor.http.get method, How to wait for the page to load like say for 5 seconds - http

How to wait for the page to load like say for 5 seconds.
In my program the sites wait for browser checks for 5 seconds before showing the content, Hence I want my http.get(url) function to wait for at least 5 seconds.
Without wait it doesn't show any content.
Thanks.

Based upon your comments, I now understand what you are trying to do and have modified this answer.
Unfortunately, there is no way to configure Meteor HTTP (which really uses
request to make the service call) to "wait" after the request has been initiated before obtaining a response. The best thing for you to do is to check out PhantomJS. It is a headless browser that you can use to load and render the page and then access dynamically generated content via javascript.
Check out this answer for a brief PhantomJS example and you can use the gadicohen:phantomjs package to install for meteor.
On a side note, it can still be useful to use the below function to pause execution in Meteor, but of course this is not useful for what you are trying to solve.
Meteor._sleepForMs(5000); // pause execution for 5 seconds

the http package is built upon npm's request package. You can do it as such with the request package directly:
var request = require('request');
var reqOptions = {
url: path,
method: 'GET',
encoding: "utf8",
jar: false,
timeout: null,
body: null,
followRedirect: null,
followAllRedirects: null,
headers: {},
time:true
};
request(reqOptions, function(error, response, body) {
console.log("time: "+response.elapsedTime)
console.log(body.toString()); //res.content returned by http.get
});
require('sleep').sleep(5); //synchronously slowing execution
You might also be able to do the same by setting {time:true} in the npmOptions parameter of the http call and then synchronously

Related

PDFKIT not starting streaming on http response till I call doc.end()

I am using pdfkit to generate pdf at runtime and returning this in http response for download. I am able to download the file at browser end but the download dialog is not opening immediately. Instead its waiting till doc.end is called. I guess pdfkit is unable to push the stream efficiently. Has anybody else faced this? If yes, please guide.
Here is the sample code which I am trying
exports.testPdfKit = functions.https.onRequest((request, response) => {
//create pdf document
doc.pipe(response);
response.set('Content-Disposition', `attachment;filename=testpdfstream.pdf`);
response.writeHead(200, { 'Content-Type': 'application/pdf' })
const bigText = "some big text"
for (var i = 0; i < 1000; i++) {
console.log('inside iteration -',i)
doc.text(bigText);
doc.addPage();
}
doc.end()
});
I am implementing this functionality on firebase functions which uses expressjs internally for processing http requests. To generate bigger files at my end, streaming is must for me.
HTTP functions can not stream the input or output of the function. The entire request is delivered in one chunk of memory, and the response is collection and send back to the client in one chunk. The maximum size of both is 10MB. There are not workarounds for this limitation of Cloud Functions (but it does help you system scale better).
If you need streaming or websockets, you'll need to use a different product, such as app engine or compute engine.

Typeahead skips async request when typeahead's value already asynchronized

When i change typeahead's value and it's already asynchronized, the request not send, and it loads from the old response.
$('#MyTypeahead').typeahead('val', 'something');// Send async request
$('#MyTypeahead').typeahead('val', 'something else');// Send async request
$('#MyTypeahead').typeahead('val', 'something');// loads from the first one
For some reasons i need to async everytime typeahead's value changes
Undocumented, i had to clear remote cache every single search,
The solution is simply disabling cache
remote : { cache:false ...}

How to send delayed response (Slack api) with Google Apps Script webapp?

We have a small Google Apps Script webapp that handles Slack slash commands. It does some convenient things like adding, updating and querying records to our sheet, straight from Slack. Everything works just fine most of the time. However the Slack API expects an answer from the request in less than 3 seconds, or it will timeout. Our Google Apps Script is not always able to respond in that timeframe, which will only get worse as our sheet grows or our queries get more complicated.
The Slack API allows for the use of asynchronous calls using a delayed response, but that means that the Google Apps Script needs to respond immediately (within 3 seconds) and do some work in the background.
Now this is the problem
I can't figure out how to make an asynchronous call work in Google Apps Script
I know Workers are not supported in Google Apps Script and my solution below hits a wall because of ReferenceError: 'google' is not defined. (Just ignore the Payload class, it formats a Slack response)
function doPost(request) {
var responseUrl = request.parameter.response_url
// This is how I try to circumvent the lack of threads in Google Apps Script
google.script.run
// Send an asynchronous slack response with result
.withSuccessHandler(function(payload) {
UrlFetchApp.fetch(responseUrl, {
'method' : 'post',
'contentType': 'application/json',
'payload' : payload.toString()
});
})
// Send an asynchronous slack response with error message
.withFailureHandler(function(payload) {
UrlFetchApp.fetch(responseUrl, {
'method' : 'post',
'contentType': 'application/json',
'payload' : payload.toString()
});
})
// do work in the background
.sleep(5);
return new Payload("Let me think about this...").asResponse();
}
function sleep(seconds) {
Utilities.sleep(1000 * seconds);
return new Payload("I waited for " + seconds + " seconds");
}
Does anyone have any idea how to make this work? Are there any alternative solutions to handle an asynchronous request in Google Apps Script?
I'm not aware of any threading in Apps Script either and as you noticed google.script.run only works in the Apps Script frontend.
As a workaround you could use a Google Forms as your "task queue". I've put together a simple G-Form with one question and inspected its final version to get the appropriate parameter names and URL. Then I set an installable on-form-submit trigger to run my script. Here's my POC code:
function doPost(e) {
var form = 'https://docs.google.com/forms/d/e/1FAIpQLScWBM<my-form-id>CRxA/formResponse';
UrlFetchApp.fetch(form, {method:'POST', payload:'entry.505669405=' + e.parameter.example});
return ContentService.createTextOutput('OK');
}
function onForm(e) {
//triggered async from doPost via a Google Forms
SpreadsheetApp.getActive().getSheetByName('Sheet1').appendRow(e.values);
}
It worked fine on my tests and should suffice for your use case.

wordpress ajax keeps losing connections

I apologize for my being little more han a newbie in WP and ajax but I need your help. I'm not sure if it's a bug or it's simply me who cannot manage to find a solution.
I've the following situation.
I've a plugin that displays certain data from a remote mysql server. This data need to be updated periodically.
At the moment I've implemented this through AJAX, more or less, like this:
$.ajax({
type : "POST",
url: cktn_ajax_object.ajax_url,
data: params,
dataType: "json",
success: function(response) {
<< Update UI according to response >>
},
error: function(request, status, err) {
console.debug("[AjaxOnTimer Error] status: " + status);
}
});
where $.ajax is calling the relevant php script responsible for retrieving the remote mysql data. The PHP script duration is variable, according to the amount of data it fetches (Let's say, something between a few seconds and four or five minutes).
If I test the whole on my local machine, there is no problem. The ajax call duly and patiently awaits the (slow) response of the local PHP server (which is querying the remote mysql server) and eventually, upon completion, it updates my UI.
On the other hand, when I install my plugin on the production machine things don't work as expected. Just a few seconds after having placed my ajax call to the PHP server, I get the following error in the console of the browser:
Failed to load resource: connection lost. ---> admin-ajax.php
and my script fails leaving me no other clue than the word error in the 'status' parameter of the ajax call.
Apparently the heartbeat.lock-post is interfering with my ajax call.
Any idea of what am I doing wrong?
Add the following to functions.php to turn off heartbeat:
add_action( 'init', 'my_deregister_heartbeat', 1 );
function my_deregister_heartbeat() {
global $pagenow;
if ( 'post.php' != $pagenow && 'post-new.php' != $pagenow )
wp_deregister_script('heartbeat');
}
And restart the apache.
Not sure if your problem is solved. But if someone experience the same problem today, i've solved this using the Heartbeat Control plugin available here: https://wordpress.org/plugins/heartbeat-control/.

Meteor Modify Boilerplate Response with Iron Router

Using Iron Router I can add a route such as /index returns "INDEX CONTENT" from the server:
this.route('index', {
path: '/',
where: 'server',
action: function () {
this.response.end("INDEX CONTENT");
}
});
The default behaviour for a Meteor app is to return a boilerplate HTML file on the initial request to the server which contains the js/css etc required to run the web app.
What I would like to do, however, is place a string (ie "INDEX CONTENT" as above) within the boilerplate which would normally be returned by default if I hadn't added the route. To do this, I'd need to be able to modify a boilerplate response before it is sent to the client but after it is constructed by the standard meteor response mechanism.
Can anyone recommend a way to be able to do this?
You could try the inject-initial meteorite package.
From the docs:
Inject.rawModHtml(id, func). At injection time, calls func(html, res) with the full page HTML which it expects to be returned, in full, after modification. res is the current http connection response request.
I think you would use it like this.
Inject.rawModHtml('breakEverything', function(html) {
return "INDEX CONTENT";
});

Resources