-
Notifications
You must be signed in to change notification settings - Fork 515
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
project-18-mongo-api #516
Open
erikamolsson
wants to merge
12
commits into
Technigo:master
Choose a base branch
from
erikamolsson:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
project-18-mongo-api #516
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
d4bdd4b
update: routes for all books, number of pages, author and id
2868a2b
update: readme
e2332ff
mongodb install
a2999eb
update: .env-file
a398bf5
data not found when deployed
33e59ed
Update: trying out ways to make the api work
6e55a2c
new try for data
89e2bea
endpoints
c494fa5
data from books
4b8263b
.env file update
75d3321
started docker desktop
34cfcfc
link to deploy
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,5 @@ | ||
## Netlify link | ||
Add your Netlify link here. | ||
PS. Don't forget to add it in your readme as well. | ||
Render link: https://project-18-mongo-api.onrender.com/ (not working yet..) | ||
|
||
## Collaborators | ||
Add any collaborators here. | ||
- |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,16 +1,14 @@ | ||
import express from "express"; | ||
import cors from "cors"; | ||
import mongoose from "mongoose"; | ||
import dotenv from "dotenv"; | ||
import expressListEndpoints from "express-list-endpoints"; | ||
import booksData from "./data/books.json" | ||
|
||
// 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"; | ||
|
||
const mongoUrl = process.env.MONGO_URL || "https://project-18-mongo-api.onrender.com/ "; | ||
mongoose.connect(mongoUrl); | ||
mongoose.Promise = Promise; | ||
|
||
|
@@ -24,11 +22,146 @@ const app = express(); | |
app.use(cors()); | ||
app.use(express.json()); | ||
|
||
// Start defining your routes here | ||
|
||
//Check if mongo is connected | ||
mongoose.connect(mongoUrl) | ||
.then(() => console.log("Connected to MongoDB")) | ||
.catch(err => console.error("Failed to connect to MongoDB:", err)); | ||
|
||
|
||
const Book = mongoose.model('Book', { | ||
"bookID": Number, | ||
"title": String, | ||
"authors": String, | ||
"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 () => { | ||
await Book.deleteMany({}) | ||
|
||
booksData.forEach((book) => { | ||
new Book(book).save() | ||
}) | ||
} | ||
|
||
seedDatabase() | ||
} | ||
|
||
|
||
|
||
// Home page - first route | ||
app.get("/", (req, res) => { | ||
res.send("Hello Technigo!"); | ||
res.send("Welcome to the website where you can find your favourite book!"); | ||
|
||
const endpoints = expressListEndpoints(app); | ||
response.json({ | ||
message: "Welcome to the Elves API! Here are the available endpoints:", | ||
description: { | ||
"/books": "all books", | ||
"/books/pages": "by number of pages", | ||
"/books/:bookID": "by ID", | ||
"/test": "Test endpoint", | ||
}, | ||
endpoints: endpoints | ||
}); | ||
}); | ||
|
||
// Route with all the books - full API | ||
app.get("/books", async (req, res) => { | ||
try { | ||
const books = await Book.find(); | ||
res.json(books); | ||
} catch (error) { | ||
res.status(500).json({ error: "An error occurred while fetching books" }); | ||
} | ||
}); | ||
|
||
|
||
// Ge books based on number of pages (needs to be befor bookID otherwise that route will override this) | ||
app.get("/books/pages", async (req, res) => { | ||
const { min, max } = req.query; | ||
|
||
// Parse min and max values or assign default values | ||
const minPages = parseInt(min, 10) || 0; // Default: 0 pages | ||
const maxPages = parseInt(max, 10) || Number.MAX_SAFE_INTEGER; // Default: No upper limit | ||
|
||
console.log(`Filtering books with num_pages between ${minPages} and ${maxPages}`); | ||
|
||
try { | ||
// Query to find books within the range | ||
const numberOfPages = await Book.find({ | ||
num_pages: { $gte: minPages, $lte: maxPages }, | ||
}); | ||
|
||
// Return books if found, otherwise send 404 | ||
if (numberOfPages.length > 0) { | ||
res.json(numberOfPages); | ||
} else { | ||
res.status(404).json({ | ||
error: `No books found with page count between ${minPages} and ${maxPages}`, | ||
}); | ||
} | ||
} catch (error) { | ||
// Handle any server-side errors | ||
res.status(500).json({ error: "An error occurred while fetching books" }); | ||
} | ||
}); | ||
|
||
|
||
// Get individual books from id | ||
app.get("/books/:bookID", async (req, res) => { | ||
const bookID = parseInt(req.params.bookID); | ||
|
||
try { | ||
const book = await Book.findOne({ bookID: bookID }); | ||
|
||
if (book) { | ||
res.json(book); // return the specifik book | ||
} else { | ||
res.status(404).json({ error: "Book not found" }); // error page if book not founf | ||
} | ||
} catch (error) { | ||
res.status(500).json({ error: "An error occurred while fetching the book" }); // 500 page when wrong | ||
} | ||
}); | ||
|
||
|
||
// Get book-books by author | ||
app.get("/books/authors/:author", async (req, res) => { | ||
const author = req.params.author; | ||
|
||
try { | ||
// $regex = to match name and not case sensitive | ||
const booksByAuthor = await Book.find({ | ||
authors: { $regex: author, $options: "i" }, // "i" case-insensitive | ||
}); | ||
|
||
if (booksByAuthor.length > 0) { | ||
res.json(booksByAuthor); // Returnera böckerna om de finns | ||
} else { | ||
res.status(404).json({ error: "No books found for this author" }); | ||
} | ||
} catch (error) { | ||
res.status(500).json({ error: "An error occurred while fetching books" }); | ||
} | ||
}); | ||
Comment on lines
+139
to
+156
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. And this should also be a query under your /books endpoint to make it more RESTful. Even though you're filtering on author, you still return books |
||
|
||
// test | ||
app.get("/test", (req, res) => { | ||
response.send("Yesbox!"); | ||
console.log("Yesbox!"); | ||
}); | ||
|
||
|
||
// Start the server | ||
app.listen(port, () => { | ||
console.log(`Server running on http://localhost:${port}`); | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This could be named just /books, because that's what this endpoint is returning