117 lines
4.0 KiB
JavaScript
117 lines
4.0 KiB
JavaScript
const axios = require('axios');
|
|
const express = require('express');
|
|
const https = require('https');
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const sqlite3 = require('sqlite3').verbose();
|
|
const bodyParser = require('body-parser');
|
|
|
|
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 };
|
|
|
|
// Middleware to parse JSON bodies
|
|
app.use(express.json()); // Use built-in body-parser for JSON
|
|
|
|
// Set up the SQLite database
|
|
const db = new sqlite3.Database('./books.db', (err) => {
|
|
if (err) {
|
|
console.error('Could not connect to database', err);
|
|
} else {
|
|
console.log('Connected to database');
|
|
db.run(`
|
|
CREATE TABLE IF NOT EXISTS books (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
isbn TEXT,
|
|
title TEXT,
|
|
authors TEXT,
|
|
publishedDate TEXT,
|
|
description TEXT
|
|
)
|
|
`);
|
|
}
|
|
});
|
|
|
|
// 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) {
|
|
console.log('Book data found in Open Library');
|
|
console.log(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' });
|
|
}
|
|
});
|
|
|
|
|
|
// Endpoint to store book in the database
|
|
app.post('/store-book', (req, res) => {
|
|
const { isbn, title, authors, publishedDate, description } = req.body;
|
|
|
|
const query = `INSERT INTO books (isbn, title, authors, publishedDate, description) VALUES (?, ?, ?, ?, ?)`;
|
|
const params = [isbn, title, authors ? authors.join(', ') : '', publishedDate, description || ''];
|
|
|
|
db.run(query, params, function (err) {
|
|
if (err) {
|
|
console.error('Error storing book in database:', err);
|
|
res.status(500).json({ error: 'Failed to store book in database' });
|
|
} else {
|
|
res.json({ success: true, message: 'Book stored successfully', bookId: this.lastID });
|
|
}
|
|
});
|
|
});
|
|
|
|
function formatOpenLibraryData(data) {
|
|
return {
|
|
isbn: data.identifiers.isbn_13 ? data.identifiers.isbn_13[0] : '',
|
|
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',
|
|
};
|
|
}
|
|
|
|
function formatArchiveData(data) {
|
|
return {
|
|
isbn: data.isbn ? data.isbn[0] : '',
|
|
title: data.title,
|
|
authors: data.creator,
|
|
publishedDate: data.date,
|
|
description: data.description ? data.description[0] : 'No description available',
|
|
};
|
|
}
|
|
|
|
const httpsServer = https.createServer(credentials, app);
|
|
|
|
httpsServer.listen(PORT, () => {
|
|
console.log(`HTTPS Server running on https://localhost:${PORT}`);
|
|
});
|