Any example using firebase-document - firebase

I need to fetch data from a Firebase using firebase-document. I need to further process the data after I receive the response payload. How do I do this?
I read the documentation here, but there are no examples. I see there is a property called transactionsComplete but, again, no examples. Since it's a promise, I am uncertain how to implement it.
Can someone please provide a working code example of how to use the properties or methods of firebase-document to process the data returned by the request and after the transaction is complete?
<firebase-document
id="doc"
app-name="my-app">
</firebase-document>
<script>
_userChanged: function(u) {
if(u) {
var doc = this.$.doc;
var path = [ 'users' , u.uid ].join('/');
doc.path = path; // this should send a request for data
// but how do I ensure to process what is returned
// after and only after it comes back?
}
},
</script>

Binding the an object to the property data="{{object}}" then you can add an observer or computed property that will return the final value
<firebase-document
path="/users/{{userId}}/notes/{{noteId}}"
data="{{noteData}}">
</firebase-document>
Using firebase-focument method getStoredValue(path); (ES6 Style)
this.$.doc.getStoredValue(path)
.then((response) => {
console.log(response);
});

<!-- setup firebase-document (node) -->
<firebase-document
path="/dummy"
data="{{dummy}}">
</firebase-document>
<paper-input
id="dummy"
name="dummy"
label="Dummy Text"
value={{dummy.text}}>
</paper-input>
or you could use this.dummy inside a javascript function to access the variable.
Since it is using the data-binding of Polymer, value will be then updated to firebase.

Related

custom javascript cannot return client ID var google tag manager

I have tried to get the client ID with custom javascript but it cannot return the value. Below is the code is tried. Would like to seek help from all experts. Thanks.
function () {
return function () {
try {
var trackers = ga.getAll();
trackers.forEach(function(tracker) {
var cid = tracker.get('clientId');
tracker.set('dimension1', cid);
});
} catch (e) {}
}
}
It cannot return a normal client ID
Your custom variable returns a function, not a value (since the function is never actually executed).
A better way to get the clientId for each current tracker is to use a custom task in Google Analytics (tasks are basically individual steps in the tracker lifecycle, from checking if a client id exists to assemble the payload to actually sending the data). A task is a Javascript function that is added to the GA tag via the "set fields" configuration. Tasks have access to the tracker data model and can add, remove or modify values from the payload.
The only task you can use via GTM is the customTask, which as the name suggests, adds custom capabilities to the tracker.
If you create a custom javascript variable called e.g. "getClientId" with the following code:
function() {
// Modify customDimensionIndex to match the index number you want to send the data to
var customDimensionIndex = 5;
return function(model) {
model.set('dimension' + customDimensionIndex, model.get('clientId'));
}
}
then go to your GA settings tag, and in the "set field" configuration set the field name "customTask" with the variable as value, the clientId will be extracted from the data model and added to the payload as custom dimension.
Better than my explanation is Simo Ahavas GTM tip for setting the client id via custom tasks.

Firebase "child_added" event

