mirror of
https://github.com/pupperpowell/bibdle.git
synced 2026-02-04 10:54:44 -05:00
Version 1
This commit is contained in:
48
src/lib/server/bible-api.ts
Normal file
48
src/lib/server/bible-api.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import type { DailyVerse } from '$lib/server/db/schema';
|
||||
import { getBookById } from './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');
|
||||
}
|
||||
|
||||
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(' ');
|
||||
|
||||
// Validate bookId
|
||||
if (!getBookById(bookId)) {
|
||||
throw new Error(`Unknown book ID from API: ${bookId}`);
|
||||
}
|
||||
|
||||
return {
|
||||
bookId,
|
||||
reference,
|
||||
verseText
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user