Worker thread issue with postMessage() - nativescript

In the worker thread, when I call postMessage() to send message back to the main thread - it's not allowing a single argument signature.
e.g. postMessage( { success: true } );
VisualCode is displaying a required signature of postMessage(any, string, transfer? );
I've got require('globals'); at the top of the worker file.
This is what I have so far:
require('globals'); // necessary to bootstrap tns modules on the new thread
onmessage = function(msg)
{
var request = msg.data;
var data = request.data;
var result = "OK";
var message : any = result !== undefined ? { success: true, src: result } : { };
postMessage( message ); // << problem
}

It's a little workaround, however I managed to fix it in my app by adding re-declared function signature in the beggining of the worker file like this:
declare function postMessage(message: any);
Hope it helps.

It is important to mention that the error you are seeing is most likely a compilation error as a result of using TypeScript.
The nativescript workers implementation should only take one argument as of the current version.
Add reference to node_modules/tns_core_modules/webworker.es2016.d.ts as they contain the proper definition

Related

Apollo server subscription not recognizing Async Iterable

I'm having an issue with Apollo GraphQL's subscription. When attempting to start the subscription I'm getting this in return:
"Subscription field must return Async Iterable. Received: { pubsub: { ee: [EventEmitter], subscriptions: {}, subIdCounter: 0 }, pullQueue: [], pushQueue: [], running: true, allSubscribed: null, eventsArray: [\"H-f_mUvS\"], return: [function return] }"
I have other subscriptions setup and are completely functional - so I can confirm the webserver is setup correctly.
I'm just curious if anyone else has ever ran onto this issue before.
Source code in PR diff (it's an open source project):
https://github.com/astronomer/houston-api/pull/165/files
error in playground
I don't think this is an issue specific to the PR you posted. I'd be surprised if any of the subscriptions were working as is.
Your subscribe function should return an AsyncIterable, as the error states. Since it returns a call to createPoller, createPoller should return an AsyncIterable. But here's what that function looks like:
export default function createPoller(
func,
pubsub,
interval = 5000, // Poll every 5 seconds
timeout = 3600000 // Kill after 1 hour
) {
// Gernate a random internal topic.
const topic = shortid.generate();
// Create an async iterator. This is what a subscription resolver expects to be returned.
const iterator = pubsub.asyncIterator(topic);
// Wrap the publish function on the pubsub object, pre-populating the topic.
const publish = bind(curry(pubsub.publish, 2)(topic), pubsub);
// Call the function once to get initial dataset.
func(publish);
// Then set up a timer to call the passed function. This is the poller.
const poll = setInterval(partial(func, publish), interval);
// If we are passed a timeout, kill subscription after that interval has passed.
const kill = setTimeout(iterator.return, timeout);
// Create a typical async iterator, but overwrite the return function
// and cancel the timer. The return function gets called by the apollo server
// when a subscription is cancelled.
return {
...iterator,
return: () => {
log.info(`Disconnecting subscription ${topic}`);
clearInterval(poll);
clearTimeout(kill);
return iterator.return();
}
};
}
So createPoller creates an AsyncIterable, but then creates a shallow copy of it and returns that. graphql-subscriptions uses iterall's isAsyncIterable for the check that's producing the error you're seeing. Because of the way isAsyncIterable works, a shallow copy won't fly. You can see this for yourself:
const { PubSub } = require('graphql-subscriptions')
const { isAsyncIterable } = require('iterall')
const pubSub = new PubSub()
const iterable = pubSub.asyncIterator('test')
const copy = { ...iterable }
console.log(isAsyncIterable(iterable)) // true
console.log(isAsyncIterable(copy)) // false
So, instead of returning a shallow copy, createPoller should just mutate the return method directly:
export default function createPoller(...) {
...
iterator.return = () => { ... }
return iterator
}

How to update an User with useMasterKey in Parse

Issue Description
I'm trying to update an User when another user click on my Xamarin button.
Then, I used Cloud Code to perform this but it doesnt work
My Code
Here is my complete JS code :
Parse.Cloud.beforeSave("Archive", function(request, response) {
Parse.serverURL = 'https://pg-app-0brffxkawi8lqvf2eyc2isqrs66zsu.scalabl.cloud/1/';
var status = request.object.get("status");
if (status == "validated") {
var event = request.object.get("event");
event.fetch({
success: function(myEvent) {
var coinsEvent = myEvent.get("coins");
var user = request.object.get("user");
user.fetch({
success: function(myUser, coinsEvent, user) {
var email = myUser.get("email");
var coinsUser = myUser.get("coins");
myUser.set("coins", coinsUser + coinsEvent);
return myUser.save(null, {useMasterKey:true});
}
});
}
});
}
response.success();
});
I think myUser.save(null, {useMasterKey:true}); should work
I actually have that error :
Dec 24, 2017, 12:27 GMT+1 - ERRORError generating response for [PUT] /1/classes/_User/1GPcqmn6Hd
"Cannot modify user 1GPcqmn6Hd."
{
"coins": 250
}
Environment Setup
Server
parse-server version : v2.3.3
Server: Sashido
Your success branch never calls response.success() which is a problem... though maybe not THE problem.
You are also doing 2 fetches inside a 'beforeSave' function which is not recommended. 'BeforeSave' must happen very quickly and fetches take time. I would consider thinking through other options.
If you really need to do it this way, consider doing a Parse.Query("event") with an include("user") and trigger the query with query.first({useMasterKey:true}).
Are you sure coinsEvent is what you think it is? Fetch only returns the object fetched... not sure that you can curry in other parameters. I would change your final success routine to (double checking that coinsEvent is valid):
success: function(myUser) {
var coinsUser = myUser.get("coins");
myUser.set("coins", coinsUser + coinsEvent);
return myUser.save(null, {useMasterKey:true}).then(_ => response.success());
}

Kendo-UI DataSource.read() not always making a GET request

I do have a kendo datasource which populates a kendo template.
var remoteTemplate = kendo.template($("#remotetemplate").html(), {
useWithBlock: false });
var remoteDatasource = new kendo.data.DataSource({
transport: {
read: {
url: 'Home/RemoteData',
}
},
change: function () {
$("#remotemovies tbody").html(kendo.render(remoteTemplate, this.view()));
}
});
A GET request is made to Home/RemoteData when we call the read method remoteDatasource.read()
One more read , another request is made to Home/RemoteData
I know this is not good , but I am trying to understand this :-)
remoteDatasource.read()
So far good , however once more time I call the read() , GET request is
not happening. Why is that? remoteDatasource.read()
No Get request here no matter how many times I call after this
Also I noticed the same behaviour with fetch() method.
Can someone explain me why is this behaviour? also what is the difference between read and fetch.
The read() method is supposed to request the remote service every time.
The fetch() method only requests the remote service the first time.
Your particular read() may not be requesting the remote service because it is caching. Can you try your request as a POST or set the configuration in transport.read.cache to false?
http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#configuration-transport.read.cache
It seems to optimize the behavior Kendo is limiting the number of calls to two if you call datasource.read() in successive lines. Which is fair as there is no need in practical scenario to have such a code.
Here are the two types of code i have written.
Scenario 1 : Calling the datasource.read() in response to a button click.
$("#remoteRequestBtn").click(function () {
var remoteTemplate = kendo.template($("#remotetemplate").html(), { useWithBlock: false });
var remoteDatasource = new kendo.data.DataSource({
transport: {
read: {
cache: false,
url: 'Home/RemoteData',
}
},
change: function () {
$("#remotemovies tbody").html(kendo.render(remoteTemplate, this.view()));
}
});
remoteDatasource.read();
});
Result : A Get request is called to the web api , whenever i click the button.
Scenario 2 : Calling multiple datasource.read() in response to a button click.
$("#remoteRequestBtn").click(function () {
var remoteTemplate = kendo.template($("#remotetemplate").html(), { useWithBlock: false });
var remoteDatasource = new kendo.data.DataSource({
transport: {
read: {
cache: true,
url: 'Home/RemoteData',
}
},
change: function () {
$("#remotemovies tbody").html(kendo.render(remoteTemplate, this.view()));
}
});
remoteDatasource.read();
remoteDatasource.read();
remoteDatasource.read();
remoteDatasource.read();
});
Note : I am calling the read method 4 times , Now if you ask me if this is a valid scenario :-) It is not :-)
Result : In this case i get only two GET requests (For the first and second read() , Rest of the reads are ignored )
As of now i would like to treat this as an optimization from the Kendo-UI side , unless someone comeback and correct it.
Special Thanks to JFlok & CodingWithSpike for giving right directions.
Does your change callback or any other Javascript throw an exception? Try removing your change handler function. I've seen issues in the past where if an uncaught exception is thrown while the DataSource is trying to process the server response, then the DataSource is left in a state where it thinks the previous request is still running (because it never finished due to the error) and won't do another request.

