I have a class MongoQueryResolver
which contains a dictionary:
private queries: {[key: string]: (params) => any} = {};
This dictionary holds functions by a key, where each function is a query function to MongoDB.
I have created a decorator MongoQuery
which represents a mongo query function:
export function MongoQuery(queryName: string) {
return function decorator(target, key, func) {
target.register(queryName, func);
}
}
This decorator calls MongoQueryResolver#register
in order to register the query in the dictionary so I can use it by the query name.
Example of a MongoQuery function I created:
@MongoQuery(QueryType.GET_ALL_ENABLED)
public async getAllEnabled(params) {
const workersDb = MongoService.getBranch(Branches.WORKERS).db("workers");
const configCollection = await workersDb.collection('config');
const criteria: any = {isEnabled: true};
if (params.proxy) {
criteria.proxy = params.proxy;
}
return await configCollection.find(criteria).toArray();
}
and how I use it outside:
MyRoutes.get('/get-enabled', async (req, res) => {
const data = await MongoQueryResolver.resolve(QueryType.GET_ALL_ENABLED, {proxy: req.query.proxy});
res.json(data);
});
The issue
When my application inits, I print the dictionary on set:
set GET_ALL_ENABLED {
value: [Function: getAllEnabled],
writable: true,
enumerable: false,
configurable: true
}
{
GET_ALL_ENABLED: {
value: [Function: getAllEnabled],
writable: true,
enumerable: false,
configurable: true
}
}
But when I get to use the dictionary, its empty ..
I mark the class as a singleton by export default new MongoQueryResolver()
Why does it happen? seems like it's a new instance somehow?
import MongoQueryResolver from '../../services/mongo/mongo-query-resolver'