Skip to content

Commit

Permalink
revert and add Item/CollectionList
Browse files Browse the repository at this point in the history
  • Loading branch information
vincentsarago committed Oct 30, 2023
1 parent 58a53f2 commit f36eb3c
Show file tree
Hide file tree
Showing 5 changed files with 108 additions and 125 deletions.
50 changes: 32 additions & 18 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,26 @@ Note: Minor version `0.X.0` update might break the API, It's recommended to pin

- add `py.typed` file

- add `ItemList` and `CollectionList` *TypedDict*

```python
class ItemList(TypedDict):
"""Items."""

items: List[Feature]
matched: Optional[int]
next: Optional[int]
prev: Optional[int]

class CollectionList(TypedDict):
"""Collections."""

collections: List[Collection]
matched: Optional[int]
next: Optional[int]
prev: Optional[int]
```

### fixed

- hide map element in HTML pages when collections/items do not have spatial component (https://github.com/developmentseed/tipg/issues/132)
Expand Down Expand Up @@ -47,30 +67,24 @@ Note: Minor version `0.X.0` update might break the API, It's recommended to pin
...
```

- make `Catalog` a Pydantic model and add `matched`, `next` and `prev` attributes
- `Collection.features()` method now returns an `ItemList` dict

```python
# Before
class Catalog(TypedDict):
"""Collection Catalog."""

collections: Dict[str, Collection]
last_updated: datetime.datetime

# Now
class Catalog(BaseModel):
"""Collection Catalog."""

collections: Dict[str, Collection]
last_updated: datetime.datetime
matched: Optional[int] = None
next: Optional[int] = None
prev: Optional[int] = None
#before
collection = Collection()
features_collection, matched = collection.features(...)

#now
collection = Collection()
items_list = collection.features(...)
print(items_list["matched"]) # Number of matched items for the query
print(items_list["next"]) # Next Offset
print(items_list["prev"]) # Previous Offset
```

- move `/collections` QueryParameters in the `CatalogParams` dependency

- the `CatalogParams` now returns a `Catalog` object
- the `CatalogParams` now returns a `CollectionList` object

- move `s_intersects` and `t_intersects` functions from `tipg.factory` to `tipg.dependencies`

Expand Down
48 changes: 26 additions & 22 deletions tipg/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,13 @@ class Feature(TypedDict, total=False):
bbox: Optional[List[float]]


class FeatureCollection(TypedDict, total=False):
"""Simple FeatureCollection model."""
class ItemList(TypedDict):
"""Items."""

type: str
features: List[Feature]
bbox: Optional[List[float]]
items: List[Feature]
matched: Optional[int]
next: Optional[int]
prev: Optional[int]


class Column(BaseModel):
Expand Down Expand Up @@ -739,8 +740,9 @@ async def features(
simplify: Optional[float] = None,
geom_as_wkt: bool = False,
function_parameters: Optional[Dict[str, str]] = None,
) -> Tuple[FeatureCollection, int]:
) -> ItemList:
"""Build and run Pg query."""
offset = offset or 0
function_parameters = function_parameters or {}

if geom and geom.lower() != "none" and not self.get_geometry_column(geom):
Expand All @@ -751,7 +753,7 @@ async def features(
f"Limit can not be set higher than the `tipg_max_features_per_query` setting of {features_settings.max_features_per_query}"
)

count = await self._features_count_query(
matched = await self._features_count_query(
pool=pool,
ids_filter=ids_filter,
datetime_filter=datetime_filter,
Expand Down Expand Up @@ -784,10 +786,13 @@ async def features(
function_parameters=function_parameters,
)
]
returned = len(features)

return (
FeatureCollection(type="FeatureCollection", features=features),
count,
return ItemList(
items=features,
matched=matched,
next=offset + returned if matched - returned > offset else None,
prev=max(offset - returned, 0) if offset else None,
)

async def get_tile(
Expand Down Expand Up @@ -876,21 +881,20 @@ def queryables(self) -> Dict:
return {**geoms, **props}


class Catalog(BaseModel):
"""Collection Catalog."""
class CollectionList(TypedDict):
"""Collections."""

collections: List[Collection]
matched: Optional[int]
next: Optional[int]
prev: Optional[int]


class Catalog(TypedDict):
"""Internal Collection Catalog."""

collections: Dict[str, Collection]
last_updated: datetime.datetime
matched: Optional[int] = None
next: Optional[int] = None
prev: Optional[int] = None

@model_validator(mode="after")
def compute_matched(self):
"""Compute matched if it does not exist."""
if self.matched is None:
self.matched = len(self.collections)
return self


async def get_collection_index( # noqa: C901
Expand Down
15 changes: 7 additions & 8 deletions tipg/dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from pygeofilter.parsers.cql2_text import parse as cql2_text_parser
from typing_extensions import Annotated

from tipg.collections import Catalog, Collection
from tipg.collections import Catalog, Collection, CollectionList
from tipg.errors import InvalidBBox, MissingCollectionCatalog, MissingFunctionParameter
from tipg.resources.enums import MediaType
from tipg.settings import TMSSettings
Expand Down Expand Up @@ -422,8 +422,8 @@ def CollectionParams(
if not catalog:
raise MissingCollectionCatalog("Could not find collections catalog.")

if collectionId in catalog.collections:
return catalog.collections[collectionId]
if collectionId in catalog["collections"]:
return catalog["collections"][collectionId]

raise HTTPException(
status_code=404, detail=f"Table/Function '{collectionId}' not found."
Expand Down Expand Up @@ -453,7 +453,7 @@ def CatalogParams(
description="Starts the response at an offset.",
),
] = None,
) -> Catalog:
) -> CollectionList:
"""Return Collections Catalog."""
limit = limit or 0
offset = offset or 0
Expand All @@ -462,7 +462,7 @@ def CatalogParams(
if not catalog:
raise MissingCollectionCatalog("Could not find collections catalog.")

collections_list = list(catalog.collections.values())
collections_list = list(catalog["collections"].values())

# type filter
if type_filter is not None:
Expand Down Expand Up @@ -499,9 +499,8 @@ def CatalogParams(

returned = len(collections_list)

return Catalog(
collections={col.id: col for col in collections_list},
last_updated=catalog.last_updated,
return CollectionList(
collections=collections_list,
matched=matched,
next=offset + returned if matched - returned > offset else None,
prev=max(offset - returned, 0) if offset else None,
Expand Down
Loading

0 comments on commit f36eb3c

Please sign in to comment.