1
Fork 0
mirror of https://github.com/RYGhub/royalnet.git synced 2024-11-23 19:44:20 +00:00
royalnet/royalpack/stars/api_poll.py

64 lines
1.7 KiB
Python
Raw Permalink Normal View History

2020-06-22 17:27:11 +00:00
from typing import *
import datetime
import uuid
2020-06-26 14:13:11 +00:00
import royalnet.utils as ru
import royalnet.constellation.api as rca
2020-06-22 17:27:11 +00:00
from ..tables import Poll
2020-06-26 14:13:11 +00:00
class ApiPollStar(rca.ApiStar):
2020-06-22 17:27:11 +00:00
path = "/api/poll/v2"
parameters = {
"get": {
"uuid": "The UUID of the poll to get.",
},
"post": {
"question": "The question to ask in the poll.",
"description": "A longer Markdown-formatted description.",
"expires": "A ISO timestamp of the expiration date for the poll.",
}
}
auth = {
"get": False,
"post": True
}
tags = ["poll"]
2020-06-26 14:13:11 +00:00
@rca.magic
async def get(self, data: rca.ApiData) -> ru.JSON:
2020-06-22 17:27:11 +00:00
"""Get a specific poll."""
PollT = self.alchemy.get(Poll)
try:
pid = uuid.UUID(data["uuid"])
except (ValueError, AttributeError, TypeError):
2020-06-26 14:13:11 +00:00
raise rca.InvalidParameterError("'uuid' is not a valid UUID.")
2020-06-22 17:27:11 +00:00
2020-06-26 14:13:11 +00:00
poll: Poll = await ru.asyncify(data.session.query(PollT).get, pid)
2020-06-22 17:27:11 +00:00
if poll is None:
2020-06-26 14:13:11 +00:00
raise rca.NotFoundError("No such page.")
2020-06-22 17:27:11 +00:00
return poll.json()
2020-06-26 14:13:11 +00:00
@rca.magic
async def post(self, data: rca.ApiData) -> ru.JSON:
2020-06-22 17:27:11 +00:00
"""Create a new poll."""
PollT = self.alchemy.get(Poll)
poll = PollT(
id=uuid.uuid4(),
creator=await data.user(),
created=datetime.datetime.now(),
expires=datetime.datetime.fromisoformat(data["expires"]) if "expires" in data else None,
question=data["question"],
description=data.get("description"),
)
data.session.add(poll)
await data.session_commit()
return poll.json()