-
Notifications
You must be signed in to change notification settings - Fork 1
/
feed_context.py
49 lines (41 loc) · 1.62 KB
/
feed_context.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from uuid import uuid4
from typing import Dict, Any, Optional
from dal import user_dal
from dal import feed_dal
class FeedContext:
def __init__(self, user_id: str, context_id: Optional[str] = None):
self.user_id = user_id
if context_id:
try:
context_holder = feed_dal.get(context_id)
self.context = context_holder["context"]
except TypeError:
self.context = None
self.context_id = None
else:
self.context = None
def upsert(self, context):
comment_dict = {}
for comment in context["comments"]:
if not "id" in comment:
comment["id"] = str(uuid4())
comment_dict[comment["id"]] = comment
if not self.context:
context_holder = feed_dal.add(self.user_id, context)
self.context = context_holder["context"]
self.context["id"] = context_holder["id"]
self.context_id = context_holder["id"]
else:
for comment in self.context["comments"]:
comment_dict[comment["id"]] = comment
self.context["comments"] = list(comment_dict.values())
self.context["comments"] = sorted(
self.context["comments"], key=lambda x: x["content"]["timestamp_ms_created"]
)
feed_dal.update(self.context["id"], self.context)
return self.context
def add_comment(self, comment):
comment["id"] = str(uuid4())
self.context["comments"].append(comment)
feed_dal.update(self.context["id"], self.context)
return comment["id"]