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

Project-Happy-Thoughts-API #491

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
14 changes: 9 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
# Project Happy Thoughts API

Replace this readme with your own information about your project.

Start by briefly describing the assignment in a sentence or two. Keep it short and to the point.
This week it was time to build my own API using Express.js, Mongoose and MongoDB, and then connect it with one of my previous front end projects - Happy Thoughts, which make this my first fullstack project.

## The problem

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?
I started with models and created it in a new folder to keep the server.js more organized and modular. Then I created different endpoints to GET and POST the data.

If I had more time I would like to keep building to make it even better.

## View it live

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.
Render:
https://project-happy-thoughts-api-j0eg.onrender.com

Netlify:
https://project-happy-thoughts-by-lovisa.netlify.app/
27 changes: 27 additions & 0 deletions models/Thoughts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import mongoose from "mongoose"

//Schema - the blueprint
const { Schema, model } = mongoose

const thoughtsSchema = new Schema({
message: {
type: String,
required: true,
minlength: 5,
maxlength: 140
},
hearts: {
type: Number,
default: 0
},
createdAt: {
type: Date,
default: Date.now
}
})

//Model
const Thought = model("Thought", thoughtsSchema)


export default Thought
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,11 @@
"@babel/node": "^7.16.8",
"@babel/preset-env": "^7.16.11",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.17.3",
"express-list-endpoints": "^7.1.0",
"mongodb": "^6.6.1",
"mongoose": "^8.0.0",
"nodemon": "^3.0.1"
}
}
}
7 changes: 0 additions & 7 deletions pull_request_template.md

This file was deleted.

113 changes: 94 additions & 19 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,102 @@
import cors from "cors";
import express from "express";
import mongoose from "mongoose";
import cors from "cors"
import express from "express"
import mongoose from "mongoose"
import dotenv from "dotenv"
import Thought from "./models/Thoughts"
import expressListEndpoints from "express-list-endpoints"

const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/project-mongo";
mongoose.connect(mongoUrl);
mongoose.Promise = Promise;
//.env
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 app = express();
const mongoUrl =
process.env.MONGO_URL || "mongodb://localhost/project-happy-thoughts"
mongoose.connect(mongoUrl)
mongoose.Promise = Promise

// Add middlewares to enable cors and json body parsing
app.use(cors());
app.use(express.json());
//The port the app will run on
const port = process.env.PORT || 8080
const app = express()

// Start defining your routes here
// Middlewares to enable cors and json body parsing
app.use(cors())
app.use(express.json())

// Route handler
app.get("/", (req, res) => {
res.send("Hello Technigo!");
});
const endpoints = expressListEndpoints(app)
res.json(endpoints)
})

//Get thoughts, descending by created and limit to 20 thoughts
app.get("/thoughts", async (req, res) => {
const thoughts = await Thought.find()
.sort({ createdAt: "desc" })
.limit(20)
.exec()

try {
res.status(201).json({
sucess: true,
response: thoughts,
message: "Happy thoughts retrieved",
})
} catch (error) {
res.status(400).json({
sucess: false,
response: error,
message: "Could not retrieve any Happy thoughts",
})
}
})

//Post a thought endpoint
app.post("/thoughts", async (req, res) => {
const { message } = req.body //Retrieve the information sent by user to our API endpoint

//Use the mongoose model to create the database entry
const thought = new Thought({ message })

try {
const newThought = await thought.save()
res.status(201).json({
sucess: true,
response: newThought,
message: "Thought posted",
})
} catch (error) {
res.status(400).json({
sucess: false,
response: error,
message: "Could not post thought",
})
}
})

//Post request to like a Happy thought
app.post("/thoughts/:thoughtId/like", async (req, res) => {
const { thoughtId } = req.params

try {
const likeThought = await Thought.findByIdAndUpdate(
thoughtId,
{ $inc: { hearts: 1 } },
{ new: true, runValidators: true }
)
res.status(200).json({
sucess: true,
response: likeThought,
message: "Happy thought was successfully liked",
})
} catch (error) {
res.status(400).json({
sucess: false,
response: error,
message: "Could not like Happy thought",
})
}
})

// Start the server
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
console.log(`Server running on http://localhost:${port}`)
})