KnockoutJS with IE8, occasional problems with Stringify?

A number of our users are still on IE8. Some of them occasionally are reporting problems when trying to post data to our servers (via a big button labeled "SAVE").
There is a script error that IE8 shows, which is: Unexpected call to method or property access, always pointing to the same line in the KnockoutJS 2.2.0 (debug, for now) library, line 450, which is as follows:
return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space);
The method in my code that is at the root of the stack trace where this happens is this:
self.saveSingle = function (onSuccess, onFailure) {
ko.utils.arrayForEach(self.days(), function (day) {
day.close();
});
var jsonData = ko.toJSON(self);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: applicationLocation + "/api/assignmentapi/save",
data: jsonData,
success: function (data) {
self.status(data.Status);
self._isDirty(false);
ko.utils.arrayForEach(self.days(), function (day) {
day.clean();
});
if (onSuccess)
onSuccess();
},
error: function (data) {
onFailure();
},
dataType: "json"
});
};
We do strip out a number of properties that are not necessary to our POST as we convert the object to JSON, using this approach: http://www.knockmeout.net/2011/04/controlling-how-object-is-converted-to.html
OurType.prototype.toJSON = function () {
var copy = ko.toJS(this);
delete copy.someUnneededProperty1;
delete copy.someUnneededProperty2;
delete copy.someUnneededProperty3;
delete copy.someUnneededProperty4;
return copy;
}
When it fails, it fails consistently on the line
var jsonData = ko.toJSON(self);
Now here comes the real mess:
It's not consistently happening
It doesn't happen to all IE8 users
We can't consistently reproduce it
The structure of our model that we're serializing doesn't appear matter
The jscript.dll is the current version for IE8
I was also experiencing this issue. Digging deeper I found a few things:
It was only failing occasionally, I found this by running the code in the console
The code in the data-bind was trowing an exception except the message was being swallowed due to IE8 gobbling up the message when using a try {} finally {} block (without catch).
Removing the try finally revealed a cannot parse bindings message.
When I started to get close to figuring out the issue (digging deep into the knockout code) it seemed to disappear in front of my eyes. This is the section of code it was failing on, catching the exception at the end of the code:
ko.utils.extend(ko.bindingProvider.prototype, {
'nodeHasBindings': function(node) {
switch (node.nodeType) {
case 1: return node.getAttribute(defaultBindingAttributeName) != null; // Element
case 8: return ko.virtualElements.virtualNodeBindingValue(node) != null; // Comment node
default: return false;
}
},
'getBindings': function(node, bindingContext) {
var bindingsString = this['getBindingsString'](node, bindingContext);
return bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node) : null;
},
// The following function is only used internally by this default provider.
// It's not part of the interface definition for a general binding provider.
'getBindingsString': function(node, bindingContext) {
switch (node.nodeType) {
case 1: return node.getAttribute(defaultBindingAttributeName); // Element
case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node
default: return null;
}
},
// The following function is only used internally by this default provider.
// It's not part of the interface definition for a general binding provider.
'parseBindingsString': function(bindingsString, bindingContext, node) {
try {
var bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, this.bindingCache);
return bindingFunction(bindingContext, node);
} catch (ex) {
throw new Error("Unable to parse bindings.\nMessage: " + ex + ";\nBindings value: " + bindingsString);
}
}
});
But yea, it stopped becoming reproducible so I came up with a hack that I tested and works earlier, just retrying the data parsing. So this:
data-bind="value: ko.computed(function(){return ko.toJSON(appViewModel.model()[0])})"
Became this:
data-bind="value: ko.computed(function(){while (true) { try { var json = ko.toJSON(appViewModel.model()[0]); return json; }catch(e){}}})"
Yes, it's very yucky, but it seems to do the trick until our users no longer need IE8 or the Knockout issue is fixed.
I have no idea if this will fix it, but you can use the mapping plugin to go between JS and JSON:
var mapping = {
'ignore': ["propertyToIgnore", "alsoIgnoreThis"]
}
var viewModel = ko.mapping.toJS(data, mapping);
Taken from my answer to this question
I'd give this a try and see if it helps, as there's nothing obviously wrong in your approach.
Are you sure it's IE8 users who are hitting the issue? IE7 does not support JSON.stringify. You'll need to include the json2.js library to support IE7 and lower.

