1
0
silverbullet/server/syscalls/page_index.ts

85 lines
2.3 KiB
TypeScript
Raw Normal View History

import { Knex } from "knex";
2022-03-25 11:03:06 +00:00
import { SysCallMapping } from "../../plugbox/system";
type IndexItem = {
page: string;
key: string;
value: any;
};
export type KV = {
key: string;
value: any;
};
2022-03-25 11:03:06 +00:00
export default function (db: Knex): SysCallMapping {
const apiObj: SysCallMapping = {
clearPageIndexForPage: async (ctx, page: string) => {
await db<IndexItem>("page_index").where({ page }).del();
},
2022-03-25 11:03:06 +00:00
set: async (ctx, page: string, key: string, value: any) => {
let changed = await db<IndexItem>("page_index")
.where({ page, key })
.update("value", JSON.stringify(value));
if (changed === 0) {
await db<IndexItem>("page_index").insert({
page,
key,
value: JSON.stringify(value),
});
}
},
2022-03-25 11:03:06 +00:00
batchSet: async (ctx, page: string, kvs: KV[]) => {
for (let { key, value } of kvs) {
2022-03-25 11:03:06 +00:00
await apiObj.set(ctx, page, key, value);
}
},
2022-03-25 11:03:06 +00:00
get: async (ctx, page: string, key: string) => {
let result = await db<IndexItem>("page_index")
.where({ page, key })
.select("value");
if (result.length) {
return JSON.parse(result[0].value);
} else {
return null;
}
},
2022-03-25 11:03:06 +00:00
delete: async (ctx, page: string, key: string) => {
await db<IndexItem>("page_index").where({ page, key }).del();
},
2022-03-25 11:03:06 +00:00
scanPrefixForPage: async (ctx, page: string, prefix: string) => {
return (
await db<IndexItem>("page_index")
.where({ page })
.andWhereLike("key", `${prefix}%`)
.select("page", "key", "value")
).map(({ page, key, value }) => ({
page,
key,
value: JSON.parse(value),
}));
},
2022-03-25 11:03:06 +00:00
scanPrefixGlobal: async (ctx, prefix: string) => {
return (
await db<IndexItem>("page_index")
.andWhereLike("key", `${prefix}%`)
.select("page", "key", "value")
).map(({ page, key, value }) => ({
page,
key,
value: JSON.parse(value),
}));
},
2022-03-25 11:03:06 +00:00
deletePrefixForPage: async (ctx, page: string, prefix: string) => {
return db<IndexItem>("page_index")
.where({ page })
.andWhereLike("key", `${prefix}%`)
.del();
},
2022-03-25 11:03:06 +00:00
clearPageIndex: async () => {
return db<IndexItem>("page_index").del();
},
};
return apiObj;
}