From dce1e5686364afefcd3668b700955df5dbda9c6b Mon Sep 17 00:00:00 2001 From: jingh999 Date: Thu, 16 May 2024 11:12:18 +0200 Subject: [PATCH 1/3] mongo api --- package.json | 4 +- server.js | 101 +++++++++++++++++++++++++++++++++++++++++++++------ 2 files changed, 92 insertions(+), 13 deletions(-) diff --git a/package.json b/package.json index 6830a48aa..323c08869 100644 --- a/package.json +++ b/package.json @@ -13,8 +13,10 @@ "@babel/node": "^7.16.8", "@babel/preset-env": "^7.16.11", "cors": "^2.8.5", + "dotenv": "^16.4.5", "express": "^4.17.3", - "mongoose": "^8.0.0", + "express-list-endpoints": "^7.1.0", + "mongoose": "^8.3.4", "nodemon": "^3.0.1" } } diff --git a/server.js b/server.js index 647e7b144..5578ed7b2 100644 --- a/server.js +++ b/server.js @@ -1,22 +1,16 @@ import express from "express"; import cors from "cors"; import mongoose from "mongoose"; +import expressListEndpoints from "express-list-endpoints"; +import booksData from "./data/books.json"; +import dotenv from "dotenv" -// If you're using one of our datasets, uncomment the appropriate import below -// to get started! -// import avocadoSalesData from "./data/avocado-sales.json"; -// import booksData from "./data/books.json"; -// import goldenGlobesData from "./data/golden-globes.json"; -// import netflixData from "./data/netflix-titles.json"; -// import topMusicData from "./data/top-music.json"; +dotenv.config() const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/project-mongo"; mongoose.connect(mongoUrl); mongoose.Promise = Promise; -// Defines the port the app will run on. Defaults to 8080, but can be overridden -// when starting the server. Example command to overwrite PORT env variable value: -// PORT=9000 npm start const port = process.env.PORT || 8080; const app = express(); @@ -24,12 +18,95 @@ const app = express(); app.use(cors()); app.use(express.json()); +const Books = mongoose.model("Books", { + bookID: { type: Number, required: true }, + title: { type: String, required: true }, + authors: { type: String, required: true }, + average_rating: Number, + isbn: Number, + isbn13: Number, + language_code: String, + num_pages: Number, + ratings_count: Number, + text_reviews_count: Number, +}); + +if (process.env.RESET_DB) { + const seedDatabase = async () => { + try { + await Books.deleteMany({}); + console.log("Database cleared"); + const savePromises = booksData.map(book => new Books(book).save()); + await Promise.all(savePromises); + console.log("Database seeded with initial data"); + } catch (error) { + console.error("Error seeding database:", error); + } + }; + seedDatabase(); +} + +app.use((req, res, next) => { + if (mongoose.connection.readyState === 1) { + next(); + } else { + res.status(503).json({ error: "Service unavailable" }); + } +}); + // Start defining your routes here app.get("/", (req, res) => { - res.send("Hello Technigo!"); + try { + const endpoints = expressListEndpoints(app); + res.json(endpoints); + } catch (error) { + console.error("Error", error); + res.status(500).send("This page is unavailable at the moment. Please try again later."); + } }); +// GET all books +app.get("/books", async (req, res) => { + try { + const books = await Books.find(); + res.json(books); + } catch (error) { + res.status(400).json({ error: "Invalid request" }); + } +}); + +// GET book by id +app.get("/books/:bookId", async (req, res) => { + const { bookId } = req.params; + try { + const book = await Books.findOne({ bookID: Number(bookId) }).exec(); + if (book) { + res.json(book); + } else { + res.status(404).send("No book found with the provided ID"); + } + } catch (error) { + console.error(`Error fetching book with ID ${bookId}:`, error); + res.status(400).json({ error: "Invalid book ID" }); + } +}); + +//GET book by author +app.get("/authors/:author", async(req, res) => { + const { author } = req.params; + try{ + const books = await Books.find({ authors: author }); + if (books && books.length>0 ){ + res.json(books); + } else { + res.status(404).json({message:"No books found for this author."}); + } + } catch (error) { + res.status(500).json({message:"Server error.", error: error.message}); + } +}) + // Start the server app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); -}); +}); \ No newline at end of file From c60624f0c2b87b6f03010414f391b7bd231f2a58 Mon Sep 17 00:00:00 2001 From: jingh999 Date: Thu, 16 May 2024 11:15:58 +0200 Subject: [PATCH 2/3] Add env example --- .env.example | 1 + 1 file changed, 1 insertion(+) create mode 100644 .env.example diff --git a/.env.example b/.env.example new file mode 100644 index 000000000..503c86e2d --- /dev/null +++ b/.env.example @@ -0,0 +1 @@ +RESET_DB=1 \ No newline at end of file From a73f4b8599547c0bf1e33213ba91dd9c3dd8cc44 Mon Sep 17 00:00:00 2001 From: jingh999 Date: Fri, 17 May 2024 10:29:54 +0200 Subject: [PATCH 3/3] get book by id --- server.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server.js b/server.js index 5578ed7b2..b90ba5dd7 100644 --- a/server.js +++ b/server.js @@ -19,7 +19,7 @@ app.use(cors()); app.use(express.json()); const Books = mongoose.model("Books", { - bookID: { type: Number, required: true }, + //bookID: { type: Number, required: true }, title: { type: String, required: true }, authors: { type: String, required: true }, average_rating: Number, @@ -79,7 +79,7 @@ app.get("/books", async (req, res) => { app.get("/books/:bookId", async (req, res) => { const { bookId } = req.params; try { - const book = await Books.findOne({ bookID: Number(bookId) }).exec(); + const book = await Books.findById( bookId ).exec(); if (book) { res.json(book); } else {