working state
This commit is contained in:
parent
05654189c9
commit
1e2888a94f
2 changed files with 158 additions and 47 deletions
|
@ -5,10 +5,13 @@ import { last, log_from } from "./utils.ts";
|
|||
|
||||
const log = log_from(import.meta);
|
||||
|
||||
export type Id<T = unknown> = { id: string };
|
||||
|
||||
export class Storage {
|
||||
db;
|
||||
devoirs;
|
||||
notifications;
|
||||
feeds;
|
||||
|
||||
constructor(db: Deno.Kv) {
|
||||
this.db = db;
|
||||
|
@ -19,10 +22,17 @@ export class Storage {
|
|||
});
|
||||
this.devoirs = new Manager(db, "devoir", devoir_parser);
|
||||
const notification_parser = z.object({
|
||||
feed_id: z.string(),
|
||||
devoir_id: z.string(),
|
||||
message_id: z.string(),
|
||||
});
|
||||
this.notifications = new Manager(db, "notification", notification_parser);
|
||||
const feed_parser = z.object({
|
||||
channel_id: z.string(),
|
||||
board_message_id: z.string(),
|
||||
notification_ids: z.set(z.string()),
|
||||
});
|
||||
this.feeds = new Manager(db, "feed", feed_parser);
|
||||
}
|
||||
|
||||
static async open(path: string) {
|
||||
|
@ -34,9 +44,13 @@ export class Storage {
|
|||
|
||||
async sanity() {
|
||||
await this.devoirs.sanity();
|
||||
await this.notifications.sanity();
|
||||
await this.feeds.sanity();
|
||||
}
|
||||
}
|
||||
|
||||
export type Devoir = z.infer<Storage["devoirs"]["parser"]>;
|
||||
|
||||
class Manager<T> {
|
||||
db;
|
||||
label;
|
||||
|
@ -51,10 +65,10 @@ class Manager<T> {
|
|||
async add(value: T) {
|
||||
const id = `${Date.now()}${Math.random()}`;
|
||||
await this.db.set([this.label, id], value);
|
||||
return id;
|
||||
return { id } as Id<T>;
|
||||
}
|
||||
|
||||
async get(id: string) {
|
||||
async get({ id }: Id<T>) {
|
||||
const entry = await this.db.get([this.label, id]);
|
||||
if (entry.value === null) return null;
|
||||
const parsed = this.parse(entry.value);
|
||||
|
@ -70,18 +84,18 @@ class Manager<T> {
|
|||
}
|
||||
}
|
||||
|
||||
async set(id: string, value: T) {
|
||||
async set({ id }: Id<T>, value: T) {
|
||||
await this.db.set([this.label, id], value);
|
||||
}
|
||||
|
||||
async update(id: string, operation: (item: T) => unknown) {
|
||||
const value = await this.get(id);
|
||||
async update({ id }: Id<T>, operation: (item: T) => unknown) {
|
||||
const value = await this.get({ id });
|
||||
if (value === null) return;
|
||||
await operation(value);
|
||||
await this.set(id, value);
|
||||
await this.set({ id }, value);
|
||||
}
|
||||
|
||||
async delete(id: string) {
|
||||
async delete({ id }: Id<T>) {
|
||||
await this.db.delete([this.label, id]);
|
||||
}
|
||||
|
||||
|
@ -91,7 +105,7 @@ class Manager<T> {
|
|||
assert(typeof id === "string");
|
||||
const value = this.parse(entry.value);
|
||||
if (value === null) continue;
|
||||
yield [id, value as T] as const;
|
||||
yield [{ id } as Id<T>, value as T] as const;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue