diff --git a/instructions.md b/instructions.md index fa87eb1c..e981c396 100644 --- a/instructions.md +++ b/instructions.md @@ -31,6 +31,19 @@ We mentioned the `Thought` model and its properties a bit earlier. Each of these - Defaults to the current time - Should not be assignable when creating a new thought +//seed db +if (process.env.RESET_DB) { + const seedDatabase = async () => { + await HappyThought.deleteMany({}) + + booksData.forEach((book) => { + new HappyThought(book).save() + }) + } + + seedDatabase() +} + ### Using your API Once you've created your API, you should deploy it, and update your frontend project to use your own API instead of the old Technigo one. The idea is that if you build this API correctly, **the only thing you should need to change in the frontend code is the URL to the API,** to change it from the Technigo one to the one you deploy. diff --git a/package.json b/package.json index 1c371b45..165b09e1 100644 --- a/package.json +++ b/package.json @@ -2,6 +2,7 @@ "name": "project-happy-thoughts-api", "version": "1.0.0", "description": "Starter project to get up and running with express quickly", + "type": "module", "scripts": { "start": "babel-node server.js", "dev": "nodemon server.js --exec babel-node" @@ -12,9 +13,13 @@ "@babel/core": "^7.17.9", "@babel/node": "^7.16.8", "@babel/preset-env": "^7.16.11", + "body-parser": "^1.20.3", "cors": "^2.8.5", - "express": "^4.17.3", - "mongoose": "^8.0.0", + "dotenv": "^16.4.7", + "express": "^4.21.2", + "express-list-endpoints": "^7.1.1", + "mongodb": "^6.12.0", + "mongoose": "^8.9.1", "nodemon": "^3.0.1" } -} \ No newline at end of file +} diff --git a/server.js b/server.js index dfe86fb8..f581ba8b 100644 --- a/server.js +++ b/server.js @@ -1,9 +1,21 @@ import cors from "cors"; import express from "express"; import mongoose from "mongoose"; +import expressListEndpoints from "express-list-endpoints"; +import dotenv from "dotenv"; + + +dotenv.config(); + const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/project-mongo"; -mongoose.connect(mongoUrl); +/* mongoose.connect(mongoUrl); */ +mongoose.connect(mongoUrl) + .then(() => console.log('Connected to MongoDB')) + .catch(err => { + console.error('Failed to connect to MongoDB:', err); + process.exit(1); + }); mongoose.Promise = Promise; // Defines the port the app will run on. Defaults to 8080, but can be overridden @@ -16,11 +28,94 @@ const app = express(); app.use(cors()); app.use(express.json()); -// Start defining your routes here + +// happyThought schema/model +const HappyThoughtSchema = new mongoose.Schema({ + message: { + type: String, + required: true, + minlength: 5, + maxlength: 140 + }, + hearts: { + type: Number, + default: 0 + }, + createdAt: { + type: Date, + default: () => new Date() + } +}); + +const HappyThought = mongoose.model("HappyThought", HappyThoughtSchema); + +// all routes/endpoints app.get("/", (req, res) => { - res.send("Hello Technigo!"); + + const endpoints = expressListEndpoints(app); + res.json({ + message: "Endpoints for happy thought message:", + endpoints: endpoints + }); +}); + +// Get all happy thoughts +app.get("/happythoughts", async (req, res) => { + try { + const happyThoughts = await HappyThought.find().sort({createdAt: "desc"}).limit(20).exec(); + res.status(200).json(happyThoughts); + } catch (error) { + console.error("Error retrieving thoughts", error); + res.status(400).send("Server error"); + } }); +// Post a happy thought +app.post("/happythoughts", async (req, res) => { + try{ + const { message } = req.body; + const newHappyThought = await new HappyThought({ message }).save(); + + res.status(201).json(newHappyThought); + } catch(error) { + res.status(400).json({ + message: "Could not save thought", + errors: error.err.errors + }); + } +}); + +// Like a happy thought +app.post("/happythoughts/:id/like", async (req, res) => { + const { id } = req.params; + + try { + const updatedThought = await HappyThought.findByIdAndUpdate( + id, + { $inc: { hearts: 1 } }, + { new: true } + ); + + if (!updatedThought) { + return res.status(404).json({ + success: false, + message: "Thought not found" + }); + } + + res.status(200).json({ + success: true, + response: updatedThought + }); + } catch (error) { + res.status(400).json({ + success: false, + error: error.message + }); + } +}); + + // Start the server app.listen(port, () => { console.log(`Server running on http://localhost:${port}`);