Added/deleted-type websocket messages

Events are now sent for not only when an object changes but also when one is created or deleted.

For now it's not really possible to subscribe to these events however.

This breaks backwards-compatibility with the websocket messages.
This commit is contained in:
Donkie
2023-10-15 19:46:10 +02:00
parent 3c5b3cea5a
commit a6d527aaf0
6 changed files with 92 additions and 25 deletions

View File

@@ -6,7 +6,7 @@ from typing import Optional
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from spoolman.api.v1.models import Vendor
from spoolman.api.v1.models import EventType, Vendor, VendorEvent
from spoolman.database import models
from spoolman.database.utils import SortOrder, add_where_clause_str
from spoolman.exceptions import ItemNotFoundError
@@ -20,14 +20,15 @@ async def create(
comment: Optional[str] = None,
) -> models.Vendor:
"""Add a new vendor to the database."""
db_item = models.Vendor(
vendor = models.Vendor(
name=name,
registered=datetime.utcnow().replace(microsecond=0),
comment=comment,
)
db.add(db_item)
db.add(vendor)
await db.commit()
return db_item
await vendor_changed(vendor, EventType.ADDED)
return vendor
async def get_by_id(db: AsyncSession, vendor_id: int) -> models.Vendor:
@@ -89,7 +90,7 @@ async def update(
for k, v in data.items():
setattr(vendor, k, v)
await db.commit()
await vendor_changed(vendor)
await vendor_changed(vendor, EventType.UPDATED)
return vendor
@@ -97,8 +98,16 @@ async def delete(db: AsyncSession, vendor_id: int) -> None:
"""Delete a vendor object."""
vendor = await get_by_id(db, vendor_id)
await db.delete(vendor)
await vendor_changed(vendor, EventType.DELETED)
async def vendor_changed(vendor: models.Vendor) -> None:
async def vendor_changed(vendor: models.Vendor, typ: EventType) -> None:
"""Notify websocket clients that a vendor has changed."""
await websocket_manager.send(("vendor", str(vendor.id)), Vendor.from_db(vendor).json())
await websocket_manager.send(
("vendor", str(vendor.id)),
VendorEvent(
type=typ,
date=datetime.utcnow(),
payload=Vendor.from_db(vendor),
),
)