Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Booksdata-mongo-api #500

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
RESET_DB=1
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
}
101 changes: 89 additions & 12 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,35 +1,112 @@
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();

// Add middlewares to enable cors and json body parsing
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}`);
});
});