55from pydantic import BaseModel as PydanticModel
66
77from .. import status
8+ from ..constants import DELETE , GET , PATCH , POST , PUT
89from ..pagination import paginate
910from .response import Detail
1011from .route import route
1415
1516
1617class ModelControllerBuilder :
18+ model_allowed_routes_actions = [
19+ "create" ,
20+ "read" ,
21+ "update" ,
22+ "patch" ,
23+ "delete" ,
24+ "list" ,
25+ ]
26+
1727 def __init__ (
1828 self ,
1929 controller_base_cls : t .Type ["ModelControllerBase" ],
@@ -22,6 +32,9 @@ def __init__(
2232 self ._base_cls = controller_base_cls
2333 self ._api_controller_instance = api_controller_instance
2434 self ._pagination_class = controller_base_cls .pagination_class
35+ self ._allowed_routes = (
36+ self ._base_cls .allowed_routes or self .model_allowed_routes_actions
37+ )
2538 self ._create_schema : t .Type [PydanticModel ] = (
2639 controller_base_cls .create_schema or controller_base_cls .model_schema
2740 )
@@ -111,7 +124,7 @@ def patch_item(
111124 patch_item .api_controller = self ._api_controller_instance
112125 self ._api_controller_instance .add_controller_route_function (patch_item )
113126
114- def _register_get_item_endpoint (self ) -> None :
127+ def _register_get_endpoint (self ) -> None :
115128 _pk_type = self ._pk_type
116129 _path = "/{%s:%s}" % (
117130 _pk_type .__name__ ,
@@ -134,7 +147,7 @@ def get_item(
134147 get_item .api_controller = self ._api_controller_instance
135148 self ._api_controller_instance .add_controller_route_function (get_item )
136149
137- def _register_list_items_endpoint (self ) -> None :
150+ def _register_list_endpoint (self ) -> None :
138151 paginate_kwargs = dict ()
139152 if self ._base_cls .paginate_by :
140153 paginate_kwargs .update (page_size = self ._base_cls .paginate_by )
@@ -178,9 +191,16 @@ def delete_item(
178191 self ._api_controller_instance .add_controller_route_function (delete_item )
179192
180193 def register_model_routes (self ) -> None :
181- self ._register_create_endpoint ()
182- self ._register_delete_endpoint ()
183- self ._register_get_item_endpoint ()
184- self ._register_patch_endpoint ()
185- self ._register_list_items_endpoint ()
186- self ._register_update_endpoint ()
194+ assert isinstance (
195+ self ._allowed_routes , list
196+ ), f"`class[{ self ._base_cls .__name__ } ].allowed_routes must be a list of strings`"
197+ for action in self ._allowed_routes :
198+ action_registration = self .__dict__ .get (
199+ f"_register_{ action } _endpoint" , None
200+ )
201+ if not f"_register_{ action } _endpoint" :
202+ raise Exception (
203+ f"`{ action } ` action in `class[{ self ._base_cls .__name__ } ]` "
204+ f"is not recognized as ModelController action"
205+ )
206+ action_registration ()
0 commit comments