Meteor 0.5.9: replacement for using Session in a server method? - session

So, I was attempting to do something like the following:
if(Meteor.isServer){
Meteor.methods({connect_to_api: function(vars){
// get data from remote API
return data;
}});
}
if(Meteor.isClient){
Template.myTpl.content = function(){
Meteor.call('connect_to_api', vars, function(err,data){
Session.set('placeholder', data);
});
return Session.get('placeholder');
};
}
This seemed to be working fine, but, of course, now breaks in 0.5.9 as the Session object has been removed from the server. How in the world do you now create a reactive Template that uses a server-only (stuff we don't want loading on the client) method call and get data back from that Method call. You can't put any Session references in the callback function because it doesn't exist on the server, and I don't know of any other reactive data sources available for this scenario.
I'm pretty new to Meteor, so I'm really trying to pin down best-practices stuff that has the best chance of being future-proof. Apparently the above implementation was not it.
EDIT: To clarify, this is not a problem of when I'm returning from the Template function. This is a problem of Session existing on the server. The above code will generate the following error message on the server:
Exception while invoking method 'connect_to_api' ReferenceError: Session is not defined
at Meteor.methods.connect_to_api (path/to/file.js:#:#)
at _.extend.protocol_handlers.method.exception ... etc etc

Setting the session in the callback seems to work fine, see this project I created on github: https://github.com/jtblin/meteor_session_test. In this example, I return data in a server method, and set it in the session in the callback.
There are 2 issues with your code:
1) Missing closing brace placement in Meteor.methods. The code should be:
Meteor.methods({
connect_to_api: function(vars) {
// get data from remote API
return data;
}
});
2) As explained above, you return the value in the session, before the callback is completed, i.e. before the callback method had the time to set the session variable. I guess this is why you don't see any data in the session variable yet.

I feel like an idiot (not the first time, not the last). Thanks to jtblin for showing me that Session.set does indeed work in the callback, I went back and scoured my Meteor.method function. Turns out there was one spot buried in the code where I was using Session.get which was what was throwing the error. Once I passed that value in from the client rather than trying to get it in the method itself, all was right with the world.
Oh, and you can indeed order things as above without issue.

Related

Creating a simple, basic page object in Nightwatch.js

