queue
Viewing readonly version: 44View latest version
Script
99
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
import { sqlite } from "https://esm.town/v/stevekrouse/sqlite?v=13";
import { parseImportMeta } from "./parseImportMeta";
const { projectName } = parseImportMeta(import.meta.url);
const DB_TABLE_PREFIX = `${projectName}_v1_`;
const makeTableName = (name: string): string => `${DB_TABLE_PREFIX}${name}`;
export async function addTaskToQueue(importUrl: string, func: string, options?: {
scheduledFor?: Date;
}) {
return (await tasksQuery(`INSERT INTO ${makeTableName("tasks")} (data, scheduled_for) VALUES (?, ?) RETURNING *`, [
JSON.stringify({ importUrl, func }),
(options?.scheduledFor || new Date())?.toISOString(),
])).at(0);
}
export async function getPendingTasks() {
return await tasksQuery(`
SELECT * FROM ${makeTableName("tasks")}
WHERE status = 'pending'
AND scheduled_for <= strftime('%Y-%m-%d %H:%M:%f', 'now')
LIMIT 5`);
}
export async function getTasks() {
return await tasksQuery(`SELECT * FROM ${makeTableName("tasks")}`);
}
async function tasksQuery(query: string, args?: string[]) {
const rows = await sqlite.execute(query, args);
return (rows.rows as unknown as TaskRow[]).map(taskRowMap);
}