Initial mvp-ish
This commit is contained in:
72
index.js
Normal file
72
index.js
Normal file
@@ -0,0 +1,72 @@
|
||||
const axios = require('axios');
|
||||
const express = require('express');
|
||||
const https = require('https');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 3000;
|
||||
|
||||
// SSL certificate paths
|
||||
const privateKey = fs.readFileSync(path.join(__dirname, 'server.key'), 'utf8');
|
||||
const certificate = fs.readFileSync(path.join(__dirname, 'server.cert'), 'utf8');
|
||||
|
||||
const credentials = { key: privateKey, cert: certificate };
|
||||
|
||||
// Serve static files from the 'public' directory
|
||||
app.use(express.static(path.join(__dirname, 'public')));
|
||||
|
||||
// Endpoint to fetch book details by ISBN
|
||||
app.get('/book/:isbn', async (req, res) => {
|
||||
const { isbn } = req.params;
|
||||
console.log(`Fetching book data for ISBN: ${isbn}`);
|
||||
|
||||
try {
|
||||
// First try Open Library
|
||||
const openLibraryResponse = await axios.get(`https://openlibrary.org/api/books?bibkeys=ISBN:${isbn}&format=json&jscmd=data`);
|
||||
const bookData = openLibraryResponse.data[`ISBN:${isbn}`];
|
||||
|
||||
if (bookData) {
|
||||
res.json(formatOpenLibraryData(bookData));
|
||||
} else {
|
||||
// Fallback to Internet Archive if no data from Open Library
|
||||
const archiveResponse = await axios.get(`https://archive.org/advancedsearch.php?q=isbn:${isbn}&output=json`);
|
||||
const archiveData = archiveResponse.data;
|
||||
|
||||
if (archiveData.response.numFound > 0) {
|
||||
res.json(formatArchiveData(archiveData.response.docs[0]));
|
||||
} else {
|
||||
res.status(404).json({ error: 'Book not found in Open Library or Internet Archive.' });
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
res.status(500).json({ error: 'Failed to fetch book data' });
|
||||
}
|
||||
});
|
||||
|
||||
function formatOpenLibraryData(data) {
|
||||
return {
|
||||
title: data.title,
|
||||
authors: data.authors ? data.authors.map(author => author.name) : [],
|
||||
publishedDate: data.publish_date,
|
||||
description: data.excerpts ? data.excerpts[0].text : 'No description available',
|
||||
cover: data.cover ? data.cover.large : ''
|
||||
};
|
||||
}
|
||||
|
||||
function formatArchiveData(data) {
|
||||
return {
|
||||
title: data.title,
|
||||
authors: data.creator,
|
||||
publishedDate: data.date,
|
||||
description: data.description ? data.description[0] : 'No description available',
|
||||
cover: data.cover ? `https://archive.org/services/img/${data.identifier}` : ''
|
||||
};
|
||||
}
|
||||
|
||||
const httpsServer = https.createServer(credentials, app);
|
||||
|
||||
httpsServer.listen(PORT, () => {
|
||||
console.log(`HTTPS Server running on https://localhost:${PORT}`);
|
||||
});
|
||||
Reference in New Issue
Block a user