Loosing ember context in callback of third party library - ember.js

I have the following code in my route for receiving webocket updates of my models. The problem is that when this line executes
setTimeout(self.stompConnect, 10000);
I no longer have access to the Ember.Route Ember object at the top of the stompConnect method.
var self = this; //no longer pointing to my route
How can I maintain the ember context across the callback in a third pary library like this? This has nothing to do with websockets or the library because I had the same issue with another third party library that had a callback.
I guess I need to use .bind() or something but I don't know the correct syntax.
stompClient : null,
activate : function() {
this.stompConnect();
},
stompConnect : function() {
var self = this;
var connectCallback = function(frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/models/update', function(payload){
var model = JSON.parse(JSON.parse(payload.body));
var modelName = Object.keys(model)[0];
var modelPayload = model[modelName];
self.store.push(modelName, modelPayload);
});
};
var errorCallback = function (error) {
console.log('STOMP: ' + error);
setTimeout(self.stompConnect, 10000); //when stompConnect() is called, the ember context is lost :(
console.log('STOMP: Reconecting in 10 seconds');
};
var url = ... ;
var socket = new SockJS(url);
var stompClient = Stomp.over(socket);
stompClient.connect({}, connectCallback, errorCallback);
this.set('stompClient', stompClient);
},
deactivate : function() {
this.get('stompClient').disconnect();
},

Basically you have a callback inside a callback. So context needs to be passed in both callbacks. self will work in errorCallBack but needs to be set again to work in stompConnect. I would rather suggest using run.later to setTimeOut. So Here goes the code.
stompClient : null,
activate : function() {
this.stompConnect();
},
stompConnect : function() {
var self = this;
var connectCallback = function(frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/models/update', function(payload){
var model = JSON.parse(JSON.parse(payload.body));
var modelName = Object.keys(model)[0];
var modelPayload = model[modelName];
self.store.push(modelName, modelPayload);
});
};
var errorCallback = function (error) {
console.log('STOMP: ' + error);
Ember.run.later(this, this.stompConnect, 1000);
//or you can also use
//setTimeout(this.stompConnect.bind(this), 10000); when stompConnect() is called, the ember context is lost :(
console.log('STOMP: Reconecting in 10 seconds');
};
var url = ... ;
var socket = new SockJS(url);
var stompClient = Stomp.over(socket);
stompClient.connect({}, connectCallback, errorCallback.bind(this));
this.set('stompClient', stompClient);
},
deactivate : function() {
this.get('stompClient').disconnect();
}
I prefer using .bind() rather var self = this;. But it depends.

Related

Having trouble using Jest with external dependancies

I'm trying to test React with Flux code using Jest. I'm reasonably new to unit testing.
I think I'm doing something wrong with Mocking my dependancies (to be honest the mocking thing kind of confuses me).
Here is what I'm having trouble with:
//LoginStore-test.js
jest.dontMock('../../constants/LoginConstants');
jest.dontMock('jsonwebtoken');
jest.dontMock('underscore');
jest.dontMock('../LoginStore');
describe("login Store", function(){
var LoginConstants = require('../../constants/LoginConstants');
var AppDispatcher;
var LoginStore;
var callback;
var jwt = require('jsonwebtoken');
var _user = {
email: 'test#test.com'
};
//mock actions
var actionLogin = {
actionType: LoginConstants.LOGIN_USER,
'jwt': jwt.sign(_user, 'shhh', { expiresInMinutes: 60*5 })
};
beforeEach(function(){
AppDispatcher = require('../../dispatchers/AppDispatcher');
LoginStore = require('../LoginStore');
callback = AppDispatcher.register.mock.calls[0][0];
});
...
it('should save the user', function(){
callback(actionLogin);
var user = LoginStore.getUser();
expect(user).toEqual(_user);
});
});
});
LoginStore.js file:
var AppDispatcher = require('../dispatchers/AppDispatcher');
var BaseStore = require('./BaseStore');
var LoginConstants = require('../constants/LoginConstants.js');
var _ = require('underscore');
var jwt = require('jsonwebtoken');
//initiate some variables
var _user;
var _jwt;
var LoginStore = _.extend({}, BaseStore, {
getUser: function(){
return _user;
}
});
AppDispatcher.register(function(action){
switch(action.actionType){
case LoginConstants.LOGIN_USER:
//set the user
_user = jwt.decode(action.jwt);
//save the token
_jwt = action.jwt;
break;
//do nothing with the default
default:
return true;
}
LoginStore.emitChange();
return true;
});
module.exports = LoginStore;
The jsonwebtoken functionality doesn't seem to be working at all. If I log actionLogin.jwt it just returns undefined. Any idea what I'm doing wrong here?
Cheers
After a bit of searching around, and actually trying to figure out a different issue I found the answer. just add
"jest": {"modulePathIgnorePatterns": ["/node_modules/"]}
to your package.json file

