[Solved] `alanning:roles` and Publishing "Admin" data

So, in this app, regular clients can only see “Episodes” which have been “Published” - whereas the admin should be able to see everything. I’m using alanning:roles

and this code:

import { Roles } from 'meteor/alanning:roles'
Meteor.startup(() => {
  Meteor.publish('Episodes.active', (serialId, slug) => {
    let isAdmin = Roles.userIsInRole(this.userId, 'admin')

    if (isAdmin) {
      return Episodes.find({ serialId, slug })
    } else {
      return Episodes.find({ serialId, slug, published: true })
    }
  })
}

And it doesn’t work as expected. Anyone have any idea why? It basically doesn’t care that I’m logged in as an admin.

As soon as I posted this - I saw the fat arrow function… I think that’s my problem.

Edit: I’ve tested this and found the problem. Basically, here it’s probably better not to use a fat arrow function, because when you do - you lose the context of this. Here is the same code in a working pattern:

import { Roles } from 'meteor/alanning:roles'
Meteor.startup(function() { // Not using a fat arrow function here make console.log() work again.
  Meteor.publish('Episodes.active', function(serialId, slug) { // Not using a fat arrow function here...
    let isAdmin = Roles.userIsInRole(this.userId, 'admin') // ... allows this.userId to come back correctly instead of 'undefined'

    if (isAdmin) {
      return Episodes.find({ serialId, slug })
    } else {
      return Episodes.find({ serialId, slug, published: true })
    }
  })
}

Why have you wrapped your publish function inside Meteor.startup? Publish functions are not called until they are subscribed to from the client, so they don’t need to be inside Meteor.startup(). Longer explanation here.

1 Like

I’ll take a look at removing them and see how my app works. Thanks for the tip.

Short answer: Habit.

Longer answer: here