diff --git a/package.json b/package.json index 1c371b45..04ffc163 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", + "main": "server.js", "scripts": { "start": "babel-node server.js", "dev": "nodemon server.js --exec babel-node" @@ -11,10 +12,14 @@ "dependencies": { "@babel/core": "^7.17.9", "@babel/node": "^7.16.8", - "@babel/preset-env": "^7.16.11", "cors": "^2.8.5", + "dotenv": "^16.4.7", "express": "^4.17.3", "mongoose": "^8.0.0", "nodemon": "^3.0.1" - } -} \ No newline at end of file + }, + "devDependencies": { + "@babel/preset-env": "^7.26.0" + }, + "type": "module" +} diff --git a/server.js b/server.js index dfe86fb8..a1158d2b 100644 --- a/server.js +++ b/server.js @@ -1,27 +1,117 @@ -import cors from "cors"; import express from "express"; +import cors from "cors"; import mongoose from "mongoose"; +import dotenv from "dotenv"; -const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/project-mongo"; -mongoose.connect(mongoUrl); -mongoose.Promise = Promise; +dotenv.config(); -// 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 port = process.env.PORT || 8081; const app = express(); -// Add middlewares to enable cors and json body parsing +// Middleware app.use(cors()); app.use(express.json()); -// Start defining your routes here +// Mongoose connection +const mongoUrl = process.env.MONGO_URL || "mongodb://127.0.0.1:27017/happyThoughts"; +mongoose.connect(mongoUrl, { + useNewUrlParser: true, + useUnifiedTopology: true, +}); +mongoose.Promise = Promise; + +mongoose.connection.on("connected", () => { + console.log(`Connected to MongoDB at ${mongoUrl}`); +}); + +mongoose.connection.on("error", (error) => { + console.error("Error connecting to MongoDB:", error); +}); + +// Mongoose schema and model +const thoughtSchema = new mongoose.Schema({ + message: { + type: String, + required: true, + minlength: 5, + maxlength: 140, + }, + hearts: { + type: Number, + default: 0, + }, + createdAt: { + type: Date, + default: Date.now, + }, +}); + +const Thought = mongoose.model("Thought", thoughtSchema); + +// Root endpoint app.get("/", (req, res) => { - res.send("Hello Technigo!"); + res.send("Welcome to the Happy Thoughts API!"); +}); + +// Get thoughts (max 20, sorted by createdAt descending) +app.get("/thoughts", async (req, res) => { + try { + const thoughts = await Thought.find().sort({ createdAt: -1 }).limit(20); + res.json(thoughts); + } catch (error) { + res.status(500).json({ + success: false, + message: "Could not fetch thoughts.", + error: error.message, + }); + } +}); + +// Post a new thought +app.post("/thoughts", async (req, res) => { + const { message } = req.body; + + try { + const thought = await new Thought({ message }).save(); + res.status(201).json(thought); + } catch (error) { + res.status(400).json({ + success: false, + message: "Could not create thought. Please check the input.", + error: error.message, + }); + } +}); + +// Add a like to a thought +app.post("/thoughts/:thoughtId/like", async (req, res) => { + const { thoughtId } = req.params; + + try { + const updatedThought = await Thought.findByIdAndUpdate( + thoughtId, + { $inc: { hearts: 1 } }, + { new: true } // Return the updated document + ); + + if (!updatedThought) { + return res.status(404).json({ + success: false, + message: "Thought not found.", + }); + } + + res.status(200).json(updatedThought); + } catch (error) { + res.status(400).json({ + success: false, + message: "Could not add like.", + error: error.message, + }); + } }); -// Start the server +// Start server app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); });