Stubbing the mongoose save method on a model

I would like to stub the save method available to Mongoose models. Here's a sample model:
/* model.js */
var mongoose = require('mongoose');
var userSchema = mongoose.Schema({
username: {
type: String,
required: true
}
});
var User = mongoose.model('User', userSchema);
module.exports = User;
I have some helper function that will call the save method.
/* utils.js */
var User = require('./model');
module.exports = function(req, res) {
var username = req.body.username;
var user = new User({ username: username });
user.save(function(err) {
if (err) return res.end();
return res.sendStatus(201);
});
};
I would like to check that user.save is called inside my helper function using a unit test.
/* test.js */
var mongoose = require('mongoose');
var createUser = require('./utils');
var userModel = require('./model');
it('should do what...', function(done) {
var req = { username: 'Andrew' };
var res = { sendStatus: sinon.stub() };
var saveStub = sinon.stub(mongoose.Model.prototype, 'save');
saveStub.yields(null);
createUser(req, res);
// because `save` is asynchronous, it has proven necessary to place the
// expectations inside a setTimeout to run in the next turn of the event loop
setTimeout(function() {
expect(saveStub.called).to.equal(true);
expect(res.sendStatus.called).to.equal(true);
done();
}, 0)
});
I discovered var saveStub = sinon.stub(mongoose.Model.prototype, 'save') from here.
All is fine unless I try to add something to my saveStub, e.g. with saveStub.yields(null). If I wanted to simulate an error being passed to the save callback with saveStub.yields('mock error'), I get this error:
TypeError: Attempted to wrap undefined property undefined as function
The stack trace is totally unhelpful.
The research I've done
I attempted to refactor my model to gain access to the underlying user model, as recommended here. That yielded the same error for me. Here was my code for that attempt:
/* in model.js... */
var UserSchema = mongoose.model('User');
User._model = new UserSchema();
/* in test.js... */
var saveStub = sinon.stub(userModel._model, 'save');
I found that this solution didn't work for me at all. Maybe this is because I'm setting up my user model in a different way?
I've also tried Mockery following this guide and this one, but that was way more setup than I thought should be necessary, and made me question the value of spending the time to isolate the db.
My impression is that it all has to do with the mysterious way mongoose implements save. I've read something about it using npm hooks, which makes the save method a slippery thing to stub.
I've also heard of mockgoose, though I haven't attempted that solution yet. Anyone had success with that strategy? [EDIT: turns out mockgoose provides an in-memory database for ease of setup/teardown, but it does not solve the issue of stubbing.]
Any insight on how to resolve this issue would be very appreciated.
Here's the final configuration I developed, which uses a combination of sinon and mockery:
// Dependencies
var expect = require('chai').expect;
var sinon = require('sinon');
var mockery = require('mockery');
var reloadStub = require('../../../spec/utils/reloadStub');
describe('UNIT: userController.js', function() {
var reportErrorStub;
var controller;
var userModel;
before(function() {
// mock the error reporter
mockery.enable({
warnOnReplace: false,
warnOnUnregistered: false,
useCleanCache: true
});
// load controller and model
controller = require('./userController');
userModel = require('./userModel');
});
after(function() {
// disable mock after tests complete
mockery.disable();
});
describe('#createUser', function() {
var req;
var res;
var status;
var end;
var json;
// Stub `#save` for all these tests
before(function() {
sinon.stub(userModel.prototype, 'save');
});
// Stub out req and res
beforeEach(function() {
req = {
body: {
username: 'Andrew',
userID: 1
}
};
status = sinon.stub();
end = sinon.stub();
json = sinon.stub();
res = { status: status.returns({ end: end, json: json }) };
});
// Reset call count after each test
afterEach(function() {
userModel.prototype.save.reset();
});
// Restore after all tests finish
after(function() {
userModel.prototype.save.restore();
});
it('should call `User.save`', function(done) {
controller.createUser(req, res);
/**
* Since Mongoose's `new` is asynchronous, run our expectations on the
* next cycle of the event loop.
*/
setTimeout(function() {
expect(userModel.prototype.save.callCount).to.equal(1);
done();
}, 0);
});
}
}
Have you tried:
sinon.stub(userModel.prototype, 'save')
Also, where is the helper function getting called in the test? It looks like you define the function as the utils module, but call it as a method of a controller object. I'm assuming this has nothing to do with that error message, but it did make it harder to figure out when and where the stub was getting called.

Ember.run.debounce does not debounce

I am using Twitter Typeahead.js in a subcomponent in Ember which I feed a dataSource function (see below).
This dataSource function queries a remote server. This query I would like to have debounced in Ember which does not seem to work.
Does this have to do with the runloop? Anything I should wrap?
import Ember from 'ember';
export default Ember.Component.extend({
dataResponse: [],
dataSource: function () {
var component = this;
// function given to typeahead.js
return function (query, cb) {
var requestFunc = function () {
var encQuery = encodeURIComponent(query);
Ember.$.getJSON('/api/autocompletion?prefix=' + encQuery).then(function (result) {
// save results
component.set('dataResponse', result.autocompletion);
// map results
var mappedResult = Ember.$.map(result.autocompletion, function (item) {
return { value: item };
});
cb(mappedResult);
});
};
// this is not debounced, why? :|
Ember.run.debounce(this, requestFunc, 500); // debounce by 500ms
};
}.property()
});
Note: I do not use Bloodhound with Typeahead.js since I need access to the results. A custom solution seemed easier at first.
Debounce works by creating a unique key based on the context/function. When you call it subsequent times it compares the existing keys to the context/function key passed in. You are passing in a different function every time you call debounce, which is why it isn't working how you're expecting it to work.
Taking the advice from #Kingpin2k I refactored the code like this:
import Ember from 'ember';
export default Ember.Component.extend({
dataResponse: [],
dataSource: function () {
var component = this;
var queryString = null;
var callBack = null;
var requestFunc = function () {
var encQuery = encodeURIComponent(queryString);
Ember.$.getJSON('/api/autocompletion?prefix=' + encQuery).then(function (result) {
// save results
component.set('dataResponse', result.autocompletion);
var mappedResult = Ember.$.map(result.autocompletion, function (item) {
return { value: item };
});
callBack(mappedResult);
});
};
// function used for typeahead
return function (q, cb) {
queryString = q;
callBack = cb;
Ember.run.debounce(this, requestFunc, 500); // debounce by 500ms
};
}.property()
});

How do I write a findMany that will get in chunks?

Ember 1.5.1
Ember-Data 1.0 beta 7
I've tried to modify the DS.ActiveModelAdapter's findMany so it'll get in chunks of 40... this is because I can't use the links feature and it seems to be generating 400 errors because it has too many ids in the URL its creating.
I tried using this adapter, but I keep getting error messages that look like this:
Error: Assertion Failed: Error: no model was found for 'super'
Here's my Adapter:
App.ApplicationAdapter = DS.ActiveModelAdapter.extend({
findMany: function(store, type, ids) {
self = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
var idsPerRequest = 40;
var totalIdsLength = ids.length;
var numberOfBins = Math.ceil( totalIdsLength / idsPerRequest ); // number per bin
var bins = [];
ids.forEach( function(someId, index) {
var thisBinIndex = index % numberOfBins;
var thisBin = Ember.A( bins[thisBinIndex] );
thisBin.pushObject(someId);
bins[thisBinIndex] = thisBin;
});
var requestPromises = bins.map(function(binOfIds) {
return self.ajax(self.buildURL(type.typeKey), 'GET', { data: { ids: binOfIds } });
});
Ember.RSVP.all(requestPromises).then(function(resolvedBinRequests) {
var resolvedObjects = Em.A([]);
resolvedBinRequests.forEach(function(resolvedBin) {
resolvedObjects.addObjects(resolvedBin);
});
resolve(resolvedObjects);
}, function(error) {
reject(error);
});
});
}
});
Can anyone help me out with this? It'd be really appreciated. Am I just missing something obvious or have I perhaps done something silly?
Thanks in advance!
[edit] Okay so further to this I've figured out why it's not working, and that's because the response that's coming back is a promise for the JSON payload, but what I'm doing is joining multiples of these into an array and returning that... which obviously won't be right... but what I need to do is merge the arrays inside the objects returned into one, I think (in concept)... I'm not really sure how to do this in actuality, though... I've tried various things, but none of them seem to work well... :(
I'm not sure how much control you have over the back-end, but this seems like a perfect use case for using links instead of returning all of the ids.
App.Foo = DS.Model.extend({
bars: DS.hasMany('bar', {async:true})
});
App.Bar = DS.Model.extend({
name: DS.attr()
});
Then when you query for foo your json returns a link instead of a list of ids
{
foo: {
id:1,
links: {
bars: '/foo/1/bars' // or anything, you could put /bars?start=1&end=9000
}
}
}
Here's an example with 1000 relationship records hitting a simple endpoint:
http://emberjs.jsbin.com/OxIDiVU/579/edit
Okay so I finally worked out how to make this work.
I'll share my answer here for future posterity ;-)
Of interest is that the required response had to be a promise and it had to contain a straight up JS object, so I "munged" all the responses into one JS object and manually built the pluralized camelized type key... I wasn't sure how else to do this. So... sorry it's so hacky, but this actually works and lets me fix my app for now until the "links" feature is working again.
App.ApplicationAdapter = DS.ActiveModelAdapter.extend({
findMany: function(store, type, ids) {
self = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
var idsPerRequest = 40;
var totalIdsLength = ids.length;
var numberOfBins = Math.ceil( totalIdsLength / idsPerRequest ); // number per bin
var bins = [];
ids.forEach( function(someId, index) {
var thisBinIndex = index % numberOfBins;
var thisBin = Ember.A( bins[thisBinIndex] );
thisBin.pushObject(someId);
bins[thisBinIndex] = thisBin;
});
// build an array of promises, then resolve using Ember.RSVP.all
var requestPromises = bins.map(function(binOfIds) {
return self.ajax(self.buildURL(type.typeKey), 'GET', { data: { ids: binOfIds } });
});
// build the required return object, which is a promise containing a plain JS object
// note this can't be an Ember object
Ember.RSVP.all(requestPromises).then(function(resolvedBinRequests) {
var pluralizedDecamelizedTypeKey = type.typeKey.decamelize().pluralize();
var resolvedObjects = Em.A([]);
var returnObject = {};
returnObject[pluralizedDecamelizedTypeKey] = resolvedObjects;
resolvedBinRequests.forEach(function(resolvedBin) {
var theArray = resolvedBin[pluralizedDecamelizedTypeKey];
resolvedObjects.addObjects(theArray);
});
var responsePromise = Ember.RSVP.Promise.cast(returnObject);
resolve(responsePromise);
}, function(error) {
reject(error);
});
});
}
});
After some feedback I updated this response to attempt to extract the response payloads in the serializer instead of attempting to mimic the store's logic in the adapter.
http://emberjs.jsbin.com/wegiy/60/edit
App.ApplicationAdapter = DS.ActiveModelAdapter.extend({
findMany: function(store, type, ids) {
// build an array of promises, then resolve using Ember.RSVP.all
var idsPerRequest = 40;
var totalIdsLength = ids.length;
var numberOfBins = Math.ceil( totalIdsLength / idsPerRequest ); // number per bin
var bins = [];
ids.forEach( function(someId, index) {
var thisBinIndex = index % numberOfBins;
var thisBin = Ember.A( bins[thisBinIndex] );
thisBin.pushObject(someId);
bins[thisBinIndex] = thisBin;
});
var requestPromises = bins.map(function(binOfIds) {
return self.ajax(self.buildURL(type.typeKey), 'GET', { data: { ids: binOfIds } });
});
return Ember.RSVP.all(requestPromises);
}
});
App.ApplicationSerializer = DS.ActiveModelSerializer.extend({
extractFindMany: function(store, type, responsePayloads) {
// responsePayloads is the resolved value from the Ember.RSVP.all(requestPromises) promise
var serializer = this;
var extractedResponses = responsePayloads.map(function(payload) {
return serializer.extractArray(store, type, payload);
});
// extractedResponses is an array of arrays. We need to flatten it into 1 array.
return [].concat.apply([], extractedResponses);
}
});