I want a function to be called whenever a new child is added to "chat". I know this can be done using "child_added" event. However, from that function, I want to modify the newly created child.
So suppose a new child "123456" is added to chat and I want to update the "123456" object in the DB. I think I could solve the problem if I somehow manage to get the key (in this case it's 123456) of the newly added object. Is there a way to achieve this?
That should do the trick:
ref.on('child_added', function(childSnapshot, prevChildKey) {
var key = childSnapshot.key;
...
});
You will find more info at:
https://firebase.google.com/docs/reference/js/firebase.database.Query#on
u can also use firebase cloud functions as well by putting a trigger, so that this can be handled by server.
export const onNewChatTrigger = functions.database.ref('chat/{chatId}').onCreate(event => {
let key = event.params.chatId;
let data = event.data.val();
...
});

EmberFire: Getting property generated by Cloud Function when saving record completes

I use a Cloud Function to generate a short unique URL on a record on the 'onWrite' event, and save it. This works well, but when I save a record from my Ember app using EmberFire, I do get a model back as an argument to a callback, but the URL of this model is undefined. Is there a way to return this back to the client? Or do I need to query the record to get the generated URL?
This is how my Cloud Function code looks:
exports.generateUrl = functions.database.ref('/tournaments/{tid}')
.onWrite(event => {
if (event.data.previous.exists()) {
return;
}
if (!event.data.exists()) {
return;
}
const url = shortid.generate();
return event.data.ref.update({ url });
});
Here is my component that saves data through form submission. I'm using an add-on called ember-changeset to handle some validations, but this shouldn't be related to the issue.
export default Ember.Component.extend({
submit(e) {
e.preventDefault();
let snapshot = this.changeset.snapshot();
return this.changeset
.cast(Object.keys(this.get('schema')))
.validate()
.then(() => {
if (this.changeset.get('isValid')) {
return this.changeset
.save()
.then((result) => {
// Here, result.get('url') is undefined.
})
}
})
}
});
If you have a function that writes new data back to a location in the database after a write, you'll have to keep listening to that location on the client in order to get that data back. Don't use a one-time read (once()), use a persistent listener (on()), and in that listener, make sure you're getting the URL or whatever you expect to be generated by the function. Then remove that listener if you don't need it any more.
(Sorry, I don't know Ember or what abstractions it provides around Realtime Database - I'm giving you the plain JavaScript API methods you'd use on a reference.)

How to 'transform' data returned via a Meteor.publish?

Meteor Collections have a transform ability that allows behavior to be attached to the objects returned from mongo.
We want to have autopublish turned off so the client does not have access to the database collections, but we still want the transform functionality.
We are sending data to the client with a more explicit Meteor.publish/Meteor.subscribe or the RPC mechanism ( Meteor.call()/Meteor.methods() )
How can we have the Meteor client automatically apply a transform like it will when retrieving data directly with the Meteor.Collection methods?
While you can't directly use transforms, there is a way to transform the result of a database query before publishing it. This is what the "publish the current size of a collection" example describes here.
It took me a while to figure out a really simple application of that, so maybe my code will help you, too:
Meteor.publish("publicationsWithHTML", function (data) {
var self = this;
Publications
.find()
.forEach(function(entry) {
addSomeHTML(entry); // this function changes the content of entry
self.added("publications", entry._id, entry);
});
self.ready();
});
On the client you subscribe to this:
Meteor.subscribe("publicationsWithHTML");
But your model still need to create a collection (on both sides) that is called 'publications':
Publications = new Meteor.Collection('publications');
Mind you, this is not a very good example, as it doesn't maintain the reactivity. But I found the count example a bit confusing at first, so maybe you'll find it helpful.
(Meteor 0.7.0.1) - meteor does allow behavior to be attached to the objects returned via the pub/sub.
This is from a pull request I submitted to the meteor project.
Todos = new Meteor.Collection('todos', {
// transform allows behavior to be attached to the objects returned via the pub/sub communication.
transform : function(todo) {
todo.update = function(change) {
Meteor.call('Todos_update', this._id, change);
},
todo.remove = function() {
Meteor.call('Todos_remove', this._id);
}
return todo;
}
});
todosHandle = Meteor.subscribe('todos');
Any objects returned via the 'todos' topic will have the update() and the remove() function - which is exactly what I want: I now attach behavior to the returned data.
Try:
let transformTodo = (fields) => {
fields._pubType = 'todos';
return fields;
};
Meteor.publish('todos', function() {
let subHandle = Todos
.find()
.observeChanges({
added: (id, fields) => {
fields = transformTodo(fields);
this.added('todos', id, fields);
},
changed: (id, fields) => {
fields = transformTodo(fields);
this.changed('todos', id, fields);
},
removed: (id) => {
this.removed('todos', id);
}
});
this.ready();
this.onStop(() => {
subHandle.stop();
});
});
Currently, you can't apply transforms on the server to published collections. See this question for more details. That leaves you with either transforming the data on the client, or using a meteor method. In a method, you can have the server do whatever you want to the data.
In one of my projects, we perform our most expensive query (it joins several collections, denormalizes the documents, and trims unnecessary fields) via a method call. It isn't reactive, but it greatly simplifies our code because all of the transformation happens on the server.
To extend #Christian Fritz answer, with Reactive Solution using peerlibrary:reactive-publish
Meteor.publish("todos", function() {
const self = this;
return this.autorun(function(computation) {
// Loop over each document in collection
todo.find().forEach(function(entry) {
// Add function to transform / modify each document here
self.added("todos", entry._id, entry);
});
});
});

Meteor.js, extend an object when publishing it

I have messages collection.
Each message has an userId.
I also defined displayUsername() function, that gets the id of user, and returns fullName.
My question is can I extend it with underscorejs on the server. or what is pratical way to extend an Object
messages = new Meteor.Collection("messages");
Meteor.publish("messages", function () {
var allMessages = messages.find({}).fetch();
return _.each(allMessages, function (msg) {
return _.extend(msg, {
username: displayName(msg.userId)
});
});
so I want
{{#each messages}}
<p><strong>{{username}}:</strong> {{messageBody}}</p>
{{/each}}
I know, that it is possible on the client side, but I am going to use it some more time...
thanks..
check transform on Collection.find
http://docs.meteor.com/#find
chris has a video tut talk about "Transforming Collection Documents"
The transform option on Meteor Collections allows us to transform MongoDB documents before they're returned in a fetch, findOne or find call, and before they are passed to observer callbacks. It lays the foundation for a Model layer. In this episode I'll build a simple transform class that has a formatPrice method for a price that is stored as cents in the database.
http://www.eventedmind.com/posts/meteor-transforming-collection-documents
Unfortunately you can't send down a transformed collection. But you can transform it on the client side.
e.g when you define your collection on the client:
client side js
var messages = new Meteor.Collection("messages", {transform:function(doc) {
doc.username = displayName(doc.userId);
return doc;
}});

Resources