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:
- What are the best practices with
Express.jsandMongoosefor keeping and accessing therequestcontext inModel.staticsandModel.methodsfunctions ?
Of course there are some possible hacks to simulate containment like:
Function.bind()everyModelfunction to add the request context.-> This would mean though that if
Model.statics.a()internally makes a call toModel.statics.b(), functionb()wouldn't have athis.context.Use the
with() {}statement on therequestobject and call everyModelfunction within that scope.-> Which would be pretty dirty and slow.
Create containers with separate scopes with the
vmstandard Node.js module.-> Same as (2), performance would take a big hit.
Any ideas ? Thank you in advance !