Delay ember view render till $getJSON isLoaded

The problem with this code is that the render code is entered twice, and the buffer is not where I expect it. Even when I get the buffer, the stuff I push in is not rendered to the screen.
App.FilterView = Ember.View.extend({
init: function() {
var filter = this.get('filter');
this.set('content', App.ViewFilter.find(filter));
this._super();
},
render: function(buffer) {
var content = this.get('content');
if(!this.get('content.isLoaded')) { return; }
var keys = Object.keys(content.data);
keys.forEach(function(item) {
this.renderItem(buffer,content.data[item], item);
}, this);
}.observes('content.isLoaded'),
renderItem: function(buffer, item, key) {
buffer.push('<label for="' + key + '"> ' + item + '</label>');
}
});
And the App.ViewFilter.find()
App.ViewFilter = Ember.Object.extend();
App.ViewFilter.reopenClass({
find: function(o) {
var result = Ember.Object.create({
isLoaded: false,
data: ''
});
$.getJSON("http://localhost:3000/filter/" + o, function(response) {
result.set('data', response);
result.set('isLoaded', true);
});
return result;
}
});
I am getting the data I expect and once isLoaded triggers, everything runs, I am just not getting the HTML in my browser.
As it turns out the answer was close to what I had with using jquery then() on the $getJSON call. If you are new to promises, the documentation is not entirely straight forward. Here is what you need to know. You have to create an object outside the promise - that you will return immediately at the end and inside the promise you will have a function that updates that object once the data is returned. Like this:
App.Filter = Ember.Object.extend();
App.Filter.reopenClass({
find: function(o) {
var result = Ember.Object.create({
isLoaded: false,
data: Ember.Object.create()
});
$.getJSON("http://localhost:3000/filter/" + o).then(function(response) {
var controls = Em.A();
var keys = Ember.keys(response);
keys.forEach(function(key) {
controls.pushObject(App.FilterControl.create({
id: key,
label: response[key].label,
op: response[key].op,
content: response[key].content
})
);
});
result.set('data', controls);
result.set('isLoaded', true);
});
return result;
}
});
Whatever the function inside then(), is the callback routine that will be called once the data is returned. It needs to reference the object you created outside the $getJSON call and returned immediately. Then this works inside the view:
didInsertElement: function() {
if (this.get('content.isLoaded')) {
var model = this.get('content.data');
this.createFormView(model);
}
}.observes('content.isLoaded'),
createFormView: function(data) {
var self = this;
var filterController = App.FilterController.create({ model: data});
var filterView = Ember.View.create({
elementId: 'row-filter',
controller: filterController,
templateName: 'filter-form'
});
self.pushObject(filterView);
},
You can see a full app (and bit more complete/complicated) example here