Files
spsays-training/scripts/seed-iso.ts
T
2026-04-17 22:51:58 +05:30

236 lines
6.5 KiB
TypeScript

/**
* seed-iso.ts — Push Śrī Īśopaniṣad JSON data into MongoDB.
*
* Uses the native MongoDB driver (same pattern as seed-nod.ts) to avoid
* Prisma replica-set write requirements.
*
* ISO is a verse book (like BG) but also has prose intro segments.
* We use volume=0 as the sentinel for "no volumes" on the prose side.
*
* Collections written:
* - book_meta → one doc { book: "iso", data: <intro.json> }
* - verses → 19 verse docs (Invocation + Mantras 1-18)
* - prose_chapters → 3 intro segment docs (front-pages, introduction, about-the-author)
*
* Usage:
* npx tsx scripts/seed-iso.ts
*/
import dotenv from "dotenv";
import fs from "fs";
import path from "path";
import { MongoClient } from "mongodb";
// Load env
dotenv.config({ path: ".env.local" });
dotenv.config({ path: ".env" });
const DATABASE_URL = process.env.DATABASE_URL;
if (!DATABASE_URL) {
console.error("❌ DATABASE_URL is not set in .env");
process.exit(1);
}
const BASE_DIR = path.resolve(__dirname, "..");
const ISO_DIR = path.join(BASE_DIR, "lib", "jsons", "books", "iso");
/** Volume sentinel for books without volumes. */
const NO_VOLUME = 0;
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function readJson<T>(filePath: string): T {
return JSON.parse(fs.readFileSync(filePath, "utf-8"));
}
/**
* Insert documents one at a time with a small delay every N docs.
* Uses insertOne to avoid BSON wire-protocol corruption.
*/
async function insertBatched(
col: ReturnType<ReturnType<MongoClient["db"]>["collection"]>,
docs: Record<string, unknown>[],
) {
for (let i = 0; i < docs.length; i++) {
await col.insertOne(docs[i]);
if ((i + 1) % 100 === 0) {
await new Promise((r) => setTimeout(r, 100));
}
}
}
// ---------------------------------------------------------------------------
// Types for the JSON files
// ---------------------------------------------------------------------------
type IsoIntroJson = {
book: string;
title: string;
author: string;
year: number;
description: string;
totalMantras: number;
mantras: { number: number; title: string; slug: string }[];
};
type IsoVerseJson = {
book: string;
book_title: string;
mantra: number;
title: string;
reference: string;
devanagari: string;
transliteration: string;
synonyms: { word: string; meanings: string[] }[];
translation: string;
purport: string[];
};
type IsoIntroSegmentJson = {
slug: string;
title: string;
type: string;
book: string;
order: number;
paragraphs: string[];
};
// ---------------------------------------------------------------------------
// Seed function
// ---------------------------------------------------------------------------
async function seedIso(db: ReturnType<MongoClient["db"]>) {
const introPath = path.join(ISO_DIR, "intro.json");
if (!fs.existsSync(introPath)) {
console.error("❌ ISO intro.json not found at", introPath);
process.exit(1);
}
const intro = readJson<IsoIntroJson>(introPath);
// ---- 1. Book meta ----
const metaCol = db.collection("book_meta");
await metaCol.deleteMany({ book: "iso" });
await metaCol.insertOne({ book: "iso", data: intro });
console.log(" 📖 ISO book meta inserted");
// ---- 2. Verses ----
const versesCol = db.collection("verses");
await versesCol.deleteMany({ book: "iso" });
const verseDocs: Record<string, unknown>[] = [];
// Verse files: invocation.json, 01.json through 18.json
const verseFiles = [
"invocation.json",
...Array.from({ length: 18 }, (_, i) =>
String(i + 1).padStart(2, "0") + ".json"
),
];
const versesDir = path.join(ISO_DIR, "verses");
for (const file of verseFiles) {
const filePath = path.join(versesDir, file);
if (!fs.existsSync(filePath)) {
console.warn(` ⚠️ Verse file not found, skipping: ${file}`);
continue;
}
const v = readJson<IsoVerseJson>(filePath);
verseDocs.push({
book: "iso",
division: null,
chapter: v.mantra,
verse: 1,
verseEnd: null,
reference: v.reference,
bookTitle: v.book_title,
devanagari: v.devanagari,
bengali: null,
transliteration: v.transliteration,
synonyms: v.synonyms,
translation: v.translation,
purport: v.purport,
});
}
console.log(` 📜 Verses prepared: ${verseDocs.length}`);
console.log(` Inserting ${verseDocs.length} verse documents...`);
await insertBatched(versesCol, verseDocs);
const totalVerses = await versesCol.countDocuments({ book: "iso" });
console.log(` ✅ ISO verses: ${totalVerses} in MongoDB`);
// ---- 3. Prose intro segments ----
const proseCol = db.collection("prose_chapters");
await proseCol.deleteMany({ book: "iso" });
const proseDocs: Record<string, unknown>[] = [];
const introSegmentFiles = [
"front-pages.json",
"introduction.json",
"about-the-author.json",
];
const introDir = path.join(ISO_DIR, "intro");
for (const file of introSegmentFiles) {
const filePath = path.join(introDir, file);
if (!fs.existsSync(filePath)) {
console.warn(` ⚠️ Intro segment not found, skipping: ${file}`);
continue;
}
const seg = readJson<IsoIntroSegmentJson>(filePath);
proseDocs.push({
book: "iso",
volume: NO_VOLUME,
chapter: null,
title: seg.title,
type: seg.type || "intro-segment",
slug: `intro-${seg.slug}`,
order: seg.order,
paragraphs: seg.paragraphs,
});
}
console.log(` 📄 Intro segments prepared: ${proseDocs.length}`);
console.log(` Inserting ${proseDocs.length} prose documents...`);
await insertBatched(proseCol, proseDocs);
const totalProse = await proseCol.countDocuments({ book: "iso" });
console.log(` ✅ ISO prose: ${totalProse} entries in MongoDB`);
}
// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------
async function main() {
console.log("🌱 Seeding Śrī Īśopaniṣad...\n");
const client = new MongoClient(DATABASE_URL!);
await client.connect();
console.log("📡 Connected to MongoDB\n");
const db = client.db();
const start = Date.now();
await seedIso(db);
const elapsed = ((Date.now() - start) / 1000).toFixed(1);
console.log(`\n🎉 Done in ${elapsed}s`);
await client.close();
}
main().catch((err) => {
console.error("❌ Seed failed:", err);
process.exit(1);
});