Stop Duplicate Ajax Submisions?

I am wondering what is the best way to stop duplciate submissions when using jquery and ajax?
I come up with 2 possible ways but not sure if these are the only 2.
On Ajax start disable all buttons till request is done. 2 problems I see with this though is I use jquery model dialog so I don't know how easy it would be to disable those button as I not sure if they have id's. Second I if the the request hangs the user has really no way to try again since all the buttons are disabled.
I am looking into something called AjaxQueue at this time I have no clue if it is what I need or how it works since the site where the plugin is apparently down for maintenance.
http://docs.jquery.com/AjaxQueue
Edit
I think this is a spin off of what I was looking at.
http://www.protofunc.com/scripts/jquery/ajaxManager/
The only problem I see with this ajaxManager is that I think I have to change all my $.post, $.get and $.ajax ones to their type.
But what happens if I need a special parameter from $.ajax? Or that fact I like using .post and .get.
Edit 2
I think it can take in all $.ajax options. I am still looking into it. However what I am unsure about now is can I use the same constructor for all requests that will use the same options.
First you have to construct/configure a new Ajaxmanager
//create an ajaxmanager named someAjaxProfileName
var someManagedAjax = $.manageAjax.create('someAjaxProfileName', {
queue: true,
cacheResponse: true
});
Or do I have to make the above every single time?
How about setting a flag when the user clicks the button? You will only clear the flag when the AJAX request completes successfully (in complete, which is called after the success and error callbacks), and you will only send an AJAX request if the flag is not set.
Related to AJAX queuing there is a plugin called jQuery Message Queuing that is very good. I've used it myself.
var requestSent = false;
jQuery("#buttonID").click(function() {
if(!requestSent) {
requestSent = true;
jQuery.ajax({
url: "http://example.com",
....,
timeout: timeoutValue,
complete: function() {
...
requestSent = false;
},
});
}
});
You can set a timeout value for long-running requests (value is in milliseconds) if you think your request has a possibility of hanging. If an timeout occurs, the error callback is called, after which the complete callback gets called.
You could store an active request in a variable, then clear it when there's a response.
var request; // Stores the XMLHTTPRequest object
$('#myButton').click(function() {
if(!request) { // Only send the AJAX request if there's no current request
request = $.ajax({ // Assign the XMLHTTPRequest object to the variable
url:...,
...,
complete: function() { request = null } // Clear variable after response
});
}
});
EDIT:
One nice thing about this, is that you could cancel long running requests using abort().
var request; // Stores the XMLHTTPRequest object
var timeout; // Stores timeout reference for long running requests
$('#myButton').click(function() {
if(!request) { // Only send the AJAX request if there's no current request
request = $.ajax({ // Assign the XMLHTTPRequest object to the variable
url:...,
...,
complete: function() { timeout = request = null } // Clear variables after response
});
timeout = setTimeout( function() {
if(request) request.abort(); // abort request
}, 10000 ); // after 10 seconds
}
});
$.xhrPool = {};
$.xhrPool['hash'] = []
$.ajaxSetup({
beforeSend: function(jqXHR,settings) {
var hash = settings.url+settings.data
if ( $.xhrPool['hash'].indexOf(hash) === -1 ){
jqXHR.url = settings.url;
jqXHR.data = settings.data;
$.xhrPool['hash'].push(hash);
}else{
console.log('Duplicate request cancelled!');
jqXHR.abort();
}
},
complete: function(jqXHR,settings) {
var hash = jqXHR.url+jqXHR.data
if (index > -1) {
$.xhrPool['hash'].splice(index, 1);
}
}
});

Resources