-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
471 lines (417 loc) · 12.4 KB
/
api.js
File metadata and controls
471 lines (417 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
const express = require("express");
const bodyParser = require("body-parser");
const fs = require("fs");
const path = require("path");
const util = require("util");
const cors = require("cors");
const readFile = util.promisify(fs.readFile);
const app = express();
const port = 3000;
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Serve the documentation page at root
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "index.html"));
});
app.get("/:translation/single", async (req, res) => {
const { translation } = req.params;
let { book, chapter, verse } = req.query;
chapter = parseInt(chapter, 10);
verse = parseInt(verse, 10);
try {
const jsonData = await readTranslation(translation);
if (
jsonData[book] &&
jsonData[book][chapter] &&
jsonData[book][chapter][verse]
) {
res.json({
book,
chapter,
verse,
content: jsonData[book][chapter][verse],
});
} else {
res
.status(404)
.json({ error: `Verse not found: ${book} ${chapter}:${verse}` });
}
} catch (error) {
console.error("Error:", error);
res.status(500).json({ error: "Error fetching the verse." });
}
});
app.get("/:translation/headings", async (req, res) => {
const { translation } = req.params; // e.g., "CNVS"
const { book, chapter } = req.query;
if (!book) {
return res.status(400).json({ error: "Book parameter is required" });
}
try {
const pericopeData = await readPericope(translation);
if (chapter) {
// Return headings for specific chapter
if (pericopeData[book] && pericopeData[book][chapter]) {
res.json({
book,
chapter: parseInt(chapter, 10),
headings: pericopeData[book][chapter]
});
} else {
res.json({ book, chapter: parseInt(chapter, 10), headings: [] });
}
} else {
// Return headings for entire book
if (pericopeData[book]) {
res.json({
book,
headings: pericopeData[book]
});
} else {
res.json({ book, headings: {} });
}
}
} catch (error) {
console.error("Error fetching headings:", error);
// If pericope file doesn't exist for this translation, return empty or error
// behaving gracefully if file not found might be better, or explicit 404
res.status(404).json({ error: "Headings not available for this translation." });
}
});
app.get("/:translation/multiple", async (req, res) => {
const { translation } = req.params;
const verses = req.query.verses.split(",");
try {
const allVerses = await Promise.all(
verses.map((verse, idx) => fetchVerses(translation, verse, idx))
);
const flattenedVerses = allVerses.flat();
res.json(flattenedVerses);
} catch (error) {
console.error("Error:", error);
res.status(500).json({ error: "Error fetching the verses." });
}
});
// Keyword search endpoint that searches across specified translation(s)
app.get("/:translation/search", async (req, res) => {
const { translation } = req.params;
const { keyword, limit = 50, book, testament } = req.query;
if (!keyword) {
return res.status(400).json({ error: "Keyword parameter is required" });
}
try {
const jsonData = await readTranslation(translation);
const results = searchInTranslation(
jsonData,
keyword,
parseInt(limit),
book,
testament
);
res.json({
translation,
keyword,
book_filter: book || "all",
testament_filter: testament || "all",
total_results: results.length,
results,
});
} catch (error) {
console.error("Search error:", error);
res.status(500).json({ error: "Error performing search." });
}
});
// Multi-translation keyword search endpoint
app.get("/search", async (req, res) => {
const { keyword, translations, limit = 50, book, testament } = req.query;
if (!keyword) {
return res.status(400).json({ error: "Keyword parameter is required" });
}
const translationList = translations ? translations.split(",") : ["NIV"];
try {
const searchPromises = translationList.map(async (translation) => {
try {
const jsonData = await readTranslation(translation.trim());
const results = searchInTranslation(
jsonData,
keyword,
parseInt(limit),
book,
testament
);
return {
translation: translation.trim(),
results,
};
} catch (error) {
console.error(`Error searching in ${translation}:`, error);
return {
translation: translation.trim(),
error: "Translation not found or error loading data",
results: [],
};
}
});
const allResults = await Promise.all(searchPromises);
const totalResults = allResults.reduce(
(sum, tr) => sum + tr.results.length,
0
);
res.json({
keyword,
translations: translationList,
book_filter: book || "all",
testament_filter: testament || "all",
total_results: totalResults,
results_by_translation: allResults,
});
} catch (error) {
console.error("Multi-search error:", error);
res
.status(500)
.json({ error: "Error performing multi-translation search." });
}
});
// Define Old Testament and New Testament books
const OLD_TESTAMENT_BOOKS = [
"Genesis",
"Exodus",
"Leviticus",
"Numbers",
"Deuteronomy",
"Joshua",
"Judges",
"Ruth",
"1 Samuel",
"2 Samuel",
"1 Kings",
"2 Kings",
"1 Chronicles",
"2 Chronicles",
"Ezra",
"Nehemiah",
"Esther",
"Job",
"Psalms",
"Proverbs",
"Ecclesiastes",
"Song of Songs",
"Isaiah",
"Jeremiah",
"Lamentations",
"Ezekiel",
"Daniel",
"Hosea",
"Joel",
"Amos",
"Obadiah",
"Jonah",
"Micah",
"Nahum",
"Habakkuk",
"Zephaniah",
"Haggai",
"Zechariah",
"Malachi",
];
const NEW_TESTAMENT_BOOKS = [
"Matthew",
"Mark",
"Luke",
"John",
"Acts",
"Romans",
"1 Corinthians",
"2 Corinthians",
"Galatians",
"Ephesians",
"Philippians",
"Colossians",
"1 Thessalonians",
"2 Thessalonians",
"1 Timothy",
"2 Timothy",
"Titus",
"Philemon",
"Hebrews",
"James",
"1 Peter",
"2 Peter",
"1 John",
"2 John",
"3 John",
"Jude",
"Revelation",
];
function searchInTranslation(
jsonData,
keyword,
limit = 50,
bookFilter = null,
testamentFilter = null
) {
const results = [];
const searchTerm = keyword.toLowerCase();
// Determine which books to search based on filters
let booksToSearch = Object.keys(jsonData);
if (testamentFilter && testamentFilter.toLowerCase() !== "all") {
if (
testamentFilter.toLowerCase() === "old" ||
testamentFilter.toLowerCase() === "ot"
) {
booksToSearch = booksToSearch.filter((book) =>
OLD_TESTAMENT_BOOKS.includes(book)
);
} else if (
testamentFilter.toLowerCase() === "new" ||
testamentFilter.toLowerCase() === "nt"
) {
booksToSearch = booksToSearch.filter((book) =>
NEW_TESTAMENT_BOOKS.includes(book)
);
}
}
if (bookFilter && bookFilter.toLowerCase() !== "all") {
// Filter by specific book (case-insensitive)
booksToSearch = booksToSearch.filter((book) =>
book.toLowerCase().includes(bookFilter.toLowerCase())
);
}
for (const book of booksToSearch) {
if (!jsonData[book]) continue;
for (const chapter in jsonData[book]) {
for (const verse in jsonData[book][chapter]) {
const content = jsonData[book][chapter][verse];
if (content.toLowerCase().includes(searchTerm)) {
results.push({
book,
chapter: parseInt(chapter),
verse: parseInt(verse),
content,
match_context: getMatchContext(content, searchTerm),
testament: OLD_TESTAMENT_BOOKS.includes(book)
? "Old Testament"
: "New Testament",
});
if (results.length >= limit) {
return results;
}
}
}
}
}
return results;
}
function getMatchContext(content, searchTerm) {
const index = content.toLowerCase().indexOf(searchTerm);
if (index === -1) return content;
const start = Math.max(0, index - 30);
const end = Math.min(content.length, index + searchTerm.length + 30);
const context = content.substring(start, end);
// Highlight the search term in the context
const regex = new RegExp(`(${searchTerm})`, "gi");
return context.replace(regex, "**$1**");
}
async function fetchVerses(translation, verseString, idx) {
verseString = verseString.trim().replace(/\/$/, "");
console.log(`[${idx}] Fetching verses for:`, verseString);
const jsonData = await readTranslation(translation);
// Support "Book Chapter" (e.g., "Genesis 1") and "Book Chapter:Verse" (e.g., "Genesis 1:1")
let match = verseString.match(/^(.*\S)\s+(\d+:\d+(?:-\d+)?(?:-\d+:\d+)?)$/);
let book, range, startChapter, startVerse, endChapter, endVerse;
if (match) {
[_, book, range] = match;
const parts = range.split("-");
if (parts[0].includes(":")) {
[startChapter, startVerse] = parts[0].split(":").map(Number);
} else {
startChapter = Number(parts[0]);
startVerse = 1;
}
if (parts[1] && parts[1].includes(":")) {
[endChapter, endVerse] = parts[1].split(":").map(Number);
} else if (parts[0].includes(":")) {
endChapter = startChapter;
if (parts.length > 1) {
endVerse = Number(parts[1]);
} else {
endVerse = startVerse;
}
} else {
endChapter = Number(parts[1]);
endVerse = Object.keys(
(jsonData[book] && jsonData[book][endChapter]) || {}
).length;
}
} else {
// Try matching "Book Chapter" (e.g., "Genesis 1")
match = verseString.match(/^(.*\S)\s+(\d+)$/);
if (!match) {
console.error(`Invalid verse format: ${verseString}`);
throw new Error(`Invalid verse format: ${verseString}`);
}
[_, book, startChapter] = match;
startChapter = Number(startChapter);
startVerse = 1;
endChapter = startChapter;
endVerse = Object.keys(
(jsonData[book] && jsonData[book][startChapter]) || {}
).length;
}
console.log(
`[${idx}] Parsed range for ${book}: startChapter ${startChapter}, startVerse ${startVerse}, endChapter ${endChapter}, endVerse ${endVerse}`
);
const results = [];
for (let chapter = startChapter; chapter <= endChapter; chapter++) {
const startV = chapter === startChapter ? startVerse : 1;
const endV =
chapter === endChapter
? endVerse
: Object.keys(jsonData[book][chapter]).length;
for (let verse = startV; verse <= endV; verse++) {
if (jsonData[book][chapter][verse]) {
results.push({
book,
chapter,
verse,
content: jsonData[book][chapter][verse],
});
}
}
}
console.log(`[${idx}] Fetched ${results.length} verses for ${book}`);
return results;
}
async function readTranslation(translation) {
const fileName = `${translation.toUpperCase()}.json`;
// Verses are now in json/verses
const jsonDirectory = path.join(__dirname, "json", "verses");
const data = await readFile(path.join(jsonDirectory, fileName), "utf8");
return JSON.parse(data);
}
async function readPericope(translation) {
const fileName = `${translation.toUpperCase()}.json`;
// Pericope data is in json/pericope
const jsonDirectory = path.join(__dirname, "json", "pericope");
const data = await readFile(path.join(jsonDirectory, fileName), "utf8");
return JSON.parse(data);
}
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
//Example Arguments:
//Single Verse:
//http://localhost:3000/NIV/single?book=Genesis&chapter=1&verse=1
//Multiple Verses:
//http://localhost:3000/NIV/multiple?verses=Genesis%201:1-3:7,Matthew%201:1-25,Psalms%201:1-6,Proverbs%201:1-6/
//Keyword Search (Single Translation):
//http://localhost:3000/NIV/search?keyword=love&limit=10
//Keyword Search with Book Filter:
//http://localhost:3000/NIV/search?keyword=faith&book=Hebrews&limit=5
//Keyword Search with Testament Filter:
//http://localhost:3000/ESV/search?keyword=covenant&testament=old&limit=20
//Multi-Translation Search:
//http://localhost:3000/search?keyword=faith&translations=NIV,ESV,KJV&limit=5
//Multi-Translation Search with Filters:
//http://localhost:3000/search?keyword=grace&translations=NIV,ESV,KJV&testament=new&limit=5