52 lines
1.3 KiB
Python
52 lines
1.3 KiB
Python
from ninja import NinjaAPI
|
|
from ninja import Schema
|
|
import datetime
|
|
from ..accounts.models import User
|
|
from .models import ThingEdit, Thing as ThingModel
|
|
|
|
api = NinjaAPI()
|
|
|
|
|
|
class Thing(Schema):
|
|
id: int
|
|
data: dict
|
|
type: str
|
|
|
|
|
|
def get_user_from_key(key: str):
|
|
# TODO: something real
|
|
return User.objects.get(username=key)
|
|
|
|
|
|
@api.post("/thing/")
|
|
def sync_thing(request, key: str, thing: Thing):
|
|
user = get_user_from_key(key)
|
|
action = "none"
|
|
try:
|
|
old_thing = ThingModel.objects.get(user=user, thing_id=thing.id)
|
|
if old_thing.data != thing.data:
|
|
ThingEdit.objects.create(
|
|
thing=old_thing,
|
|
data=old_thing.data,
|
|
timestamp=old_thing.synced_at,
|
|
)
|
|
old_thing.data = thing.data
|
|
old_thing.synced_at = datetime.datetime.utcnow()
|
|
old_thing.save()
|
|
thing = old_thing
|
|
action = "updated"
|
|
except ThingModel.DoesNotExist:
|
|
thing = ThingModel.objects.create(
|
|
user=user, thing_id=thing.id, data=thing.data, type=thing.type
|
|
)
|
|
action = "created"
|
|
# TODO: deleted
|
|
return {"action": action}
|
|
|
|
|
|
@api.get("/thing/{id}")
|
|
def get_thing(request, id: int, key: str):
|
|
user = get_user_from_key(key)
|
|
thing = ThingModel.objects.get(user=user, thing_id=id)
|
|
return thing.data
|