@gent-js/gent
Version:
template-based data generator.
64 lines (63 loc) • 2.22 kB
JavaScript
import * as fs from "node:fs";
import * as fsPromises from "node:fs/promises";
import { buildDocumentFromJsonTemplate } from "./buildDocumentFromJsonTemplate.js";
import { buildDocumentFromTextTemplate } from "./buildDocumentFromTextTemplate.js";
import { WeightedItemFeeder, } from "./common/weightedItemFeeder.js";
import { assertNever } from "./utils.js";
export async function createDocumentFeeder(templateOptionsArray, programOptions, commandManager) {
const { from, to, count } = programOptions;
const sharedDocumentOptions = {
from: from,
to: to,
total: count,
};
const documentFeeder = new WeightedItemFeeder();
const weightedDocuments = await Promise.all(templateOptionsArray.map(async (templateOptions) => createWeightedDocument(templateOptions, sharedDocumentOptions, commandManager)));
weightedDocuments.forEach((weightedDocument) => {
if (weightedDocument === undefined) {
return;
}
documentFeeder.addWeightedItem(weightedDocument);
});
return documentFeeder;
}
async function createWeightedDocument(templateOptions, sharedDocumentOptions, commandManager) {
const { mode, path, weight } = templateOptions;
const documentOptions = {
shared: sharedDocumentOptions,
path: path,
};
try {
await fsPromises.access(path, fs.constants.R_OK);
}
catch (error) {
console.error(`cannot access template file. ${path}`);
console.log(error);
return undefined;
}
let templateString;
try {
templateString = await fsPromises.readFile(path, {
encoding: "utf8",
});
}
catch (error) {
console.log(error);
return undefined;
}
let documentContent;
if (mode === "text") {
documentContent = buildDocumentFromTextTemplate(templateString, commandManager, documentOptions);
}
else if (mode === "json") {
documentContent = buildDocumentFromJsonTemplate(templateString, commandManager, documentOptions);
}
else {
assertNever(mode);
}
const weightDocument = {
content: documentContent,
weight: weight,
};
return weightDocument;
}