1
0
silverbullet/plugos/syscalls/store.dexie_browser.ts

67 lines
1.4 KiB
TypeScript
Raw Normal View History

2022-03-25 11:03:06 +00:00
import Dexie from "dexie";
import {SysCallMapping} from "../system";
2022-03-25 11:03:06 +00:00
export type KV = {
key: string;
value: any;
};
export function storeSyscalls(
dbName: string,
tableName: string
): SysCallMapping {
const db = new Dexie(dbName);
db.version(1).stores({
2022-04-04 13:25:07 +00:00
[tableName]: "key",
2022-03-25 11:03:06 +00:00
});
const items = db.table(tableName);
return {
"store.delete": async (ctx, key: string) => {
2022-03-25 11:03:06 +00:00
await items.delete(key);
},
"store.deletePrefix": async (ctx, prefix: string) => {
2022-03-25 11:03:06 +00:00
await items.where("key").startsWith(prefix).delete();
},
"store.deleteAll": async () => {
2022-03-25 11:03:06 +00:00
await items.clear();
},
"store.set": async (ctx, key: string, value: any) => {
2022-03-25 11:03:06 +00:00
await items.put({
key,
value,
});
},
"store.batchSet": async (ctx, kvs: KV[]) => {
2022-03-25 11:03:06 +00:00
await items.bulkPut(
kvs.map(({ key, value }) => ({
key,
value,
}))
);
},
"store.get": async (ctx, key: string): Promise<any | null> => {
2022-03-25 11:03:06 +00:00
let result = await items.get({
key,
});
return result ? result.value : null;
},
"store.queryPrefix": async (
2022-03-25 11:03:06 +00:00
ctx,
keyPrefix: string
): Promise<{ key: string; value: any }[]> => {
2022-03-25 11:03:06 +00:00
let results = await items.where("key").startsWith(keyPrefix).toArray();
return results.map((result) => ({
key: result.key,
value: result.value,
}));
},
};
}