In the Node Meteor environment, I am using a settings singleton like this:
class settingsClass {
partner = undefined;
setPartner(name: string) {
return this.partner = name;
}
getPartner() {
if (this.partner) return this.partner
throw 'Partner is unknown'
}
}
export let Settings = new settingsClass()
I found out that this setting is shared between clients and method calls. What other option is there for a client and method call separated “global” namespace? I want to manage some environment without passing all via parameters, etc.
Based on the documentation the methods this conext
Inside your method invocation, this
is bound to a method invocation object, which provides the following:
So I might extend this object with my variable. But how can I access it from inside some function, without passing it all the way down?
function somecall() {
... ? // how to access method invocation object's property partner?
}
Meteor.methods({
'setpartner'(name) {
// @ts-ignore
this.partner = name
somecall()
}
})
you have some options here.
- you could put in a DB collection
- you can create a global Map, which has either userId, or connectionId (or both) keys and you store objects there - you need to be sure to clean this up
- you can access the connection object at
Meteor.default_server.sessions
- depending on which version of meteor you are using, this will either be an object or a Map
If you’re doing userId based keys, and need data to be available across connections, you should ensure that you either have a single server, or if load balancing, that you have sticky sessions enabled.
Of course if you are doing connectionId based keys, you won’t need to think about that
1 Like
Thank you @znewsham - I think using connectionId works for my case. But there is no way to get it outside from the Meteor.methods definition? I can pass it down, but that becomes quite a difficult job for complex structures.
function somecall() {
Meteor.default_server.sessions[ ... how do I get the connectionid? ]
}
Meteor.methods({
'setpartner'(name) {
somecall() // call without passing context / connectionid
}
})
You can do something like this from anywhere on the server
const invocation = DDP._CurrentPublicationInvocation.get() || DDP._CurrentMethodInvocation.get();
const session = invocation && (invocation._session || invocation.connection);
//session.id == connectionId
I would just pass it. It’s simple and clear.