Closed mizzao closed 10 years ago
In meteor/meteor#2221 I suggested harmonizing the userId
APIs in method calls and publish functions, but it seems we'll need to convince @glasser of its value first.
Hey @matb33, I really need a function to determine whether the current dynamic scope was part of a publish function or not, so I added CollectionHooks.isWithinPublish()
while implementing this. Hope you don't mind - if anything looks strange, I'd be happy to adjust.
I added tests for this in addition to some of the existing find
/findOne
tests. However, I could not think of a reliable way to test whether the userId
is stored properly across yielding operations. I believe the current tests should suffice to ensure it's working, though - as long as Meteor.EnvironmentVariable
is behaving as intended.
This also fixed a potential error where if a publish function yielded, hooks that run in other fibers before the publish function returned would get a value for userId
when there shouldn't have been one. This led to a couple of hard-to-reproduce errors in my app, but I think I finally narrowed it down to this.
I was just reading some of our past discussions about collection hooks. In particular, in considering the use of global variables, it occurred to me that the value of
currentUserId
might be overwritten when yielding operations happen inside apublish
function and a differentpublish
function runs afind
operation. I don't thinkfind
itself yields, butforEach
probably would, and then afind
used after that might have the wronguserId
.I didn't know how to solve this at the time, but the proper solution to this would be to bind the publish
userId
in aMeteor.EnvironmentVariable
and call the original publish function using thewithValue
function of this variable. This would ensure that after any yielding operations, the function will still always see the sameuserId
.In fact, this is how
Meteor.userId()
itself is implemented; it's just too bad that it depends onDDP.currentInvocation
and is therefore not available in publish functions: https://github.com/meteor/meteor/blob/devel/packages/accounts-base/accounts_server.js#L7I can implement this and add a test for it when I get a moment - just writing it down for now.