2023-08-28 15:12:15 +00:00
|
|
|
import { events } from "$sb/syscalls.ts";
|
2022-10-28 14:17:40 +00:00
|
|
|
|
2023-08-28 15:12:15 +00:00
|
|
|
import { replaceTemplateVars } from "../template/template.ts";
|
2022-10-28 14:17:40 +00:00
|
|
|
import { renderTemplate } from "./util.ts";
|
|
|
|
import { parseQuery } from "./parser.ts";
|
|
|
|
import { jsonToMDTable } from "./util.ts";
|
2023-05-23 18:53:53 +00:00
|
|
|
import { ParseTree } from "$sb/lib/tree.ts";
|
2023-08-28 15:12:15 +00:00
|
|
|
import type { PageMeta } from "../../web/types.ts";
|
2022-10-28 14:17:40 +00:00
|
|
|
|
|
|
|
export async function queryDirectiveRenderer(
|
|
|
|
_directive: string,
|
2023-07-02 09:25:32 +00:00
|
|
|
pageMeta: PageMeta,
|
2022-12-14 19:04:20 +00:00
|
|
|
query: string | ParseTree,
|
2022-10-28 14:17:40 +00:00
|
|
|
): Promise<string> {
|
2022-12-14 19:04:20 +00:00
|
|
|
if (typeof query === "string") {
|
|
|
|
throw new Error("Argument must be a ParseTree");
|
|
|
|
}
|
|
|
|
const parsedQuery = parseQuery(
|
2023-07-02 09:25:32 +00:00
|
|
|
JSON.parse(replaceTemplateVars(JSON.stringify(query), pageMeta)),
|
2022-12-14 19:04:20 +00:00
|
|
|
);
|
2022-10-28 14:17:40 +00:00
|
|
|
|
2023-01-26 14:52:37 +00:00
|
|
|
const eventName = `query:${parsedQuery.table}`;
|
|
|
|
|
2022-12-14 19:04:20 +00:00
|
|
|
// console.log("Parsed query", parsedQuery);
|
2022-10-28 14:17:40 +00:00
|
|
|
// Let's dispatch an event and see what happens
|
|
|
|
const results = await events.dispatchEvent(
|
2023-01-26 14:52:37 +00:00
|
|
|
eventName,
|
2023-07-02 09:25:32 +00:00
|
|
|
{ query: parsedQuery, pageName: pageMeta.name },
|
2022-12-09 13:16:28 +00:00
|
|
|
30 * 1000,
|
2022-10-28 14:17:40 +00:00
|
|
|
);
|
|
|
|
if (results.length === 0) {
|
2023-01-26 14:52:37 +00:00
|
|
|
// This means there was no handler for the event which means it's unsupported
|
|
|
|
return `**Error:** Unsupported query source '${parsedQuery.table}'`;
|
2022-10-28 14:17:40 +00:00
|
|
|
} else if (results.length === 1) {
|
2023-05-23 18:53:53 +00:00
|
|
|
// console.log("Parsed query", parsedQuery);
|
2022-10-28 14:17:40 +00:00
|
|
|
if (parsedQuery.render) {
|
2023-05-23 18:53:53 +00:00
|
|
|
const rendered = await renderTemplate(
|
2023-07-02 09:25:32 +00:00
|
|
|
pageMeta,
|
2023-05-23 18:53:53 +00:00
|
|
|
parsedQuery.render,
|
|
|
|
results[0],
|
|
|
|
);
|
2022-10-28 14:17:40 +00:00
|
|
|
return rendered.trim();
|
|
|
|
} else {
|
2022-12-14 10:21:06 +00:00
|
|
|
if (results[0].length === 0) {
|
|
|
|
return "No results";
|
|
|
|
} else {
|
|
|
|
return jsonToMDTable(results[0]);
|
|
|
|
}
|
2022-10-28 14:17:40 +00:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
throw new Error(`Too many query results: ${results.length}`);
|
|
|
|
}
|
|
|
|
}
|