data/utils/engine.js

88 lines
2.2 KiB
JavaScript
Raw Normal View History

2023-11-28 03:05:02 +01:00
import { join } from "https://deno.land/std@0.208.0/path/mod.ts";
import { emptyDir } from "https://deno.land/std@0.196.0/fs/empty_dir.ts";
import { parse, stringify } from "npm:yaml";
2024-01-25 20:45:28 +01:00
import { exists } from "https://deno.land/std@0.213.0/fs/exists.ts";
2023-11-28 03:05:02 +01:00
2024-01-25 20:45:28 +01:00
const SRC_DIR = "./src";
2023-11-28 03:05:02 +01:00
const DEST_DIR = "./dist";
const SCHEMA_DIR = "./schema";
export class Engine {
constructor() {
this.index = {};
this.db = {};
this.schemas = {};
}
async init() {
// load schemas
for await (const dirEntry of Deno.readDir(SCHEMA_DIR)) {
const [fn, _] = dirEntry.name.split(".");
this.schemas[fn] = await readYamlFile(join(SCHEMA_DIR, dirEntry.name));
}
2024-01-25 20:45:28 +01:00
// load
2023-11-28 03:05:02 +01:00
this.index = await readYamlFile(join(SRC_DIR, "index.yaml"));
2024-01-25 20:45:28 +01:00
this.rendered = await this.render(this.index);
}
async loadDir(src) {
const out = {}
const dir = join(SRC_DIR, src)
console.log(`reading dir=${dir}`)
if (await exists(join(dir, "index.yaml"))) {
const out = readYamlFile(join(dir, "index.yaml"));
return out
}
for await (const dirEntry of Deno.readDir(dir)) {
2023-11-28 03:05:02 +01:00
const [fn, ext] = dirEntry.name.split(".");
2024-01-25 20:45:28 +01:00
if (!ext) {
out[fn] = await this.loadDir(join(src, fn))
continue;
}
2023-11-28 03:05:02 +01:00
if (ext === "yaml" && fn !== "index") {
2024-01-25 20:45:28 +01:00
out[fn] = await readYamlFile(join(dir, dirEntry.name));
2023-11-28 03:05:02 +01:00
}
}
2024-01-25 20:45:28 +01:00
return out
}
async render(src) {
const out = {}
for (const key of Object.keys(src)) {
const val = src[key];
if (typeof val === "object" && val.$load) {
out[key] = await this.loadDir(val.$load);
continue;
}
out[key] = val
}
return out
2023-11-28 03:05:02 +01:00
}
async build() {
await emptyDir(DEST_DIR);
2024-01-25 20:45:28 +01:00
//await writeJSONFile(join(DEST_DIR, "index.json"), this.index);
2023-11-28 03:05:02 +01:00
await writeJSONFile(
2024-01-25 20:45:28 +01:00
join(DEST_DIR, "index.json"),
Object.assign({}, this.rendered),
2023-11-28 03:05:02 +01:00
);
2024-01-25 20:45:28 +01:00
/*for (const col of Object.keys(this.db)) {
2023-11-28 03:05:02 +01:00
await writeJSONFile(join(DEST_DIR, `${col}.json`), this.db[col]);
2024-01-25 20:45:28 +01:00
}*/
2023-11-28 03:05:02 +01:00
}
}
async function readYamlFile(fn) {
return parse(await Deno.readTextFile(fn));
}
async function writeJSONFile(fn, data) {
console.log(`File written: ${fn}`);
return Deno.writeTextFile(fn, JSON.stringify(data, null, 2));
}