[READ-ONLY] Mirror of https://github.com/flo-bit/skywatched-backend. backend/jetstream consumer for skywatched.app
skywatched.app
1.5 kB
58 lines
1import { db, getRecord } from "../database";
2
3type LikeRecord = {
4 uri: string;
5 author_did: string;
6 subject_cid: string;
7 subject_uri: string;
8 createdAt: string;
9};
10
11export async function saveLikeToDatabase(json: LikeRecord) {
12 // first check if the like already exists
13 const existingLike = db
14 .query("SELECT * FROM likes WHERE author_did = ? AND subject_uri = ?")
15 .get(json.author_did, json.subject_uri);
16 if (existingLike) return;
17
18 // check if the record exists
19 const record = getRecord(json.subject_uri);
20 if (!record) return;
21
22 // save the like to the database
23 const sql =
24 "INSERT INTO likes (uri, author_did, subject_cid, subject_uri, createdAt) VALUES (?, ?, ?, ?, ?)";
25 db.query(sql).run(
26 json.uri,
27 json.author_did,
28 json.subject_cid,
29 json.subject_uri,
30 json.createdAt
31 );
32
33 // update the record with the new like count
34 const newLikes = record.record.likes ? record.record.likes + 1 : 1;
35 db.query("UPDATE records SET record_likes = ? WHERE uri = ?").run(
36 newLikes,
37 json.subject_uri
38 );
39}
40
41export async function deleteLikeFromDatabase(json: LikeRecord) {
42 db.query("DELETE FROM likes WHERE uri = ?").run(json.uri);
43}
44
45export async function getLikesByUser(did: string) {
46 return db
47 .query(
48 "SELECT * FROM likes WHERE author_did = ? ORDER BY createdAt DESC LIMIT 100"
49 )
50 .all(did);
51}
52
53export async function getAllUsersWithLikes() {
54 return db
55 .query("SELECT DISTINCT author_did FROM likes")
56 .all()
57 .map((row: any) => row.author_did);
58}