Polymerfire - Read document once - firebase

I was wondering if there is a way to retrieve a document just once, and avoid every kind of bidirectional sync with the database.
The Polymerfire documentation is poor, and I couldn't find it.
Thanks

No, the firebase-document element does not have a 'once' mode. However, you can easily drop down to the underlying JS SDK if you've already initialized the SDK with firebase-app:
Polymer({
is: 'my-element',
attached: function() {
firebase.database().ref('/path/to/doc')
.once('value').then(snap => this.data = snap.val());
}
});

I found another solution. You can check if the data are already loaded and then call the off() method on firebase reference, which disables all listeners.
Here are the important parts of code:
<firebase-document id="office_document" app-name="doctor-appointment-system" path="/offices/{{profileID}}" data="{{officeData}}">
</firebase-document>
dataNotLoaded: {
type: Boolean,
computed: 'computeDataAvailability(officeData)',
observer: 'disableReference'
}
computeDataAvailability: function (data) {
return Object.keys(data).length === 0;
}
disableReference: function (dataNotLoaded) {
if (!dataNotLoaded) {
this.$.office_document.ref.off();
}
},
I prefer this approach because it allows me to use Polymerfire and I needed to check if the data were loaded to disable paper-spinner so it didn't cause unnecessary complexity in my code.

Related

How can I be updated of an attribute change in Meteor?

