-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfeed.ts
87 lines (77 loc) · 1.98 KB
/
feed.ts
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import { cacheDb, PostWithData } from "./db.js";
export function parseCursor(cursor: string | undefined) {
if (!cursor) {
return { time: undefined, index: undefined };
}
const [time, index] = cursor.split("/");
return { time, index: parseInt(index || "0") };
}
export type ParsedCursor = ReturnType<typeof parseCursor>;
export interface RankLinksOptions {
limit: number;
cursor?: ParsedCursor;
range?: string;
}
export async function rankLinks({
limit,
cursor = { time: undefined, index: undefined },
range = "1 day",
}: RankLinksOptions) {
const cursorTime = cursor.time || "now";
const cursorDateTime = `DATETIME('${cursorTime}', '-${range}')`;
const posts = cacheDb
.prepare(
`
SELECT
did,
rkey,
url,
createdAt,
score,
dateWritten
FROM
post
WHERE
createdAt >= ${cursorDateTime} AND
dateWritten = (
SELECT
dateWritten
FROM
date_written
WHERE
dateWritten >= ${cursorDateTime}
ORDER BY
julianday(dateWritten) - julianday('${cursorTime}')
DESC
LIMIT 1
)
ORDER BY
score DESC
LIMIT
${limit}
${cursor.index ? `OFFSET ${cursor.index}` : ""};
`
)
.all() as PostWithData[];
return {
items: posts,
cursor: `${cursor.time || posts[posts.length - 1]?.dateWritten}/${
(cursor.index || 0) + (posts.length === limit ? limit : posts.length)
}`,
};
}
export function constructFeed(items: PostWithData[]) {
return items.map((post) => {
return {
post: `at://${post.did}/app.bsky.feed.post/${post.rkey}`,
};
});
}
export async function trendingLinks(options: Omit<RankLinksOptions, "range">) {
return rankLinks({ ...options, range: "1 day" });
}
export async function trendingLinksHourly(
options: Omit<RankLinksOptions, "range">
) {
return rankLinks({ ...options, range: "1 hour" });
}