1
0
silverbullet/webapp/spaces/indexeddb_space_primitives.ts

87 lines
1.9 KiB
TypeScript
Raw Normal View History

2022-04-07 13:21:30 +00:00
import { SpacePrimitives } from "./space_primitives";
2022-04-05 15:02:17 +00:00
import { PageMeta } from "../../common/types";
import Dexie, { Table } from "dexie";
import { Plug } from "../../plugos/plug";
type Page = {
name: string;
text: string;
meta: PageMeta;
};
2022-04-07 13:21:30 +00:00
export class IndexedDBSpacePrimitives implements SpacePrimitives {
2022-04-05 15:02:17 +00:00
private pageTable: Table<Page, string>;
constructor(dbName: string, readonly timeSkew: number = 0) {
2022-04-05 15:02:17 +00:00
const db = new Dexie(dbName);
db.version(1).stores({
page: "name",
});
this.pageTable = db.table("page");
}
async deletePage(name: string): Promise<void> {
return this.pageTable.delete(name);
}
async getPageMeta(name: string): Promise<PageMeta> {
let entry = await this.pageTable.get(name);
if (entry) {
return entry.meta;
} else {
throw Error(`Page not found`);
2022-04-05 15:02:17 +00:00
}
}
invokeFunction(
plug: Plug<any>,
env: string,
name: string,
args: any[]
): Promise<any> {
return plug.invoke(name, args);
}
async fetchPageList(): Promise<{
pages: Set<PageMeta>;
nowTimestamp: number;
}> {
2022-04-05 15:02:17 +00:00
let allPages = await this.pageTable.toArray();
return {
pages: new Set(allPages.map((p) => p.meta)),
nowTimestamp: Date.now() + this.timeSkew,
};
2022-04-05 15:02:17 +00:00
}
proxySyscall(plug: Plug<any>, name: string, args: any[]): Promise<any> {
return plug.syscall(name, args);
}
async readPage(name: string): Promise<{ text: string; meta: PageMeta }> {
let page = await this.pageTable.get(name);
if (page) {
return page;
2022-04-05 15:02:17 +00:00
} else {
throw new Error("Page not found");
2022-04-05 15:02:17 +00:00
}
}
async writePage(
name: string,
text: string,
selfUpdate?: boolean,
lastModified?: number
2022-04-05 15:02:17 +00:00
): Promise<PageMeta> {
let meta = {
name,
lastModified: lastModified ? lastModified : Date.now() + this.timeSkew,
};
2022-04-05 15:02:17 +00:00
await this.pageTable.put({
name,
text,
meta,
});
return meta;
}
}