forked from stapi-spec/stapi-fastapi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroot_router.py
More file actions
270 lines (248 loc) · 9.39 KB
/
Copy pathroot_router.py
File metadata and controls
270 lines (248 loc) · 9.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
import logging
import traceback
from typing import Self
from fastapi import APIRouter, HTTPException, Request, status
from fastapi.datastructures import URL
from returns.maybe import Maybe, Some
from returns.result import Failure, Success
from stapi_fastapi.backends.root_backend import GetOrder, GetOrders, GetOrderStatuses
from stapi_fastapi.constants import TYPE_GEOJSON, TYPE_JSON
from stapi_fastapi.exceptions import NotFoundException
from stapi_fastapi.models.conformance import CORE, Conformance
from stapi_fastapi.models.order import (
Order,
OrderCollection,
OrderStatuses,
)
from stapi_fastapi.models.product import Product, ProductsCollection
from stapi_fastapi.models.root import RootResponse
from stapi_fastapi.models.shared import Link
from stapi_fastapi.responses import GeoJSONResponse
from stapi_fastapi.routers.product_router import ProductRouter
logger = logging.getLogger(__name__)
class RootRouter(APIRouter):
def __init__(
self,
get_orders: GetOrders,
get_order: GetOrder,
get_order_statuses: GetOrderStatuses,
conformances: list[str] = [CORE],
name: str = "root",
openapi_endpoint_name: str = "openapi",
docs_endpoint_name: str = "swagger_ui_html",
*args,
**kwargs,
) -> None:
super().__init__(*args, **kwargs)
self._get_orders = get_orders
self._get_order = get_order
self._get_order_statuses = get_order_statuses
self.name = name
self.conformances = conformances
self.openapi_endpoint_name = openapi_endpoint_name
self.docs_endpoint_name = docs_endpoint_name
# A dict is used to track the product routers so we can ensure
# idempotentcy in case a product is added multiple times, and also to
# manage clobbering if multiple products with the same product_id are
# added.
self.product_routers: dict[str, ProductRouter] = {}
self.add_api_route(
"/",
self.get_root,
methods=["GET"],
name=f"{self.name}:root",
tags=["Root"],
)
self.add_api_route(
"/conformance",
self.get_conformance,
methods=["GET"],
name=f"{self.name}:conformance",
tags=["Conformance"],
)
self.add_api_route(
"/products",
self.get_products,
methods=["GET"],
name=f"{self.name}:list-products",
tags=["Products"],
)
self.add_api_route(
"/orders",
self.get_orders,
methods=["GET"],
name=f"{self.name}:list-orders",
response_class=GeoJSONResponse,
tags=["Orders"],
)
self.add_api_route(
"/orders/{order_id}",
self.get_order,
methods=["GET"],
name=f"{self.name}:get-order",
response_class=GeoJSONResponse,
tags=["Orders"],
)
self.add_api_route(
"/orders/{order_id}/statuses",
self.get_order_statuses,
methods=["GET"],
name=f"{self.name}:list-order-statuses",
tags=["Orders"],
)
def get_root(self, request: Request) -> RootResponse:
return RootResponse(
id="STAPI API",
conformsTo=self.conformances,
links=[
Link(
href=str(request.url_for(f"{self.name}:root")),
rel="self",
type=TYPE_JSON,
),
Link(
href=str(request.url_for(f"{self.name}:conformance")),
rel="conformance",
type=TYPE_JSON,
),
Link(
href=str(request.url_for(f"{self.name}:list-products")),
rel="products",
type=TYPE_JSON,
),
Link(
href=str(request.url_for(f"{self.name}:list-orders")),
rel="orders",
type=TYPE_JSON,
),
Link(
href=str(request.url_for(self.openapi_endpoint_name)),
rel="service-description",
type=TYPE_JSON,
),
Link(
href=str(request.url_for(self.docs_endpoint_name)),
rel="service-docs",
type="text/html",
),
],
)
def get_conformance(self, request: Request) -> Conformance:
return Conformance(conforms_to=self.conformances)
def get_products(self, request: Request) -> ProductsCollection:
return ProductsCollection(
products=[pr.get_product(request) for pr in self.product_routers.values()],
links=[
Link(
href=str(request.url_for(f"{self.name}:list-products")),
rel="self",
type=TYPE_JSON,
)
],
)
async def get_orders(self, request: Request) -> OrderCollection:
match await self._get_orders(request):
case Success(orders):
for order in orders:
order.links.append(
Link(
href=str(
request.url_for(
f"{self.name}:get-order", order_id=order.id
)
),
rel="self",
type=TYPE_JSON,
)
)
return orders
case Failure(e):
logger.error(
"An error occurred while retrieving orders: %s",
traceback.format_exception(e),
)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Error finding Orders",
)
case _:
raise AssertionError("Expected code to be unreachable")
async def get_order(self: Self, order_id: str, request: Request) -> Order:
"""
Get details for order with `order_id`.
"""
match await self._get_order(order_id, request):
case Success(Some(order)):
self.add_order_links(order, request)
return order
case Success(Maybe.empty):
raise NotFoundException("Order not found")
case Failure(e):
logger.error(
"An error occurred while retrieving order '%s': %s",
order_id,
traceback.format_exception(e),
)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Error finding Order",
)
case _:
raise AssertionError("Expected code to be unreachable")
async def get_order_statuses(
self: Self, order_id: str, request: Request
) -> OrderStatuses:
match await self._get_order_statuses(order_id, request):
case Success(statuses):
return OrderStatuses(
statuses=statuses,
links=[
Link(
href=str(
request.url_for(
f"{self.name}:list-order-statuses",
order_id=order_id,
)
),
rel="self",
type=TYPE_JSON,
)
],
)
case Failure(e):
logger.error(
"An error occurred while retrieving order statuses: %s",
traceback.format_exception(e),
)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Error finding Order Statuses",
)
case _:
raise AssertionError("Expected code to be unreachable")
def add_product(self: Self, product: Product, *args, **kwargs) -> None:
# Give the include a prefix from the product router
product_router = ProductRouter(product, self, *args, **kwargs)
self.include_router(product_router, prefix=f"/products/{product.id}")
self.product_routers[product.id] = product_router
def generate_order_href(self: Self, request: Request, order_id: str) -> URL:
return request.url_for(f"{self.name}:get-order", order_id=order_id)
def generate_order_statuses_href(
self: Self, request: Request, order_id: str
) -> URL:
return request.url_for(f"{self.name}:list-order-statuses", order_id=order_id)
def add_order_links(self, order: Order, request: Request):
order.links.append(
Link(
href=str(self.generate_order_href(request, order.id)),
rel="self",
type=TYPE_GEOJSON,
)
)
order.links.append(
Link(
href=str(self.generate_order_statuses_href(request, order.id)),
rel="monitor",
type=TYPE_JSON,
),
)