mirror of
https://github.com/pupperpowell/bibdle.git
synced 2026-02-04 10:54:44 -05:00
switched to NKJV, improved grading, improved styling
This commit is contained in:
@@ -1,45 +1,30 @@
|
||||
import type { DailyVerse } from '$lib/server/db/schema';
|
||||
import { getBookById } from './bible';
|
||||
import { getRandomVerses, formatReference } from './xml-bible';
|
||||
|
||||
type ApiVerse = Omit<DailyVerse, 'id' | 'date' | 'createdAt'>;
|
||||
|
||||
export async function fetchRandomVerse(): Promise<ApiVerse> {
|
||||
// Step 1: Fetch random verse to get starting position
|
||||
const randomRes = await fetch('https://bible-api.com/data/web/random');
|
||||
if (!randomRes.ok) {
|
||||
throw new Error(`Failed to fetch random verse: ${randomRes.status}`);
|
||||
}
|
||||
const randomData = await randomRes.json() as any;
|
||||
const randomVerse = randomData.random_verse;
|
||||
if (!randomVerse || !randomVerse.book_id) {
|
||||
throw new Error('Invalid random verse data');
|
||||
// Get 3 random verses from the local XML Bible
|
||||
const verseData = getRandomVerses(3);
|
||||
|
||||
if (!verseData) {
|
||||
throw new Error('Failed to get random verses from Bible XML');
|
||||
}
|
||||
|
||||
const bookId = randomVerse.book_id as string;
|
||||
const chapter = randomVerse.chapter as number;
|
||||
const verse = randomVerse.verse as number;
|
||||
const endVerse = verse + 2;
|
||||
|
||||
// Step 2: Fetch 3 consecutive verses starting from random
|
||||
const rangeUrl = `https://bible-api.com/${bookId}${chapter}:${verse}-${endVerse}`;
|
||||
const rangeRes = await fetch(rangeUrl);
|
||||
if (!rangeRes.ok) {
|
||||
throw new Error(`Failed to fetch verse range: ${rangeRes.status}`);
|
||||
}
|
||||
const rangeData = await rangeRes.json() as any;
|
||||
|
||||
const reference = rangeData.reference as string;
|
||||
const verses = rangeData.verses as any[];
|
||||
if (!verses || verses.length === 0) {
|
||||
throw new Error('No verses in range');
|
||||
}
|
||||
const verseText = verses.map((v: any) => v.text).join(' ');
|
||||
const { bookId, bookName, chapter, startVerse, endVerse, verses } = verseData;
|
||||
|
||||
// Validate bookId
|
||||
if (!getBookById(bookId)) {
|
||||
throw new Error(`Unknown book ID from API: ${bookId}`);
|
||||
throw new Error(`Unknown book ID: ${bookId}`);
|
||||
}
|
||||
|
||||
// Format the reference string (e.g., "Matthew 1:1-3")
|
||||
const reference = formatReference(bookName, chapter, startVerse, endVerse);
|
||||
|
||||
// Join verses with spaces
|
||||
const verseText = verses.join(' ');
|
||||
|
||||
return {
|
||||
bookId,
|
||||
reference,
|
||||
|
||||
@@ -1,10 +1,26 @@
|
||||
import type { BibleBook, Testament, BibleSection } from '$lib/types/bible';
|
||||
import { bibleBooks } from '$lib/types/bible';
|
||||
|
||||
// Book number (1-66) to book ID mapping derived from bibleBooks order property
|
||||
export const bookNumberToId: Record<number, string> = bibleBooks.reduce((acc, book) => {
|
||||
acc[book.order] = book.id;
|
||||
return acc;
|
||||
}, {} as Record<number, string>);
|
||||
|
||||
// Book ID to book number mapping (reverse lookup)
|
||||
export const bookIdToNumber: Record<string, number> = bibleBooks.reduce((acc, book) => {
|
||||
acc[book.id] = book.order;
|
||||
return acc;
|
||||
}, {} as Record<string, number>);
|
||||
|
||||
export function getBookById(id: string): BibleBook | undefined {
|
||||
return bibleBooks.find((book) => book.id === id);
|
||||
}
|
||||
|
||||
export function getBookByNumber(number: number): BibleBook | undefined {
|
||||
return bibleBooks.find((book) => book.order === number);
|
||||
}
|
||||
|
||||
export function getBooksByTestament(testament: Testament): BibleBook[] {
|
||||
return bibleBooks.filter((book) => book.testament === testament);
|
||||
}
|
||||
|
||||
212
src/lib/server/xml-bible.ts
Normal file
212
src/lib/server/xml-bible.ts
Normal file
@@ -0,0 +1,212 @@
|
||||
import { XMLParser } from 'fast-xml-parser';
|
||||
import { readFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import { bookNumberToId, getBookByNumber } from './bible';
|
||||
|
||||
// XML parser configuration
|
||||
const parser = new XMLParser({
|
||||
ignoreAttributes: false,
|
||||
attributeNamePrefix: '',
|
||||
textNodeName: '_text',
|
||||
parseAttributeValue: true,
|
||||
trimValues: true,
|
||||
isArray: (name) => ['chapter', 'verse'].includes(name)
|
||||
});
|
||||
|
||||
// Cache for parsed Bible data to avoid re-reading the file
|
||||
let cachedBible: any = null;
|
||||
|
||||
interface VerseData {
|
||||
number: number;
|
||||
_text: string;
|
||||
}
|
||||
|
||||
interface ChapterData {
|
||||
number: number;
|
||||
verse: VerseData[];
|
||||
}
|
||||
|
||||
interface BookData {
|
||||
number: number;
|
||||
chapter: ChapterData[];
|
||||
}
|
||||
|
||||
interface TestamentData {
|
||||
name: string;
|
||||
book: BookData[];
|
||||
}
|
||||
|
||||
interface BibleData {
|
||||
bible: {
|
||||
testament: TestamentData[];
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Load and parse the Bible XML file
|
||||
*/
|
||||
function loadBibleXml(): BibleData {
|
||||
if (cachedBible) {
|
||||
return cachedBible;
|
||||
}
|
||||
|
||||
const xmlPath = join(process.cwd(), 'EnglishNKJBible.xml');
|
||||
const xmlContent = readFileSync(xmlPath, 'utf-8');
|
||||
cachedBible = parser.parse(xmlContent) as BibleData;
|
||||
return cachedBible;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a specific book from the Bible XML
|
||||
*/
|
||||
function getBook(bookNumber: number): BookData | null {
|
||||
const bible = loadBibleXml();
|
||||
|
||||
// Old Testament books are 1-39, New Testament are 40-66
|
||||
const testamentIndex = bookNumber <= 39 ? 0 : 1;
|
||||
const testament = bible.bible.testament[testamentIndex];
|
||||
|
||||
if (!testament) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Find the book by number within the testament
|
||||
const bookIndex = bookNumber <= 39 ? bookNumber - 1 : bookNumber - 40;
|
||||
return testament.book[bookIndex] || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a specific chapter from a book
|
||||
*/
|
||||
function getChapter(bookNumber: number, chapterNumber: number): ChapterData | null {
|
||||
const book = getBook(bookNumber);
|
||||
if (!book) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return book.chapter.find((ch) => ch.number === chapterNumber) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of verses in a specific chapter
|
||||
*/
|
||||
function getVerseCount(bookNumber: number, chapterNumber: number): number {
|
||||
const chapter = getChapter(bookNumber, chapterNumber);
|
||||
return chapter ? chapter.verse.length : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of chapters in a specific book
|
||||
*/
|
||||
function getChapterCount(bookNumber: number): number {
|
||||
const book = getBook(bookNumber);
|
||||
return book ? book.chapter.length : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract consecutive verses from a specific location
|
||||
*/
|
||||
function extractVerses(
|
||||
bookNumber: number,
|
||||
chapterNumber: number,
|
||||
startVerse: number,
|
||||
count: number
|
||||
): string[] {
|
||||
const chapter = getChapter(bookNumber, chapterNumber);
|
||||
if (!chapter) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const verses: string[] = [];
|
||||
for (let i = 0; i < count; i++) {
|
||||
const verseIndex = startVerse - 1 + i; // Convert to 0-based index
|
||||
if (verseIndex >= chapter.verse.length) {
|
||||
break;
|
||||
}
|
||||
verses.push(chapter.verse[verseIndex]._text);
|
||||
}
|
||||
|
||||
return verses;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a random book number (1-66)
|
||||
*/
|
||||
function getRandomBookNumber(): number {
|
||||
return Math.floor(Math.random() * 66) + 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a random chapter number for a specific book
|
||||
*/
|
||||
function getRandomChapterNumber(bookNumber: number): number {
|
||||
const chapterCount = getChapterCount(bookNumber);
|
||||
return Math.floor(Math.random() * chapterCount) + 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a random starting verse number for a specific chapter
|
||||
* Ensures there are enough verses for the requested count
|
||||
*/
|
||||
function getRandomStartVerse(bookNumber: number, chapterNumber: number, verseCount: number): number {
|
||||
const totalVerses = getVerseCount(bookNumber, chapterNumber);
|
||||
const maxStartVerse = Math.max(1, totalVerses - verseCount + 1);
|
||||
return Math.floor(Math.random() * maxStartVerse) + 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a random set of verses from the Bible
|
||||
* Returns 3 consecutive verses by default
|
||||
*/
|
||||
export function getRandomVerses(count: number = 3): {
|
||||
bookId: string;
|
||||
bookName: string;
|
||||
chapter: number;
|
||||
startVerse: number;
|
||||
endVerse: number;
|
||||
verses: string[];
|
||||
} | null {
|
||||
// Try up to 10 times to find a valid passage
|
||||
for (let attempt = 0; attempt < 10; attempt++) {
|
||||
const bookNumber = getRandomBookNumber();
|
||||
const book = getBookByNumber(bookNumber);
|
||||
|
||||
if (!book) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const chapterNumber = getRandomChapterNumber(bookNumber);
|
||||
const verseCount = getVerseCount(bookNumber, chapterNumber);
|
||||
|
||||
// Skip chapters that don't have enough verses
|
||||
if (verseCount < count) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const startVerse = getRandomStartVerse(bookNumber, chapterNumber, count);
|
||||
const verses = extractVerses(bookNumber, chapterNumber, startVerse, count);
|
||||
|
||||
if (verses.length === count) {
|
||||
return {
|
||||
bookId: book.id,
|
||||
bookName: book.name,
|
||||
chapter: chapterNumber,
|
||||
startVerse,
|
||||
endVerse: startVerse + count - 1,
|
||||
verses
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a reference string from verse data
|
||||
*/
|
||||
export function formatReference(bookName: string, chapter: number, startVerse: number, endVerse: number): string {
|
||||
if (startVerse === endVerse) {
|
||||
return `${bookName} ${chapter}:${startVerse}`;
|
||||
}
|
||||
return `${bookName} ${chapter}:${startVerse}-${endVerse}`;
|
||||
}
|
||||
Reference in New Issue
Block a user