Add locations
This commit is contained in:
278
index.js
278
index.js
@@ -18,7 +18,110 @@ 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 { Sequelize, DataTypes } = require('sequelize');
|
||||
|
||||
// Initialize Sequelize
|
||||
const sequelize = new Sequelize({
|
||||
dialect: 'sqlite',
|
||||
storage: './books.db',
|
||||
});
|
||||
|
||||
|
||||
// Test the connection
|
||||
|
||||
sequelize.authenticate()
|
||||
.then(() => {
|
||||
console.log('Connection has been established successfully.');
|
||||
})
|
||||
.catch(err => {
|
||||
console.error('Unable to connect to the database:', err);
|
||||
});
|
||||
// TODO: Add physical location of book to database
|
||||
const Book = sequelize.define('Book', {
|
||||
id: {
|
||||
type: DataTypes.INTEGER,
|
||||
autoIncrement: true,
|
||||
primaryKey: true,
|
||||
},
|
||||
isbn: {
|
||||
type: DataTypes.TEXT,
|
||||
allowNull: false,
|
||||
unique: true,
|
||||
},
|
||||
title: {
|
||||
type: DataTypes.TEXT,
|
||||
allowNull: false,
|
||||
},
|
||||
authors: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
publishedDate: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
description: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
url: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
number_of_pages: {
|
||||
type: DataTypes.INTEGER,
|
||||
},
|
||||
identifiers: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
publishers: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
subjects: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
notes: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
cover_small: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
cover_medium: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
cover_large: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
location_id: {
|
||||
type: DataTypes.INTEGER,
|
||||
references: {
|
||||
model: Location,
|
||||
key: 'id'
|
||||
}
|
||||
}
|
||||
}, {
|
||||
tableName: 'books',
|
||||
timestamps: false, // If your table doesn't have `createdAt` and `updatedAt`
|
||||
});
|
||||
|
||||
const Location = sequelize.define('Location', {
|
||||
id: {
|
||||
type: DataTypes.INTEGER,
|
||||
autoIncrement: true,
|
||||
primaryKey: true,
|
||||
},
|
||||
name: {
|
||||
type: DataTypes.TEXT,
|
||||
allowNull: false,
|
||||
},
|
||||
shelf: {
|
||||
type: DataTypes.TEXT,
|
||||
allowNull: false,
|
||||
}
|
||||
}, {
|
||||
tableName: 'locations',
|
||||
timestamps: false, // If your table doesn't have `createdAt` and `updatedAt`
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
// Set up the SQLite database
|
||||
const db = new sqlite3.Database('./books.db', (err) => {
|
||||
if (err) {
|
||||
@@ -51,14 +154,22 @@ const db = new sqlite3.Database('./books.db', (err) => {
|
||||
// Serve static files from the 'public' directory
|
||||
app.use(express.static(path.join(__dirname, 'public')));
|
||||
|
||||
// Endpoint to fetch book details by ISBN
|
||||
// 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 Google Books
|
||||
// First, check if the book is in the local database
|
||||
const book = await Book.findOne({ where: { isbn } });
|
||||
|
||||
if (book) {
|
||||
console.log('Book found in the local database');
|
||||
res.json({ source: 'local', data: book });
|
||||
return;
|
||||
}
|
||||
|
||||
// If not found locally, try Google Books
|
||||
const apiKey = 'AIzaSyCQikthZ5TlkFTcKTG8n171dRafosK2Mg8';
|
||||
const googleBooksResponse = await axios.get(`https://www.googleapis.com/books/v1/volumes?q=${isbn}&key=${apiKey}`);
|
||||
|
||||
@@ -77,7 +188,7 @@ app.get('/book/:isbn', async (req, res) => {
|
||||
if (googleBooksResponse.data.items && googleBooksResponse.data.items.length > 0) {
|
||||
const googleBookData = googleBooksResponse.data.items[0];
|
||||
console.log('Book data found in Google Books');
|
||||
res.json(formatGoogleBooksData(googleBookData));
|
||||
res.json({ source: 'external', data: formatGoogleBooksData(googleBookData) });
|
||||
return;
|
||||
} else {
|
||||
console.log('Book not found in Google Books');
|
||||
@@ -101,7 +212,7 @@ app.get('/book/:isbn', async (req, res) => {
|
||||
|
||||
if (bookData) {
|
||||
console.log('Book data found in Open Library');
|
||||
res.json(formatOpenLibraryData(bookData));
|
||||
res.json({ source: 'external', data: formatOpenLibraryData(bookData) });
|
||||
return;
|
||||
} else {
|
||||
console.log('Book not found in Open Library');
|
||||
@@ -113,7 +224,7 @@ app.get('/book/:isbn', async (req, res) => {
|
||||
|
||||
if (archiveData) {
|
||||
console.log('Book data found in the Internet Archive');
|
||||
res.json(formatArchiveData(archiveData));
|
||||
res.json({ source: 'external', data: formatArchiveData(archiveData) });
|
||||
} else {
|
||||
console.log('Book not found in the Internet Archive');
|
||||
res.status(404).json({ error: 'Book not found' });
|
||||
@@ -126,20 +237,39 @@ app.get('/book/:isbn', async (req, res) => {
|
||||
|
||||
|
||||
|
||||
|
||||
// Endpoint to search for book by title
|
||||
app.get('/search-title', async (req, res) => {
|
||||
const { title } = req.query;
|
||||
console.log(`Searching for book by title: ${title}`);
|
||||
const { title, internalOnly=false } = req.query;
|
||||
console.log(`Searching for books by title or related fields: ${title}`);
|
||||
|
||||
try {
|
||||
// Search Open Library by title, limit to 5 results
|
||||
// First, search in the local database across all relevant fields
|
||||
const localBooks = await Book.findAll({
|
||||
where: {
|
||||
[Sequelize.Op.or]: [
|
||||
{ title: { [Sequelize.Op.like]: `%${title}%` } },
|
||||
{ authors: { [Sequelize.Op.like]: `%${title}%` } },
|
||||
{ publishers: { [Sequelize.Op.like]: `%${title}%` } },
|
||||
{ description: { [Sequelize.Op.like]: `%${title}%` } },
|
||||
{ subjects: { [Sequelize.Op.like]: `%${title}%` } }
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
if (localBooks.length > 0) {
|
||||
console.log('Books found in the local database');
|
||||
res.json({ source: 'local', results: localBooks });
|
||||
return;
|
||||
}
|
||||
if (internalOnly) {
|
||||
res.status(404).json({ error: 'No books found with that title or related fields.' });
|
||||
return;
|
||||
}
|
||||
// If no results found locally, proceed to search external sources
|
||||
const openLibraryResponse = await axios.get(`https://openlibrary.org/search.json?q=${encodeURIComponent(title)}&limit=7`);
|
||||
const searchResults = openLibraryResponse.data.docs;
|
||||
console.log(searchResults);
|
||||
|
||||
if (searchResults.length > 0) {
|
||||
console.log('Books found by title');
|
||||
console.log('Books found by title in external sources');
|
||||
const bookData = searchResults.map(result => ({
|
||||
title: result.title,
|
||||
authors: result.author_name || [],
|
||||
@@ -148,88 +278,63 @@ app.get('/search-title', async (req, res) => {
|
||||
publisher: result.publisher ? result.publisher[0] : '',
|
||||
key: result.key // Unique key to fetch more detailed data later if needed
|
||||
}));
|
||||
console.log(bookData);
|
||||
res.json({ results: bookData });
|
||||
res.json({ source: 'external', results: bookData });
|
||||
} else {
|
||||
res.status(404).json({ error: 'No books found with that title.' });
|
||||
res.status(404).json({ error: 'No books found with that title or related fields.' });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
res.status(500).json({ error: 'Failed to search for book by title' });
|
||||
res.status(500).json({ error: 'Failed to search for book by title or related fields' });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
// Endpoint to store book in the database
|
||||
// Endpoint to store book in the database
|
||||
// Endpoint to store book in the database
|
||||
app.post('/store-book', (req, res) => {
|
||||
const {
|
||||
isbn, title, authors, publishedDate, description, url,
|
||||
number_of_pages, identifiers, publishers, subjects,
|
||||
notes, cover_small, cover_medium, cover_large
|
||||
} = req.body;
|
||||
|
||||
// Check if a book with the same ISBN already exists
|
||||
const checkQuery = `SELECT * FROM books WHERE isbn = ?`;
|
||||
db.get(checkQuery, [isbn], (err, row) => {
|
||||
if (err) {
|
||||
console.error('Error checking for existing book:', err);
|
||||
return res.status(500).json({ error: 'Failed to check for existing book' });
|
||||
}
|
||||
|
||||
if (row) {
|
||||
// Book already exists, update the existing record
|
||||
const updateQuery = `
|
||||
UPDATE books
|
||||
SET title = ?, authors = ?, publishedDate = ?, description = ?, url = ?,
|
||||
number_of_pages = ?, identifiers = ?, publishers = ?, subjects = ?,
|
||||
notes = ?, cover_small = ?, cover_medium = ?, cover_large = ?
|
||||
WHERE isbn = ?
|
||||
`;
|
||||
|
||||
const updateParams = [
|
||||
title, authors ? authors.join(', ') : '', publishedDate, description || '',
|
||||
url, number_of_pages, identifiers, publishers, subjects,
|
||||
notes, cover_small, cover_medium, cover_large, isbn
|
||||
];
|
||||
|
||||
db.run(updateQuery, updateParams, function (err) {
|
||||
if (err) {
|
||||
console.error('Error updating book in database:', err);
|
||||
return res.status(500).json({ error: 'Failed to update book in database' });
|
||||
} else {
|
||||
res.json({ success: true, message: 'Book updated successfully' });
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// Book does not exist, insert a new record
|
||||
const insertQuery = `
|
||||
INSERT INTO books (
|
||||
isbn, title, authors, publishedDate, description, url,
|
||||
number_of_pages, identifiers, publishers, subjects,
|
||||
notes, cover_small, cover_medium, cover_large
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`;
|
||||
|
||||
const insertParams = [
|
||||
isbn, title, authors ? authors.join(', ') : '', publishedDate, description || '',
|
||||
url, number_of_pages, identifiers, publishers, subjects,
|
||||
notes, cover_small, cover_medium, cover_large
|
||||
];
|
||||
|
||||
db.run(insertQuery, insertParams, function (err) {
|
||||
if (err) {
|
||||
console.error('Error storing book in database:', err);
|
||||
return res.status(500).json({ error: 'Failed to store book in database' });
|
||||
} else {
|
||||
res.json({ success: true, message: 'Book stored successfully', bookId: this.lastID });
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
app.post('/store-book', async (req, res) => {
|
||||
try {
|
||||
const book = await Book.create(req.body);
|
||||
res.json({ success: true, book });
|
||||
} catch (error) {
|
||||
console.error('Failed to store book:', error);
|
||||
res.status(500).json({ error: 'Failed to store book in database' });
|
||||
}
|
||||
});
|
||||
|
||||
app.put('/book/:isbn', async (req, res) => {
|
||||
try {
|
||||
const { isbn } = req.params;
|
||||
const book = await Book.findOne({ where: { isbn } });
|
||||
if (book) {
|
||||
await book.update(req.body);
|
||||
res.json({ success: true, message: 'Book updated successfully' });
|
||||
} else {
|
||||
res.status(404).json({ error: 'Book not found' });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to update book:', error);
|
||||
res.status(500).json({ error: 'Failed to update book in database' });
|
||||
}
|
||||
});
|
||||
|
||||
app.delete('/book/:id', async (req, res) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const book = await Book.findByPk(id);
|
||||
if (book) {
|
||||
await book.destroy();
|
||||
res.json({ success: true, message: 'Book deleted successfully' });
|
||||
} else {
|
||||
res.status(404).json({ error: 'Book not found' });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to delete book:', error);
|
||||
res.status(500).json({ error: 'Failed to delete book from database' });
|
||||
}
|
||||
});
|
||||
|
||||
// TODO: Function to checkout a book
|
||||
|
||||
// TODO: Function to return a book
|
||||
|
||||
function formatOpenLibraryData(data) {
|
||||
return {
|
||||
@@ -294,6 +399,11 @@ function formatGoogleBooksData(data) {
|
||||
|
||||
const httpsServer = https.createServer(credentials, app);
|
||||
|
||||
sequelize.sync({ alter: true }).then(() => {
|
||||
console.log('Database & tables synced!');
|
||||
});
|
||||
|
||||
|
||||
httpsServer.listen(PORT, () => {
|
||||
console.log(`HTTPS Server running on https://localhost:${PORT}`);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user