Ok, so I've read up on the use of page_objects in nightwatch.js, but I'm still getting issues with it (which I'm convinced is due to something obvious and/or simple).
Using http://nightwatchjs.org/guide/#page-objects as the guide, I added the the file cookieremoval.js in my page_objects folder.
module.exports = {
elements: {
removeCookies: {
selector: '.banner_continue--2NyXA'
}
}
}
In my nightwatch.conf.js file I have;
page_objects_path: "tests/functional/config/page_objects",
And in my test script I have;
module.exports = {
"/cars/road-tax redirects to /car-tax/ ": browser => {
browser.url(browser.launch_url + browser.globals.carReviews)
.assert.urlEquals(browser.launchUrl + "/car-reviews/")
.waitForElementPresent('#cookieRemove', 3000)
.click('#cookieRemove')
.end();
},
};
However, when I run the test, I keep getting an error reading;
Timed out while waiting for element <#cookieRemove>
Any ideas why this is not working?
Many thanks
First of all, you never instantiated your page object. You're asking the browser object to search for an unknown element, that's why it's timing out. Your code should look something like this in your test script: var cookieRemoval = browser.page.cookieremoval(); then use this object to access those variables and functions in your page object. For example, if you wanted to access the remove cookie element, then you would do this cookieRemoval.click('#removeCookies');.
Secondly, you will have to know when to use the global browser object and when to use your page object. If you need to access something within your page object, obviously use the page object to call a function or access a variable. Otherwise, browser won't know the element you're looking for exists. Hope this help you out, I would definitely spend some more time learning about objects and specifically how they're used in nightwatch.js.

How does a Meteor database mutator know if it's being called from a Meteor.method vs. normal code?

If one does something on the client like
Foo.insert({blah : 1})
where Foo is a Meteor collection, this actually triggers a Meteor.method call as documented in the last paragraph of http://docs.meteor.com/#meteor_methods that executes code on both the client and the server.
However, let's say I define a method (on client and server) that does the same thing:
Meteor.methods({
bar: function() {
Foo.insert({blah : 1})
}
});
Now, I trigger this on the client with
Meteor.call("bar");
Foo.insert will now be called both on the client and the server as a result of the method. However, how does the client-side invocation of insert know not to call the server again, since it is itself a method?
Moreover, is there a way to call insert on the client side without automatically triggering the canonical server-side latency-compensation call and resulting synchronization? (For why I'd want to do this, see Loading a Meteor client app with fake fire-and-forget data)
The client side one becomes a 'stub'. It has this isSimulation property set that makes it appear as if the data is inserted for latency compensation.
I think if a .method is run on the client the latency compensation is always enabled and it shouldn't enter in the database. So anything running on a client side method would be a 'fake' type simulation
If you try setting this.isSimulation to false you'll get some weird error that shows you that the client side insert starts to throw errors with the insert.
I'm not too sure how to run it in a false simulation. I think you'd have to run it off in some other method var dothis = function() {...} type method.
To do this 'fake fire' & forget and have client side only data, which is what I presume (please correct if I'm wrong so I change the answer) modify the _collection property in your client side method.
e.g if you have
mydata = new Meteor.Collection("something");
function something() {
mydata.insert({..});
}
Modify the method to do this instead
mydata._collection.insert({..});
This will make sure that the data isn't synchronized to the server, yet will have the local collection have this 'fake data'.
Hope this helps!

Breezejs How to debug cause of TypeError in query response

I'm attempting to use Breeze to query a ASP.Net Web API endpoint and the query fails - with the data object containing:
internalError: TypeError
arguments: Array[2]
0: "createCtor"
1: null
length: 2
__proto__: Array[0]
get message: function () { [native code] }
get stack: function () { [native code] }
set message: function () { [native code] }
set stack: function () { [native code] }
type: "non_object_property_load"
The data object has a message (and responsetext) property which contains the full json response from the query which looks ok and the metadata thats been generated matches the response - it also records status 200 for the response
So I'm guessing there is some kind of issue mapping the response to an object on the client side?
I'm using the NuGet package for Breeze version 0.85.2
I can get the sample ToDo project to run fine on the same environment
My project does use domain objects, contexts etc all from different assemblies and namespaces but I understood thats supported in this version?
Also that one of the properties is an enum - in the metadata this is defined as {\"name\":\"State\",\"type\":\"Edm.Self.State\",\"nullable\":\"false\"}] but in the response is comes through as an integer
Looking for tips on how to debug this further on the client side
Update
comparing the working sample with my code, the error looks to be coming from this function:
/**
Returns the constructor for this EntityType.
#method getEntityCtor
#return {Function} The constructor for this EntityType.
**/
ctor.prototype.getEntityCtor = function () {
if (this._ctor) return this._ctor;
var typeRegistry = this.metadataStore._typeRegistry;
var aCtor = typeRegistry[this.name] || typeRegistry[this.shortName];
if (!aCtor) {
var createCtor = v_modelLibraryDef.defaultInstance.createCtor;
if (createCtor) {
aCtor = createCtor(this);
} else {
aCtor = function() {
};
}
}
this._setCtor(aCtor);
return aCtor;
};
The defaultInstance property on v_modelLibraryDef is undefined in my running code - what am I missing on the configuration of breeze for that to happen?
Update 2 - Resolved but why
Ok so I got this working - I was missing a reference to knockout (which I was planning to use but hadn't got that far) - I was a little bit misled by the breeze prerequisites which don't mention knockout so if anyone can explain how I could have got this working without knockout and if its a bug then the points are yours
Got same error, and referencing knockout.js helped(I'm using angularjs for my app)
manager.executeQuery(query).then(function(data) {
console.log(data);
});
But.
It seems, that data-mapper works with knockout by default, so we have XHR results as K.O. model with observables.
so I added breeze.config.initializeAdapterInstance("modelLibrary", "backingStore", true);
and now I don't receive data.results as observable collection.
Hope my answer will help.
Sorry you struggled Richard. We'll try to learn from it and spare the next person the pain you endured.
FWIW, we do not say that Knockout is a prerequisite ... because KO is not a prerequisite. You can use Angular or Backbone instead and we anticipate other alternatives in future.
We don't want to drown you in configuration options when you're just learning Breeze. So we picked KO as the default model library (just as jQuery is the default AJAX provider and Web API is the default "dataservice" technology). We say so in numerous places; prerequisites looks like another good place to mention it.
As it happens, you intended to go with KO anyway so no configuration would have been necessary. Most folks start with something like the MVC template which includes KO and loads it for you in the Index.cshtml.
Apparently you started from a clean slate ("ASP Empty Web Application" perhaps?). The Breeze Web API NuGet package strives to be spare and therefore does not include KO. We figured (incorrectly) that you would add it yourself ... in the right script order ... if you wanted to use KO. Clearly we could do a better job of documenting this particular development path ... especially as we like it so much ourselves. Thanks for pointing it out.
The other problem is that the exception was not helpful. You can see from other attempts to answer your question that even folks with Breeze experience couldn't recognize what was wrong. We'll look to see if we can detect the missing script a little earlier and throw an exception with a better message.
This error looks like it has to do with one of your Entity type constructors. I'm guessing that you are calling the 'registerEntityTypeCtor' method somewhere in your code. If so, then I would put a breakpoint in the constructor that you are registering there.
Per your other comment, .NET enums are supposed to get converted into integers on the breeze client. This is the only 'primitive' datatype that could support them. They will get converted back to enums on the server when you call 'EntityManager.saveChanges'
Breeze does not require 'knockout', you can use either 'angularjs' or 'backbone' as well. We simply default the breeze client to knockout if you do not specify another library. See the 'breeze.config.initializeAdapterInstance' topic here. We do need to a better job of documenting this.
Every time I get an error at which the Message property of the response is the data in json format means I have a bug in the function that runs after getting the data.
Example:
dataservice.getPalanca(routeData.PalancaID)
.then(function (data) {
self.palanca(data.results[0]);
})
.fail(function (error) {
console.log(error); /*if I get here and error.Message == correct json almost always means error in .then function*/
toastr.error("Ha ocurrido un error al obtener los datos");
});
I hope I help you.

Adding custom code to mootools addEvent

Even though I've been using mootools for a while now, I haven't really gotten into playing with the natives yet. Currently I'm trying to extend events by adding a custom addEvent method beside the original. I did that using the following code(copied from mootools core)
Native.implement([Element, Window, Document], {
addMyEvent:function(){/* code here */}
}
Now the problem is that I can't seem to figure out, how to properly overwrite the existing fireEvent method in a way that I can still call the orignal method after executing my own logic.
I could probably get the desired results with some ugly hacks but I'd prefer learning the elegant way :)
Update: Tried a couple of ugly hacks. None of them worked. Either I don't understand closures or I'm tweaking the wrong place. I tried saving Element.fireEvent to a temporary variable(with and without using closures), which I would then call from the overwritten fireEvent function(overwritten using Native.implement - the same as above). The result is an endless loop with fireEvent calling itself over and over again.
Update 2:
I followed the execution using firebug and it lead me to Native.genericize, which seems to act as a kind of proxy for the methods of native classes. So instead of referencing the actual fireEvent method, I referenced the proxy and that caused the infinite loop. Google didn't find any useful documentation about this and I'm a little wary about poking around under the hood when I don't completely understand how it works, so any help is much appreciated.
Update 3 - Original problem solved:
As I replied to Dimitar's comment below, I managed to solve the original problem by myself. I was trying to make a method for adding events that destroy themselves after a certain amount of executions. Although the original problem is solved, my question about extending natives remain.
Here's the finished code:
Native.implement([Element, Window, Document], {
addVolatileEvent:function(type,fn,counter,internal){
if(!counter)
counter=1;
var volatileFn=function(){
fn.run(arguments);
counter-=1;
if(counter<1)
{
this.removeEvent(type,volatileFn);
}
}
this.addEvent(type,volatileFn,internal);
}
});
is the name right? That's the best I could come up with my limited vocabulary.
document.id("clicker").addEvents({
"boobies": function() {
console.info("nipple police");
this.store("boobies", (this.retrieve("boobies")) ? this.retrieve("boobies") + 1 : 1);
if (this.retrieve("boobies") == 5)
this.removeEvents("boobies");
},
"click": function() {
// original function can callback boobies "even"
this.fireEvent("boobies");
// do usual stuff.
}
});
adding a simple event handler that counts the number of iterations it has gone through and then self-destroys.
think of events as simple callbacks under a particular key, some of which are bound to particular events that get fired up.
using element storage is always advisable if possible - it allows you to share data on the same element between different scopes w/o complex punctures or global variables.
Natives should not be modded like so, just do:
Element.implement({
newMethod: function() {
// this being the element
return this;
}
});
document.id("clicker").newMethod();
unless, of course, you need to define something that applies to window or document as well.

Ajax-Enabled WCF Only Intermittently Returns to Callback Function

I have an ajax-enabled WCF service that returns a set of JSON objects back to the browser. The service has a simple function that calls a business layer dll. This then returns the objects to the calling method.
Below is the service implementation (minus the Imports statements):
<ServiceContract(Namespace:="")> _
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
<ServiceBehavior(IncludeExceptionDetailInFaults:=True, MaxItemsInObjectGraph:=5000)> _
Public Class NoteService
<OperationContract()> _
Public Function GetAllInsuredNotes(ByVal insuredID As Integer) As List(Of NoteExport)
Dim allNotes As New List(Of NoteExport)
Using nr As New NoteRepository()
allNotes = nr.GetInsuredNotesForExport(insuredID)
If allNotes Is Nothing Then
Throw New InvalidOperationException("The operation to retrieve notes caused an error.")
End If
End Using
Return allNotes.ToList()
End Function
The Javascript to call my service is as follows:
function exportToExcel(sender, eventArgs) {
var insuredID = $('input[id*=hdnInsuredID]').val();
NoteService.GetAllInsuredNotes(insuredID, OnNoteGetSuccess, OnNoteGetFailure, null);
}
function OnNoteGetSuccess(result) {
var insuredID = $('input[id*=hdnInsuredID]').val();
OutputExcel(insuredID, result);
return true;
}
function OnNoteGetFailure(result) {
alert('There was an error retrieving notes for export. Please contact the help desk for assistance.');
return false;
}
Basically my problem is this. Everything seems to work fine from the server side function standpoint. Every time I call the function client side, the server side code executes and the result is generated. However, the success callback function only gets called periodically. I can invoke the function several times and only have the callback executed once. The problem seems to grow worse the larger the result set returned.
I could understand if it was related to the MaxObjectsInGraph setting, but the problem isn't that the result never comes back if I have a large amount of data. It will come back sometimes every forth or fifth try, sometimes 2 tries in a row, sometimes 1 in ten tries. It seems very random.
I have spent at least 2 days racking my brain on this one and can't seem to discover the solution. Does anyone have any insight on this?
Ok, I figured out what was happening and thought I'd post it here in case anyone else experiences this kind of issue. Using fiddler was the tool that put me on the right track.
Basically, the link button I was using to make the call to the javascript function was calling a full page postback, not just calling the javascript function. So if the request was small enough, the response to the web service call came quickly and the web page ran the callback function with the new JSON data it received. As the data sets got larger, sometimes the response would come back in time for the page to process the results. However, sometimes the response wouldn't come back until the full page postback was complete and the reference to the callback function was lost. So it would get back the JSON data but wouldn't know what to do with it.
So I had the javascript function called by the link button always return false to cancel the post back and the problem was solved.
I only had one other issue to deal with and that was setting the MaxObjectsInGraph setting for the service to a high enough value to account for the JSON size coming back. The only thing I still find odd is that if this setting was not high enough, I would get a challenge response box asking for a login name for the first couple of attempts, then the service would just come back with an unknown status code.
In any case, I hope this post proves helpful to someone else.
I don't think we can help you figure it out either unless we have the JavaScript definition for
NoteService.GetAllInsuredNotes(insuredId, CallBack1, CallBack2, WhatIsThisParam)

Resources