diff --git a/app/data/__init__.py b/app/data/__init__.py index 60a75dac..689af6d0 100644 --- a/app/data/__init__.py +++ b/app/data/__init__.py @@ -3,13 +3,7 @@ from ..services.location.jhu import JhuLocationService from ..services.location.nyt import NYTLocationService -# Mapping of services to data-sources. -DATA_SOURCES = { - "jhu": JhuLocationService(), - "csbs": CSBSLocationService(), - "nyt": NYTLocationService(), -} - +DATA_SOURCES = ['jhu', 'csbs', 'nyt'] def data_source(source): """ @@ -18,4 +12,13 @@ def data_source(source): :returns: The service. :rtype: LocationService """ - return DATA_SOURCES.get(source.lower()) + s = source.lower() + if s not in DATA_SOURCES: + return None + # return the singleton instance of the required service + if s == 'jhu': + return JhuLocationService.getInstance() + elif s == 'csbs': + return CSBSLocationService.getInstance() + elif s == 'nyt': + return NYTLocationService.getInstance() diff --git a/app/routers/v2.py b/app/routers/v2.py index 31eb408c..5b33bee0 100644 --- a/app/routers/v2.py +++ b/app/routers/v2.py @@ -107,4 +107,4 @@ async def sources(): """ Retrieves a list of data-sources that are availble to use. """ - return {"sources": list(DATA_SOURCES.keys())} + return {"sources": DATA_SOURCES)} diff --git a/app/services/location/__init__.py b/app/services/location/__init__.py index 6d292b54..9975ada9 100644 --- a/app/services/location/__init__.py +++ b/app/services/location/__init__.py @@ -7,6 +7,10 @@ class LocationService(ABC): Service for retrieving locations. """ + # this class variable will store the singleton instance for + # the LocationService instance from the child class + __instance__ = None + @abstractmethod async def get_all(self): """ @@ -26,3 +30,13 @@ async def get(self, id): # pylint: disable=redefined-builtin,invalid-name :rtype: Location """ raise NotImplementedError + + @classmethod + def getInstance(cls): + # singleton pattern + if cls.__instance__ is None: + # instantiate new object from the class (note that we are + # expecting 0 parameters for the constructor. if parameters + # needed this method should be overridden by the subclass) + cls.__instance__ = cls() + return cls.__instance__