Skip to content

Commit

Permalink
update transaction endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
vincentsarago committed Apr 26, 2024
1 parent 1260543 commit 1ca76b9
Show file tree
Hide file tree
Showing 6 changed files with 53 additions and 21 deletions.
4 changes: 4 additions & 0 deletions stac_fastapi/pgstac/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,10 @@ async def _get_base_item(collection_id: str) -> Dict[str, Any]:

for feature in collection.get("features") or []:
base_item = await base_item_cache.get(feature.get("collection"))

# Exclude None values
base_item = {k: v for k, v in base_item.items() if v is not None}

feature = hydrate(base_item, feature)

# Grab ids needed for links that may be removed by the fields extension.
Expand Down
2 changes: 1 addition & 1 deletion stac_fastapi/pgstac/extensions/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def operator(self) -> Callable[[Any, Any], bool]:
class QueryExtensionPostRequest(BaseModel):
"""Query Extension POST request model."""

query: Optional[Dict[str, Dict[Operator, Any]]]
query: Optional[Dict[str, Dict[Operator, Any]]] = None


class QueryExtension(QueryExtensionBase):
Expand Down
48 changes: 37 additions & 11 deletions stac_fastapi/pgstac/transactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
)
from stac_fastapi.types import stac as stac_types
from stac_fastapi.types.core import AsyncBaseTransactionsClient
from stac_pydantic import Collection, Item, ItemCollection
from starlette.responses import JSONResponse, Response

from stac_fastapi.pgstac.config import Settings
Expand Down Expand Up @@ -69,11 +70,13 @@ def _validate_item(
async def create_item(
self,
collection_id: str,
item: Union[stac_types.Item, stac_types.ItemCollection],
item: Union[Item, ItemCollection],
request: Request,
**kwargs,
) -> Optional[Union[stac_types.Item, Response]]:
"""Create item."""
item = item.model_dump(mode="json")

if item["type"] == "FeatureCollection":
valid_items = []
for item in item["features"]: # noqa: B020
Expand All @@ -100,6 +103,7 @@ async def create_item(
).get_links(extra_links=item.get("links"))

return stac_types.Item(**item)

else:
raise HTTPException(
status_code=400,
Expand All @@ -111,10 +115,12 @@ async def update_item(
request: Request,
collection_id: str,
item_id: str,
item: stac_types.Item,
item: Item,
**kwargs,
) -> Optional[Union[stac_types.Item, Response]]:
"""Update item."""
item = item.model_dump(mode="json")

self._validate_item(request, item, collection_id, item_id)
item["collection"] = collection_id

Expand All @@ -130,31 +136,49 @@ async def update_item(
return stac_types.Item(**item)

async def create_collection(
self, collection: stac_types.Collection, request: Request, **kwargs
self,
collection: Collection,
request: Request,
**kwargs,
) -> Optional[Union[stac_types.Collection, Response]]:
"""Create collection."""
collection = collection.model_dump(mode="json")

self._validate_collection(request, collection)

async with request.app.state.get_connection(request, "w") as conn:
await dbfunc(conn, "create_collection", collection)

collection["links"] = await CollectionLinks(
collection_id=collection["id"], request=request
).get_links(extra_links=collection.get("links"))
).get_links(extra_links=collection["links"])

return stac_types.Collection(**collection)

async def update_collection(
self, collection: stac_types.Collection, request: Request, **kwargs
self,
collection: Collection,
request: Request,
**kwargs,
) -> Optional[Union[stac_types.Collection, Response]]:
"""Update collection."""
col = collection.model_dump(mode="json")

async with request.app.state.get_connection(request, "w") as conn:
await dbfunc(conn, "update_collection", collection)
collection["links"] = await CollectionLinks(
collection_id=collection["id"], request=request
).get_links(extra_links=collection.get("links"))
return stac_types.Collection(**collection)
await dbfunc(conn, "update_collection", col)

col["links"] = await CollectionLinks(
collection_id=col["id"], request=request
).get_links(extra_links=col.get("links"))

return stac_types.Collection(**col)

async def delete_item(
self, item_id: str, collection_id: str, request: Request, **kwargs
self,
item_id: str,
collection_id: str,
request: Request,
**kwargs,
) -> Optional[Union[stac_types.Item, Response]]:
"""Delete item."""
q, p = render(
Expand All @@ -164,6 +188,7 @@ async def delete_item(
)
async with request.app.state.get_connection(request, "w") as conn:
await conn.fetchval(q, *p)

return JSONResponse({"deleted item": item_id})

async def delete_collection(
Expand All @@ -172,6 +197,7 @@ async def delete_collection(
"""Delete collection."""
async with request.app.state.get_connection(request, "w") as conn:
await dbfunc(conn, "delete_collection", collection_id)

return JSONResponse({"deleted collection": collection_id})


Expand Down
6 changes: 4 additions & 2 deletions tests/clients/test_postgres.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@ async def test_create_collection(app_client, load_test_data: Callable):
"/collections",
json=in_json,
)
assert resp.status_code == 200
assert resp.status_code == 201
post_coll = Collection.parse_obj(resp.json())
assert in_coll.dict(exclude={"links"}) == post_coll.dict(exclude={"links"})

resp = await app_client.get(f"/collections/{post_coll.id}")
assert resp.status_code == 200
get_coll = Collection.parse_obj(resp.json())
Expand Down Expand Up @@ -66,6 +67,7 @@ async def test_create_item(app_client, load_test_data: Callable, load_test_colle
assert resp.status_code == 200
post_item = Item.parse_obj(resp.json())
assert in_item.dict(exclude={"links"}) == post_item.dict(exclude={"links"})

resp = await app_client.get(f"/collections/{coll.id}/items/{post_item.id}")
assert resp.status_code == 200
get_item = Item.parse_obj(resp.json())
Expand All @@ -86,7 +88,7 @@ async def test_create_item_no_collection_id(
json=item,
)

assert resp.status_code == 200
assert resp.status_code == 201

resp = await app_client.get(f"/collections/{coll.id}/items/{item['id']}")

Expand Down
10 changes: 5 additions & 5 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,9 @@ async def pgstac(database):
params=[
# hydratation, prefix
(False, ""),
(False, "/router_prefix"),
(True, ""),
(True, "/router_prefix"),
# (False, "/router_prefix"),
# (True, ""),
# (True, "/router_prefix"),
],
scope="session",
)
Expand Down Expand Up @@ -186,7 +186,7 @@ async def load_test_collection(app_client, load_test_data):
"/collections",
json=data,
)
assert resp.status_code == 200
assert resp.status_code == 201
return Collection.parse_obj(resp.json())


Expand All @@ -198,7 +198,7 @@ async def load_test_item(app_client, load_test_data, load_test_collection):
f"/collections/{coll.id}/items",
json=data,
)
assert resp.status_code == 200
assert resp.status_code == 201

return Item.parse_obj(resp.json())

Expand Down
4 changes: 2 additions & 2 deletions tests/data/test_item.json
Original file line number Diff line number Diff line change
Expand Up @@ -504,7 +504,7 @@
{
"href": "preview.html",
"rel": "preview",
"type": "application/html"
"type": "text/html"
}
]
}
}

0 comments on commit 1ca76b9

Please sign in to comment.