diff --git a/README.md b/README.md index 6a75d8e1..b3fe23c3 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,41 @@ # Project Happy Thoughts API -Replace this readme with your own information about your project. +This is a backend API for the Happy Thoughts app, built using Express.js, MongoDB (via Mongoose), and CORS. -Start by briefly describing the assignment in a sentence or two. Keep it short and to the point. +The app allows users to post, retrieve, and like "thoughts" (messages), which are stored in a MongoDB database. -## The problem +## Features +Post Thoughts: Users can submit a message (between 5 to 140 characters) to create a new thought. + +Like Thoughts: Users can "like" a thought, which increases the "hearts" count for that particular thought. + +Get Thoughts: Users can retrieve the latest 20 thoughts, sorted in descending order by creation date. + +CORS Support: The API allows cross-origin requests from a specific frontend hosted on Netlify (https://post-happy-thoughts.netlify.app). + +## Technologies Used +Node.js: Backend runtime environment. + +Express.js: Web framework for building the API. + +MongoDB: NoSQL database used to store thoughts and related data. + +Mongoose: MongoDB object modeling tool. + +dotenv: For managing environment variables. + +CORS: Cross-origin resource sharing to allow specific domains to interact with the API. + +## API Endpoints + +GET /thoughts: Retrieves the 20 most recent thoughts. + +POST /thoughts: Submits a new thought with a message. + +POST /thoughts/:id/like: Likes a thought by incrementing the hearts count. -Describe how you approached to problem, and what tools and techniques you used to solve it. How did you plan? What technologies did you use? If you had more time, what would be next? ## View it live +project-happy-thoughts-api-production-5d1d.up.railway.app + -Every project should be deployed somewhere. Be sure to include the link to the deployed project so that the viewer can click around and see what it's all about. diff --git a/package.json b/package.json index 1c371b45..1193322b 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.7", "express": "^4.17.3", + "express-list-endpoints": "^7.1.1", "mongoose": "^8.0.0", "nodemon": "^3.0.1" } -} \ No newline at end of file +} diff --git a/server.js b/server.js index dfe86fb8..66a91076 100644 --- a/server.js +++ b/server.js @@ -1,27 +1,112 @@ import cors from "cors"; import express from "express"; import mongoose from "mongoose"; +import dotenv from "dotenv"; +import listEndpoints from "express-list-endpoints"; -const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/project-mongo"; -mongoose.connect(mongoUrl); -mongoose.Promise = Promise; +dotenv.config() +const mongoURI = process.env.MONGODB_URI + +mongoose.connect(mongoURI) +.then(() => { + console.log('MongoDB successfully connected!') + }) + .catch((error) => { + console.error('Error to connect with MongoDB', error) + }) + +// Setting a Schema and model +const Thought = mongoose.model("Thought", new mongoose.Schema({ + message: { + type: String, + required: true, + minlength: 5, + maxlength: 140 + }, + hearts: { + type: Number, + default: 0 + }, + likedBy: [{ + type: mongoose.Schema.Types.ObjectId, //stores preferences to user object + ref:"User" + }], + createdAt: { + type: Date, + default: () => new Date() + } +})) // 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(cors({ + origin: "https://post-happy-thoughts.netlify.app", + methods: ["GET", "POST"], // Specify allowed methods + allowedHeaders: ["*"], // Specify allowed headers, in this case all +})); + app.use(express.json()); // Start defining your routes here app.get("/", (req, res) => { - res.send("Hello Technigo!"); + const endpoints = listEndpoints(app); + res.json({ + message: "These are the endpoints of the Happy Thoughts API", + endpoints: endpoints + }) }); +app.get("/thoughts", async (req, res) => { + try { + // returning 20 thoughts in descending order + const thoughts = await Thought.find().sort({createdAt: "desc"}).limit(20).exec(); + res.json(thoughts) + }catch (error) { + console.error('Error retrieving thoughts', error); + res.status(500).send('Server error'); + } + }); + + app.post("/thoughts", async (req, res) => { + try{ + //retrieve the information sent by the client to the API endpoint + const {message} = req.body; + //use the mongoose model to create the DB entry + const newThought = new Thought({message}); + await newThought.save(); + + res.status(201).json(newThought); + } catch(error) { + res.status(400).json({message: "Could not save thought", errors: error.err.errors}) + } + }); + + // Like a thought + app.post("/thoughts/:id/like", async (req, res) => { + try { + const {id} = req.params + const thought = await Thought.findById(id) + if(!thought) { + return res.status(404).json({message: "Thought was not found"}) + } + + // Update hearts count + const newHearts = thought.hearts % 2 === 0 ? thought.hearts +1 : thought.hearts -1; + + const updatedThought = await Thought.findByIdAndUpdate(id, {hearts: newHearts}, {new: true}); + + res.status(200).json(updatedThought); + } catch (error){ + console.error("There is an errow by liking the thought", error); + res.status(500).json({message: "Could not like thought"}) + } + }) + // Start the server app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); -}); +}); \ No newline at end of file