|
| 1 | +import importlib |
| 2 | +from msgraph import GraphServiceClient |
| 3 | +from kiota_abstractions.base_request_configuration import RequestConfiguration |
| 4 | +from msgraph.generated.models.o_data_errors.o_data_error import ODataError |
| 5 | +from typing import Dict, Any |
| 6 | +import asyncio |
| 7 | + |
| 8 | +class MicrosoftGraphFetcher: |
| 9 | + def __init__(self, graph_client: GraphServiceClient, resource_path: str, query_params: Dict[str, Any], resource_params: Dict[str, str]): |
| 10 | + """ |
| 11 | + Initializes the fetcher with the Graph client, resource path, and query parameters. |
| 12 | +
|
| 13 | + :param graph_client: The authenticated GraphServiceClient instance. |
| 14 | + :param resource_path: The resource path (e.g., "sites/by_site_id/lists/by_list_id/items"). |
| 15 | + :param params: Query parameters for the request. |
| 16 | + """ |
| 17 | + self.graph_client = graph_client |
| 18 | + self.resource_path = resource_path |
| 19 | + self.query_params = query_params |
| 20 | + self.resource_params = resource_params |
| 21 | + |
| 22 | + def _get_request_builder_class(self): |
| 23 | + """ |
| 24 | + Dynamically resolves the correct RequestBuilder class from `msgraph.generated`. |
| 25 | +
|
| 26 | + Example: For "sites/by_site_id/lists/by_list_id/items", it will resolve: |
| 27 | + `msgraph.generated.sites.item.lists.item.items.items_request_builder.ItemsRequestBuilder` |
| 28 | + """ |
| 29 | + path_parts = self.resource_path.split("/") |
| 30 | + base_module = "msgraph.generated" |
| 31 | + module_path = [] |
| 32 | + class_name = "RequestBuilder" # Default fallback |
| 33 | + |
| 34 | + i = 0 |
| 35 | + while i < len(path_parts): |
| 36 | + part = path_parts[i] |
| 37 | + |
| 38 | + if part.startswith("by_"): # Handling {site_id}, {list_id}, etc. |
| 39 | + module_path.append("item") # `by_site_id` means `.item` |
| 40 | + |
| 41 | + else: |
| 42 | + module_path.append(part) |
| 43 | + |
| 44 | + i += 1 |
| 45 | + |
| 46 | + # Construct the full module path |
| 47 | + module_name = f"{base_module}." + ".".join(module_path) + f".{module_path[-1]}_request_builder" |
| 48 | + |
| 49 | + try: |
| 50 | + module = importlib.import_module(module_name) |
| 51 | + pascal_case_class = self._pascal_case(f"{module_path[-1]}_request_builder") |
| 52 | + |
| 53 | + for attr in dir(module): |
| 54 | + if attr == pascal_case_class: |
| 55 | + return getattr(module, attr) |
| 56 | + |
| 57 | + raise ValueError(f"Could not find {pascal_case_class} in {module_name}") |
| 58 | + |
| 59 | + except ModuleNotFoundError: |
| 60 | + raise ValueError(f"Could not resolve RequestBuilder for resource path: {self.resource_path}") |
| 61 | + |
| 62 | + def _pascal_case(self, snake_str: str) -> str: |
| 63 | + """ |
| 64 | + Converts snake_case to PascalCase. |
| 65 | + Example: "items_request_builder" -> "ItemsRequestBuilder" |
| 66 | + """ |
| 67 | + return "".join(word.title() for word in snake_str.split("_")) |
| 68 | + |
| 69 | + def _get_query_parameters_class(self, request_builder_class): |
| 70 | + """ |
| 71 | + Fetches the corresponding `RequestBuilderGetQueryParameters` class dynamically. |
| 72 | + """ |
| 73 | + for attr in dir(request_builder_class): |
| 74 | + if attr.endswith("RequestBuilderGetQueryParameters"): |
| 75 | + return getattr(request_builder_class, attr) |
| 76 | + raise ValueError(f"No QueryParameters class found for {request_builder_class.__name__}") |
| 77 | + |
| 78 | + async def fetch_data(self): |
| 79 | + """ |
| 80 | + Fetches data from Microsoft Graph using the dynamically built request. |
| 81 | + Handles pagination automatically. |
| 82 | + """ |
| 83 | + request_builder_class = self._get_request_builder_class() |
| 84 | + query_params_class = self._get_query_parameters_class(request_builder_class) |
| 85 | + |
| 86 | + |
| 87 | + # Create Query Parameters object |
| 88 | + valid_params = {p for p in query_params_class.__annotations__.keys()} |
| 89 | + filtered_params = {k: v for k, v in self.query_params.items() if k in valid_params} |
| 90 | + query_parameters = query_params_class(**filtered_params) |
| 91 | + request_configuration = RequestConfiguration( |
| 92 | + query_parameters=query_parameters, |
| 93 | + ) |
| 94 | + |
| 95 | + # Get Request Builder Instance from Graph Client |
| 96 | + builder = self._get_request_builder_instance(request_builder_class) |
| 97 | + |
| 98 | + try: |
| 99 | + items = await builder.get(request_configuration=request_configuration) |
| 100 | + while True: |
| 101 | + print("Page fetched....") |
| 102 | + for item in items.value: |
| 103 | + yield item |
| 104 | + if not items.odata_next_link: |
| 105 | + break |
| 106 | + items = await builder.with_url(items.odata_next_link).get() |
| 107 | + |
| 108 | + except ODataError as e: |
| 109 | + raise Exception(f"Graph API Error: {e.error.message}") |
| 110 | + |
| 111 | + def _get_request_builder_instance(self, request_builder_class): |
| 112 | + """ |
| 113 | + Uses the `graph_client` to resolve the correct instance of the request builder dynamically, |
| 114 | + passing actual `site_id`, `list_id`, etc., instead of placeholders. |
| 115 | + """ |
| 116 | + parts = self.resource_path.split("/") |
| 117 | + builder = self.graph_client |
| 118 | + |
| 119 | + i = 0 |
| 120 | + while i < len(parts): |
| 121 | + part = parts[i] |
| 122 | + |
| 123 | + if part.startswith("by_"): # Handling "by_site_id", "by_list_id", etc. |
| 124 | + param_name = part[3:] # Extract parameter name (e.g., "site_id", "list_id") |
| 125 | + actual_id = self.resource_params.get(param_name) # Get actual ID from user input |
| 126 | + if not actual_id: |
| 127 | + raise ValueError(f"Missing required parameter: {param_name}") |
| 128 | + method_name = part # Keep "by_site_id" format |
| 129 | + |
| 130 | + if hasattr(builder, method_name): |
| 131 | + builder = getattr(builder, method_name)(actual_id) # Pass actual ID |
| 132 | + elif hasattr(builder, part): |
| 133 | + builder = getattr(builder, part) |
| 134 | + else: |
| 135 | + raise ValueError(f"Invalid resource path: '{part}' not found in {builder}") |
| 136 | + |
| 137 | + i += 1 |
| 138 | + |
| 139 | + return builder |
0 commit comments