From 9ebf83af5dd0cab383ac74fa778eb723c28388ed Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 24 Jul 2023 22:38:36 -0500 Subject: [PATCH] Add preliminary TrendsDB module --- src/deps.ts | 1 + src/trends.ts | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 src/trends.ts diff --git a/src/deps.ts b/src/deps.ts index 91833db..c930339 100644 --- a/src/deps.ts +++ b/src/deps.ts @@ -39,3 +39,4 @@ export { default as sanitizeHtml } from 'npm:sanitize-html@^2.10.0'; export { default as ISO6391 } from 'npm:iso-639-1@2.1.15'; export { Dongoose } from 'https://raw.githubusercontent.com/alexgleason/dongoose/68b7ad9dd7b6ec0615e246a9f1603123c1709793/mod.ts'; export { createPentagon } from 'https://deno.land/x/pentagon@v0.1.1/mod.ts'; +export { DB as Sqlite } from 'https://deno.land/x/sqlite@v3.7.0/mod.ts'; diff --git a/src/trends.ts b/src/trends.ts new file mode 100644 index 0000000..15b80d7 --- /dev/null +++ b/src/trends.ts @@ -0,0 +1,46 @@ +import { Sqlite } from '@/deps.ts'; + +class TrendsDB { + #db: Sqlite; + + constructor(db: Sqlite) { + this.#db = db; + + this.#db.execute(` + CREATE TABLE IF NOT EXISTS tag_usages ( + tag TEXT NOT NULL, + pubkey8 TEXT NOT NULL, + inserted_at DATETIME NOT NULL, + ); + + CREATE INDEX IF NOT EXISTS idx_time_tag ON tag_usages(inserted_at, tag); + `); + } + + getTrendingTags(): string[] { + return this.#db.query(` + SELECT tag, COUNT(DISTINCT pubkey8) + FROM tag_usages + WHERE inserted_at >= $1 AND inserted_at < $2 + GROUP BY tag + ORDER BY COUNT(DISTINCT pubkey8) + DESC LIMIT 10; + `).map((row) => row[0]); + } + + addTagUsage(tag: string, pubkey8: string): void { + this.#db.query( + 'INSERT INTO tag_usages (tag, pubkey8, inserted_at) VALUES (?, ?, ?)', + [tag, pubkey8, new Date()], + ); + } + + cleanupTagUsages(): void { + this.#db.query( + 'DELETE FROM tag_usages WHERE inserted_at < ?', + [new Date(Date.now() - 1000 * 60 * 60 * 24 * 7)], + ); + } +} + +export { TrendsDB };