1
0
silverbullet/packages/plugs/query/materialized_queries.ts

70 lines
2.1 KiB
TypeScript
Raw Normal View History

import {
flashNotification,
getCurrentPage,
getText,
reloadPage,
2022-04-25 08:33:38 +00:00
save,
2022-04-25 09:24:13 +00:00
} from "@silverbulletmd/plugos-silverbullet-syscall/editor";
2022-04-01 15:07:08 +00:00
2022-04-25 09:24:13 +00:00
import {
readPage,
writePage,
} from "@silverbulletmd/plugos-silverbullet-syscall/space";
import { invokeFunction } from "@silverbulletmd/plugos-silverbullet-syscall/system";
import { parseQuery } from "./engine";
import { replaceTemplateVars } from "../core/template";
import { queryRegex, removeQueries } from "./util";
2022-04-25 08:33:38 +00:00
import { dispatch } from "@plugos/plugos-syscall/event";
import { replaceAsync } from "../lib/util";
2022-04-25 09:24:13 +00:00
import { parseMarkdown } from "@silverbulletmd/plugos-silverbullet-syscall/markdown";
2022-03-29 15:02:28 +00:00
export async function updateMaterializedQueriesCommand() {
2022-04-01 15:07:08 +00:00
const currentPage = await getCurrentPage();
await save();
await flashNotification("Updating materialized queries...");
2022-04-05 15:02:17 +00:00
await invokeFunction(
"server",
"updateMaterializedQueriesOnPage",
currentPage
);
2022-04-01 15:07:08 +00:00
await reloadPage();
await flashNotification("Updated materialized queries");
2022-03-29 15:02:28 +00:00
}
export async function whiteOutQueriesCommand() {
const text = await getText();
const parsed = await parseMarkdown(text);
console.log(removeQueries(parsed));
}
2022-03-29 15:02:28 +00:00
// Called from client, running on server
export async function updateMaterializedQueriesOnPage(pageName: string) {
2022-04-01 15:07:08 +00:00
let { text } = await readPage(pageName);
text = await replaceAsync(
text,
queryRegex,
async (fullMatch, startQuery, query, body, endQuery) => {
let parsedQuery = parseQuery(replaceTemplateVars(query, pageName));
console.log("Parsed query", parsedQuery);
// Let's dispatch an event and see what happens
let results = await dispatch(
`query:${parsedQuery.table}`,
{ query: parsedQuery, pageName: pageName },
10 * 1000
);
if (results.length === 0) {
return `${startQuery}\n${endQuery}`;
} else if (results.length === 1) {
return `${startQuery}\n${results[0]}\n${endQuery}`;
} else {
console.error("Too many query results", results);
return fullMatch;
}
2022-03-29 15:02:28 +00:00
}
);
2022-03-29 15:02:28 +00:00
// console.log("New text", text);
2022-04-01 15:07:08 +00:00
await writePage(pageName, text);
2022-03-29 15:02:28 +00:00
}