I'm trying to come up with a nice way to wrap each user I fetch from the Meteor Accounts Collection in a function, including a few prototype helper functions and counts from other collections, etc. The best way to describe this is in code.
The User function I want to wrap each user in would look something like this:
// - - - - - -
// USER OBJECT
// - - - - - -
var currentUser = null; // holds the currentUser object when aplicable
function User(fbId) {
var self = this,
u = (typeof id_or_obj == 'string' || id_or_obj instanceof String ? Meteor.users.findOne({'profile.facebook.id': id_or_obj}) : id_or_obj);
self.fb_id = parseInt(u.profile.facebook.id, 10),
// Basic info
self.first_name = u.profile.facebook.first_name,
self.last_name = u.profile.facebook.last_name,
self.name = u.name,
self.birthday = u.birthday,
self.email = u.profile.facebook.email,
// Quotes
self.likeCount = Likes.find({fb_id: self.fb_id}).count() || 0;
}
// - - - - - - -
// USER FUNCTIONS
// - - - - - - -
User.prototype = {
// Get users avatar
getAvatar: function() {
return '//graph.facebook.com/' + this.fb_id + '/picture';
},
getName: function(first_only) {
return (first_only ? this.first_name : this.name);
}
};
I can easily have a global 'currentUser' variable, that holds this information about the currently logged in user on the client side like this:
Meteor.autorun(function() {
if (Meteor.user()) {
currentUser = new User(Meteor.user().profile.facebook.id);
}
});
It's also easy to implement this into a Handlebars helper, replacing the use of {{currentUser}}
like this:
Handlebars.registerHelper('thisUser', function() {
if (Meteor.user()) {
return new User(Meteor.user());
} else {
return false;
}
});
What I want to do in addition to this is to make it so that when Meteor returns Meteor.user() or Meteor.users.find({}).fetch(), it includes these helper functions and short handles for first_name, last_name, etc.
Can I somehow extend Meteor.user() or is there some way to do this?
In Meteor 0.5.8, you can just tack on a transform function like so:
Meteor.users._transform = function(user) {
// attach methods, instantiate a user class, etc.
// return the object
// e.g.:
return new User(user);
}
You can do the same with non-user collections, but you can also do it this way when you instantiate the Collection:
Activities = new Meteor.Collection("Activities", {
transform: function (activity) { return new Activity(activity); }
});
(this way doesn't seem to work with the 'special' users collection)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With