appdata-triggers
All checks were successful
Deploy to core / deploy (push) Successful in 1m16s

This commit is contained in:
2024-02-20 21:57:39 +03:00
parent 66f1c654cf
commit 4f26812340
3 changed files with 59 additions and 1 deletions

View File

@@ -1,6 +1,7 @@
import time
from sqlalchemy import JSON, Boolean, Column, ForeignKey, Integer, String
from sqlalchemy import event
from services.db import Base
@@ -40,3 +41,35 @@ class Author(Base):
last_seen = Column(Integer, nullable=False, default=lambda: int(time.time()))
updated_at = Column(Integer, nullable=False, default=lambda: int(time.time()))
deleted_at = Column(Integer, nullable=True, comment='Deleted at')
def get_object(connection, table_name, object_id):
return connection.execute(f"SELECT * FROM {table_name} WHERE id = :object_id", {"object_id": object_id}).fetchone()
def update_app_data(connection, user_id, app_data):
connection.execute("UPDATE authorizer_users SET app_data = :app_data WHERE id = :user_id", {"app_data": app_data, "user_id": user_id})
def update_follows(user, entity_type, entity):
app_data = user.app_data or {}
app_data['follows'] = user.app_data or {"topics": [], "authors": [], "shouts": [], "communities": []}
app_data['follows'][f'{entity_type}s'].append(vars(entity))
return app_data
@event.listens_for(Author, 'after_insert')
@event.listens_for(Author, 'after_update')
def after_author_update(mapper, connection, target):
user_id = target.user
user = get_object(connection, 'authorizer_users', user_id)
if user:
app_data = update_follows(user, 'author', target)
update_app_data(connection, user_id, app_data)
@event.listens_for(AuthorFollower, 'after_insert')
@event.listens_for(AuthorFollower, 'after_delete')
def after_author_follower_change(mapper, connection, target):
author_id = target.author
follower_id = target.follower
user = get_object(connection, 'authorizer_users', follower_id)
if user:
app_data = update_follows(user, 'author', get_object(connection, 'author', author_id))
update_app_data(connection, follower_id, app_data)