When storing data on the Meteor.user() object and then accessing it in a template I find that I have a bunch of code that looks like:
Meteor.user() && Meteor.user().team && Meteor.user().team.number
Is there a way to functionalize this or make it shorter?
3 Likes
Refactor it into an object. You still need to write the multiple checks, but you’ll only need to do it once. Example:
User.prototype.fullName = function () {
// if we're using Auth0
if (this.services && this.services.auth0) {
return this.services.auth0.name;
// if we're using an HL7 FHIR HumanName resource
} else if (this.profile && this.profile.name && this.profile.name.text){
// the following assumes a Person, RelatedPerson, or Practitioner resource
// which only has a single name specified
return this.profile.name.text;
} else if (this.profile && this.profile.name){
// the following assumes a Patient resource
// where multiple names and aliases may be specified
return this.profile.name[0].text;
// if we're using traditional Meteor naming convention
} else if (this.profile && this.profile.fullName){
return this.profile.fullName;
} else {
return "---";
This file has been truncated. show original
1 Like
solo999
September 18, 2016, 6:50am
3
How about this:
((Meteor.user() || {}).team || {}).number
timw
September 18, 2016, 11:58am
4
I have struggled with this for quite a while as well. In the end, I decided to use the underscore.deep mixin for underscore.js.
See https://atmospherejs.com/practicalmeteor/underscore-deep
For example,
_.deep(Meteor.user(), "profile.emails.0.address")
will give you either the address or undefined
. It will not throw an error like “cannot find property “profile” of undefined”.
1 Like
timw
September 18, 2016, 11:59am
5
What would that even do? When there is not Meteor.user(), it tries to access the field “team” of an empty object?
vyky
September 18, 2016, 12:29pm
6
Create function:
function shorter (args,callback) {
if (Meteor.user() && Meteor.user().team && Meteor.user().team.number) {
return callback
} else {
return false
};
}
then,
shorter(args, function (err, id) {
// do something if Meteor.user() && Meteor.user().team && Meteor.user().team.number true
})
solo999
September 18, 2016, 6:57pm
7
This is the short notation of Meteor.user() && Meteor.user().team && Meteor.user().team.number
team of empty object will be undefined, so finally all this expression will be undefined if Meteor.user() is undefined. I do not know if it is what you asked about, but I am widely use it everywhere to shorten object checking…
1 Like