store.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { DB } from "https://deno.land/x/sqlite@v3.1.1/mod.ts";
  2. function dateToEpoch(dateStr: string | Date) {
  3. const date = typeof dateStr === "string" ? new Date(dateStr) : dateStr;
  4. return Math.floor(date.getTime() / 1000);
  5. }
  6. export class SqliteStore {
  7. private db: DB;
  8. constructor(path: string) {
  9. this.db = new DB(path);
  10. this.db.query(`
  11. CREATE TABLE IF NOT EXISTS emails (
  12. id INTEGER PRIMARY KEY,
  13. recipient TEXT NOT NULL,
  14. sender TEXT NOT NULL,
  15. data TEXT NOT NULL,
  16. received_at INTEGER NOT NULL
  17. );
  18. `);
  19. }
  20. saveEmail(recipient: string, sender: string, data: string) {
  21. this.db.query("INSERT INTO emails VALUES (?, ?, ?, ?, ?)", [
  22. null,
  23. recipient,
  24. sender,
  25. data,
  26. dateToEpoch(new Date()),
  27. ]);
  28. }
  29. getLatestEmails(
  30. recipient: string,
  31. newerThan: Date,
  32. ): Array<{ id: string; receivedAt: Date; data: string }> {
  33. const result = this.db.query<[string, string, number]>(
  34. `
  35. SELECT id, data, received_at FROM emails
  36. WHERE recipient = ?
  37. AND received_at > ?
  38. ORDER BY id DESC
  39. `,
  40. [recipient, dateToEpoch(newerThan)],
  41. );
  42. return result.map(([id, data, receivedAt]) => {
  43. return { id, data, receivedAt: new Date(receivedAt * 1000) };
  44. });
  45. }
  46. }