We have a node-express app with multiple endpoints. We have created 5 different services that does different jobs such as making HTTP calls, process/modify data, cache data, search specific data, etc.
We realized that the services we created are not singleton. The services were being instantiated left right and center. A total of 26 objects were being created. We changed that and made all our services singleton, and now only 5 objects get created across the entire application. We want to structure the app properly now.
We want each express route to call DataService
(which checks if that data is available in the CacheService
, if not then make an HTTP call and store the data in cache and return the data to the express route). But, the current code makes use of CacheService
and DataService
together to check if the data is available in the cache or fetches fresh data using DataService
. Which approach is recommended? Use one service (Dataservice
) that internally uses multiple services (CacheService, DataModificationService
), or use all the services together in the express route (DataService, CacheService, DataModificationService
)
Before making the classes singleton, we were using static classes
. Do we even need to make services singleton or continue to use static classes? Which one is more recommended and why?
Here's the code that we've written to create a Singleton Service . Is this the correct way?
class DataService {
private dataModificationService: DataModificationService;
private tokenService: TokenService;
private constructor(tokenService: TokenService, dataModificationService: DataModificationService) {
this.tokenService = tokenService;
this.dataModificationService = dataModificationService;
}
public static getInstance(): DataService {
const dataModificationService: DataModificationService = DataModificationService.getInstance();
const tokenService: TokenService = TokenService.getInstance();
if (!DataService.instance) {
DataService.instance = new DataService(tokenService, dataModificationService);
}
return DataService.instance;
}
}
Aucun commentaire:
Enregistrer un commentaire