I am developing a REST API with my colleagues using Express.js and Mongoose.
For some of the Mongoose Model methods and statics we need the Express.js Request object as an added context information source, like the authenticated user currently doing the request.
What we currently do is attach a custom property called context to a Model's this context by prototyping Mongoose's Model function.
The issue is that we ran into a nasty bug that made us realise that while with Model.methods, who are called on Model instances, it works fine.
For Model.statics, who are called on the Model "class" which is implemented as a singleton though, the scope is shared by the whole app meaning that if you have concurrent requests, they will override each-other's this.context value if you have any async behaviour in the request processing.
Now my question is the following:
Express.js and Mongoose for keeping and accessing the request context in Model.statics and Model.methods functions ?Of course there are some possible hacks to simulate containment like:
Function.bind() every Model function to add the request context.
-> This would mean though that if Model.statics.a() internally makes a call to Model.statics.b(), function b() wouldn't have a this.context.
Use the with() {} statement on the request object and call every Model function within that scope.
-> Which would be pretty dirty and slow.
Create containers with separate scopes with the vm standard Node.js module.
-> Same as (2), performance would take a big hit.
Any ideas ? Thank you in advance !