I have a template that subscribes to a document. Everything works fine in the DOM and Blaze updates as soon as an attribute used in the template helpers is changed.
I also have some custom logic that doesn't appears in the DOM and depends on the document attributes. How can I call a function to change that logic when an attribute is updated?
I'm looking for something like this.data.attr.onChanged where this would refer to the template and this.data is the data send to the template, as usual; or a Meteor function that is rerun on change where I could put my callback in.
I hoped that template.onRendered would be recalled, but that's not the case.
I've read a lot about reactive variables, but could not find how they could be useful here.
[edit] the change is coming from the server that is communicating with another service
I've tried Tracker.autorun like this:
Template.editItem.onRendered(function() {
var self = this;
Tracker.autorun(function () {
console.log("tracker", self.data.item.socketId);
});
});
And the corresponding route is:
Router.route('editItem', {
path: '/edit/:_id',
waitOn: function () {
var sub = Meteor.subscribe('item', this.params._id);
return [sub];
},
data: function () {
return {item: Items.findOne(this.params._id)};
},
action: function () {
if (this.ready())
this.render();
}
});
At some point, the property socketId gets removed from the corresponding document by the server and I'm sure of that since I've checked in the shell, but the tracker doesn't rerun.
Use Template.currentData().item.socketId instead of self.data.item.socketId, this will give you reactivity.
And in templates generally, use self.autorun instead of Tracker.autorun (unlike Tracker.autorun, this will ensure that the autorun is stopped when the template is destroyed). Likewise, if you want to subscribe in a template, use self.subscribe instead of Meteor.subscribe.
Code to see if Template.currentData() works for you:
Template.editItem.onRendered(function() {
var self = this;
self.autorun(function () {
console.log("tracker", Template.currentData().item.socketId);
});
});
I'm not sure if I got you right, you just want to observe your html inputs and apply the new value to your helper method(s) on change?!
If so, you could use session variables to store your temporary UI state:
// observe your input
Template.yourTemplate.events({
"change #inputA": function (event) {
if(event.target.value != "") {
Session.set("valueA", event.target.value);
}
}
}
// apply the changed value on your helper function
Template.yourTemplate.helpers({
getSomeData: function() {
var a = Session.get("valueA");
// do something with a ..
}
}
In meteor's official todo app tutorial this concept is also used.
If you need to re-run something which is not part of DOM/helper, you can use Tracker.autorun. According to meteor docs, Run a function now and rerun it later whenever its dependencies change.
here's the docs link
Try moving the subscription into Tracker.autorun
Template.editItem.onRendered(function() {
var self = this;
Tracker.autorun(function () {
Meteor.subscribe('item', this.params._id);
console.log("tracker", self.data.item.socketId);
});
});
Of course you can't use this.params there so you can store this as a Session variable

Check if element has class only with Jasmine test framework

I am using webdriverJS and Jasmine to perform an end-to-end testing of a web page. I would like to test if an element has class under certain circumstances, but I would like to do it using methods from pure jasmine.
This is the part of the code where the issue is located:
describe('Header bar', function() {
it('should show/hide elements accoding to the window position', function() {
this.driver.executeScript('scroll(0, 1000)');
var elemSearch = this.driver.findElements(webdriver.By.id('animatedElement, animatedElement2, animatedElement3'));
expect(elemSearch).toContain('appear-2');
});
})
Do you know if there's a way to solve this issue, or a couple of examples I could look at, without using extensions like jasmine-jquery?
Thanks in advance for your replies!
If you don't want having jasmine-jquery or other third-party packages introducing custom jasmine matchers as a dependency, you can always extract the toHaveClass() matcher implementation and use it. Note that having your assertion logic encapsulated inside custom matchers helps to follow the DRY principle and make your tests cleaner.
FYI, here is toHaveClass implementation we are currently using:
beforeEach(function() {
jasmine.addMatchers({
toHaveClass: function() {
return {
compare: function(actual, expected) {
return {
pass: actual.getAttribute("class").then(function(classes) {
return classes.split(" ").indexOf(expected) !== -1;
})
};
}
};
},
});
});

Ability to update collections on front-end in Meteor

I'm struggling to get my head around the ability to edit any collection that's available to the front-end, and how to prevent it - and if this is a feature only available to Mongol.
Mongol states:
… because Mongol is a debugOnly package, it does not compile to production code.
Which is great, but as I'm new to Meteor I'm not sure if Mongol is just an interface in this scenario, or if the ability to update is something always available to the front-end (and Mongol is just making it easier).
My scenario is that I have a form submission page that grabs the profile of an associated Meteor.user to display their name along with the form:
HTML
<template name="form">
<h2>Submission for: {{ user.profile.name }}</h2>
<form id="brief">
…
</form>
</template>
Route
Router.route('/form/:_id', {
loadingTemplate: 'loading',
waitOn: function () {
return Meteor.subscribe('forms', this.params._id);
},
action: function () {
this.render('form', {
data: {
_id: this.params._id,
form: function() {
return Forms.findOne({});
},
user: function() {
return Meteor.users.findOne({});
}
}
});
}
});
Publication
Meteor.publishComposite('forms', function(formId) {
return {
find: function() {
return Forms.find({_id: formId});
},
children: [
{
find: function(form) {
return Meteor.users.find({_id: form.userId}, {fields: {profile:1}});
}
}
]
};
});
This works perfectly - however using the Mongol console I can update, duplicate and remove the user. Naturally in a production environment I wouldn't want this to be possible - is this something only available because Mongol is there, or could a determined user achieve the same thing without Mongol?
If they can, how do I prevent/work with it?
Edit: It's also elaborated on here: https://github.com/msavin/Mongol/blob/master/documentation/SECURITY.md
Given how they refer to 'special methods' I'm assuming that's what allows this to happen, and that the ability to directly update the fields isn't ordinarily available to the front-end. If anyone's able to confirm that would be ace!
Yes, Mongol uses a backdoor solution (in debug/dev only) to access and change your mongo docs in the db. This means it wont be included in your production code. As far as client side operations on the DB, Meteor restricts updating, removing, and inserting to the server although you can use Meteor's allow/deny rules to allow the client to update a DB collection. However, allow/deny rules need to be very tight to ensure the client can not alter data they should not be able to. For this reason, most people stick to using server side DB changes that are fired by meteor.methods that the client can initialize.
Since it is a debugOnly package as long as you don't deploy to production in "debug mode" it is safe.

Meteor performance: not sure if publication is causing the lag

My Meteor app runs slowly in the beginning for about ten seconds, and then becomes fast again. I am trying to improve the performance but having troubles to find the real cause.
I thought the problem was that I am publishing all the course information like following:
if (Meteor.isServer) {
Meteor.publish("courses", function() {
return Courses.find();
});
}
I tried using Kadira to monitor exactly what's happening. However, looking at the result, I am starting to think maybe it's not the real problem.
If it only takes 292ms for pubsub response time, it shouldn't feel that laggy but I cannot think of any other reason why the app would be so slow in the beginning and become fast again. Can an expert point me to the redirection?
UPDATE:
I could improve the duration of lagginess in the beginning by making the following changes:
in /server/publications.js
if (Meteor.isServer) {
Meteor.publish("courses", function() {
// since we only need these two fields for the search bar's autocomplete feature
return Courses.find({}, {fields: {'catalog':1, 'titleLong':1}});
});
Meteor.publish("courseCatalog", function(catalog) {
// publish specific information only when needed
return Courses.find({"catalog": catalog});
});
}
and in router.js I made changes accordingly so I subscribe based on specific pages. But there's still some lag in the beginning and I wonder if I can make more optimizations, and what is the real cause of the slowness in the beginning.
UPDATE2:
I followed the suggestion and made changes like below:
Session.set('coursesReady', false); on startup.
and in router:
Router.route('/', function () {
Meteor.subscribe("courses", function(err) {
if (!err) {
console.log("course data is ready")
Session.set('coursesReady', true);
}
});
....
and in /lib/helpers.js which returns data for typeahead library
if (Meteor.isClient) {
Template.registerHelper("course_data", function() {
console.log("course_data helper is called");
if (Session.get('coursesReady')) {
var courses = Courses.find().fetch();
return [
{
name: 'course-info1',
valueKey: 'titleLong',
local: function() {
return Courses.find().fetch();
},
template: 'Course'
},
But now the problem is that when the helper function is called, the data is never ready. The console print:
Q: How do I ensure that the helper function is called only after the data is ready, OR called again when the data is ready? Since Session is reactive, shouldn't it be called again automatically?
I can't check this right now, but I believe your issue might be that the course_data helper is being run multiple times before all 1000+ documents in the subscription are ready, causing the typeahead package to re-run some expensive calculations. Try something like this:
/client/views/global/helpers.js
Template.registerHelper("course_data", function() {
if (!Session.get('coursesReady')) return [];
return [ //...
/client/subscriptions.js
Meteor.subscribe("courses", function(error) {
if (!error) Session.set('coursesReady', true);
});
Update:
Really, Meteor's new features this.subscribe() and Template.instance().subscriptionsReady() are ideal for this. Session isn't really the right choice, but it should still be reactively updating (not sure why it isn't for you). Try instead making the following changes to /client/views/navwithsearch.js (and main, though ideally both templates should share a single search template):
Template.NavWithSearch.onCreated(function() {
this.subscribe('courses');
});
Template.NavWithSearch.onRendered(function() {
this.autorun(function() {
if (Template.instance().subscriptionsReady()) {
Meteor.typeahead.inject();
}
});
});
The idea is to tie the lifecycle of the subscription to the view that will actually be using that subscription. This should delay the typeahead injection until the subscription is completely ready.

How can I access the name of the current route in meteor when using meteor-router?

I'm building an app using meteor and meteor router, and I would like to make a template helper for checking if the route is a specific one ({{#ifRouteIs login}}{{/ifRouteIs}}).
I had the same issue. Building on your answer, I found a working solution. It needs to go in the client side of Meteor.
Handlebars.registerHelper('ifRouteIs', function (routeName, options) {
if (Meteor.Router.page() === routeName) {
return options.fn(this);
}
return options.inverse(this);
});
According to meteor-router's README, you can get the current page with Meteor.Router.page(), so the helper might look like this:
Handlebars.registerHelper('ifRouteIs', function (routeName) {
return Meteor.Router.page() === routeName;
});

Resources