Skip to content

Commit d485c94

Browse files
committed
This commit applies builder design pattern in the router/v2.py for readability and easy manipulation
1 parent 6edb9cd commit d485c94

File tree

1 file changed

+31
-12
lines changed

1 file changed

+31
-12
lines changed

app/routers/v2.py

Lines changed: 31 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""app.routers.v2"""
2+
from abc import ABCMeta, abstractclassmethod
23
import enum
34

45
from fastapi import APIRouter, HTTPException, Request
@@ -18,6 +19,33 @@ class Sources(str, enum.Enum):
1819
CSBS = "csbs"
1920
NYT = "nyt"
2021

22+
class IBuilder(metaclass=ABCMeta):
23+
@staticmethod
24+
@abstractclassmethod
25+
26+
def buildLatest():
27+
"Display latest confirmed, deaths and recoverd"
28+
def buildLocation():
29+
"Display location"
30+
31+
32+
class Builder(IBuilder):
33+
async def buildLatest(request: Request, source: Sources = Sources.JHU):
34+
locations = await request.state.source.get_all()
35+
return{
36+
"latest": {
37+
"confirmed": sum(map(lambda location: location.confirmed, locations)),
38+
"deaths": sum(map(lambda location: location.deaths, locations)),
39+
"recovered": sum(map(lambda location: location.recovered, locations)),
40+
}
41+
}
42+
43+
async def buildLocation( request: Request, timelines):
44+
locations = await request.state.source.get_all()
45+
return {
46+
"locations": [location.serialize(timelines) for location in locations],
47+
}
48+
2149

2250
@V2.get("/latest", response_model=LatestResponse)
2351
async def get_latest(
@@ -26,13 +54,9 @@ async def get_latest(
2654
"""
2755
Getting latest amount of total confirmed cases, deaths, and recoveries.
2856
"""
29-
locations = await request.state.source.get_all()
57+
3058
return {
31-
"latest": {
32-
"confirmed": sum(map(lambda location: location.confirmed, locations)),
33-
"deaths": sum(map(lambda location: location.deaths, locations)),
34-
"recovered": sum(map(lambda location: location.recovered, locations)),
35-
}
59+
Builder.buildLatest()
3660
}
3761

3862

@@ -81,12 +105,7 @@ async def get_locations(
81105

82106
# Return final serialized data.
83107
return {
84-
"latest": {
85-
"confirmed": sum(map(lambda location: location.confirmed, locations)),
86-
"deaths": sum(map(lambda location: location.deaths, locations)),
87-
"recovered": sum(map(lambda location: location.recovered, locations)),
88-
},
89-
"locations": [location.serialize(timelines) for location in locations],
108+
Builder.buildLatest, Builder.buildLocation( request, timelines)
90109
}
91110

92111

0 commit comments

Comments
 (0)