Context:
Some years ago I decided to write a microservice in node with the fibers package, just for the sake of getting to know fibers better since the main application was built in Meteor. This experiment went very well, never had a single issue with fibers.
Today I’m writing code related with roles and permissions. In this new project there is the concept of a user belonging to an organisation. So, as you can imagine, for every method call, publication, etc. I’ve to check if the current user belongs to an organisation which implies a database query. I also need to provide the organisationId for every call because the user might switch the organisation.
Using Meteor.user()
is an expensive operation, it will query the database. So I had an idea that seems pretty possible to me but there must be something internally in Meteor that is blocking me.
With Meteor every websocket client is associated with a fiber. You can access the Fiber very easily:
const Fibers = require( 'fibers' );
Meteor.methods({
'showFiber'(){
console.log( Fibers.current );
}
});
You’ll find _meteor_dynamics
on Fiber.current with the userId. When you do Meteor.user()
on the server, this is how Meteor knows which user is using the current connection to the server.
Dream Goal;
If I could extend Fibers.current
with my own namespace, I could cache a roles/permission object and avoid several database queries. This would have some impact on the server memory but with a small object, i wouldn’t mind.
Even better, I could write my own: Meteor.myCurrentUser()
helper and use collection-helpers
to access my roles/permission on every single Method and Subscription,
If I track every login and logout on the server, I can add data to the right Fiber and remove it.
Problem:
Accounts.onLogin( ( info ) => {
_.extend( Fibers.current , {
__myapp_internals : {
userId : info.user._id
}
}
);
console.log( 'Fibers.current : ' , Fibers.current );
} );
I can see my context being assigned but when I call the method showFiber
, my context is gone. I’m pretty sure this is the same Fiber since I calling the method in Chrome with a user logged in. Kadira is able to add it’s own namespace called __kadiraInfo
but I’m not.
What am I missing here?
Took a look at Kadira and it seems that it hijacks and wraps the core functions, this is a behaviour that I would like to avoid if possible. Is there any naming convention not present in the docs?