-
Notifications
You must be signed in to change notification settings - Fork 54
Happy thoughts API #35
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
Open
marinalendt
wants to merge
19
commits into
Technigo:master
Choose a base branch
from
marinalendt: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
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
1c968cd
adding endpoints to server.js
marinalendt ec5928b
adding error handling to thoughtsId
marinalendt cfa2867
adding new endpoint, thoughts/hearts/:amount
marinalendt 7fb4dd5
adding mongoose, and changing the endpoints
marinalendt ca09348
adding middleware. errorhandling if database is down.
marinalendt bc751f1
adding post thoughts
marinalendt 884ebd4
adding .env file
marinalendt b53ae1b
adding seeding so it only renders once when emty
marinalendt f4d4444
adding comments
marinalendt 0bdae33
adding authentication logic
marinalendt 81a9c5e
adding comments + debugging to make delete and edit work
marinalendt 323c845
adding new files and folders
marinalendt 87bf7f0
restructuring files and folders
marinalendt 4d9ffaa
debugging signup
marinalendt 89ba4b0
adding authentication
marinalendt b942b8d
small fixes, adding comments etc
marinalendt b9af4eb
small fixes
marinalendt 39e39fc
removing auth_base_url, to only use BASE_URL everywhere
marinalendt a3a2f32
adding text to readme file
marinalendt 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 hidden or 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,11 +1,43 @@ | ||
| # Project API | ||
|
|
||
| This project includes the packages and babel setup for an express server, and is just meant to make things a little simpler to get up and running with. | ||
| Render: https://js-project-api-e8xy.onrender.com | ||
| Netlify: https://project-happy-thoughts-ml.netlify.app/ | ||
|
|
||
| ## Getting started | ||
| Welcome to my first backend project! A RESTful API for sharing and liking thoughts with user authentication. | ||
|
|
||
| Install dependencies with `npm install`, then start the server by running `npm run dev` | ||
| ## Features | ||
|
|
||
| ## View it live | ||
| - User Authentication** - Sign up and log in with email/password | ||
| - Create Thoughts** - Share your thoughts (5-140 characters) | ||
| - Like Thoughts** - Increase heart count on any thought | ||
| - Update Thoughts** - Edit your own thoughts | ||
| - Delete Thoughts** - Remove your own thoughts | ||
| - Password Encryption** - Bcrypt for secure password storage | ||
|
|
||
| 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. | ||
| ## Tech Stack | ||
|
|
||
| Backend: | ||
| - Node.js | ||
| - Express.js | ||
| Database: | ||
| - MongoDB with Mongoose | ||
| Authentication: | ||
| - access tokens | ||
| Security: | ||
| - Bcrypt password hashing | ||
| - CORS | ||
|
|
||
| ## API Endpoints | ||
| Authentication endpoints: | ||
| - POST /signup- Create new account | ||
| - POST /login - Log in to existing account | ||
|
|
||
| Thoughts endpoints: | ||
| - GET /thoughts - Get all thoughts | ||
| - GET /thoughts/:id - Get single thought | ||
| - POST /thoughts - Create thought (authenticated) | ||
| - PATCH /thoughts/:id - Update thought (authenticated) | ||
| - DELETE /thoughts/:id - Delete thought (authenticated) | ||
| - POST /thoughts/:id/like - Like a thought | ||
|
|
||
| # ENJOY # |
This file contains hidden or 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 |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| import { User } from "../schema/User.js"; | ||
|
|
||
| export const authenticateUser = async (req, res, next) => { | ||
| const user = await User.findOne({ | ||
| accessToken: req.header("Authorization") | ||
| }); | ||
| if (user) { | ||
| req.user = user | ||
| next(); | ||
| } else { | ||
| res.status(401).json({ | ||
| loggedOut: true | ||
| }); | ||
| } | ||
| }; |
This file contains hidden or 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 hidden or 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 |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| import express from "express"; | ||
| import { Thought } from "../schema/Thoughts.js"; | ||
| import { authenticateUser } from "../middleware/authMiddleware.js"; | ||
|
|
||
| export const router = express.Router(); | ||
|
|
||
| // Endpoint for all the thoughts. | ||
| router.get("/thoughts", async (req, res) => { | ||
| try { | ||
| const thoughts = await Thought.find() | ||
| res.json(thoughts); | ||
| } catch (error) { | ||
| res.status(500).json({ error: "Could not fetch thoughts" }) | ||
| } | ||
| }); | ||
|
|
||
| // Endpoint for the thoughts id, to get one specific thought. | ||
| router.get("/thoughts/:id", async (req, res) => { | ||
| try { | ||
| const thoughtsId = await Thought.findById(req.params.id) | ||
|
|
||
| if (!thoughtsId) { | ||
| return res.status(404).json({ error: `Thought with id ${req.params.id} does not exist` }) | ||
| } | ||
| res.json(thoughtsId) | ||
|
|
||
| } catch (error) { | ||
| return res.status(500).json({ error: `Could not fetch thoughts` }) | ||
| } | ||
| }); | ||
|
|
||
| // Adding a new message to the database | ||
| router.post("/thoughts", authenticateUser, async (req, res) => { | ||
| try { | ||
| const { message } = req.body | ||
|
|
||
| if (!message || message.trim().length === 0) { | ||
| return res.status(400).json({ error: `Message is required` }) | ||
| } | ||
|
|
||
| const newThought = await Thought.create({ message }) | ||
|
|
||
| res.status(201).json(newThought) | ||
| } catch (error) { | ||
| res.status(500).json({ error: `Could not create thought` }) | ||
| } | ||
| }); | ||
|
|
||
| // Endpoint for liking a thought, increases hearts by 1 | ||
| router.post("/thoughts/:id/like", async (req, res) => { | ||
| try { | ||
| const id = req.params.id; | ||
| const thought = await Thought.findById(id); | ||
|
|
||
| if (!thought) { | ||
| return res.status(404).json({ error: "Thought not found" }); | ||
| } | ||
| thought.hearts += 1; | ||
| await thought.save(); | ||
| res.json(thought); | ||
|
|
||
| } catch (error) { | ||
| res.status(500).json({ error: "Could not like thought" }); | ||
| } | ||
| }); | ||
|
|
||
|
|
||
| // Updates a thought - can update message and/or hearts | ||
| router.patch("/thoughts/:id", authenticateUser, async (req, res) => { | ||
| try { | ||
| const id = req.params.id | ||
| const { message, hearts } = req.body | ||
|
|
||
| const update = {} | ||
|
|
||
| if (message !== undefined) { | ||
| if (message.trim().length === 0) { | ||
| return res.status(400).json({ error: "Message can not be empty" }) | ||
| } | ||
| update.message = message | ||
| } | ||
|
|
||
| if (hearts !== undefined) { | ||
| if (isNaN(hearts)) { | ||
| return res.status(400).json({ error: "Hearts must be a number" }) | ||
| } | ||
| update.hearts = hearts | ||
| } | ||
|
|
||
| const updatedThought = await Thought.findByIdAndUpdate( | ||
| id, | ||
| update, | ||
| { new: true } | ||
| ) | ||
|
|
||
| if (!updatedThought) { | ||
| return res.status(404).json({ error: "Thought not found" }) | ||
| } | ||
|
|
||
| res.json(updatedThought) | ||
| } catch (error) { | ||
| res.status(500).json({ error: "Could not update thought" }) | ||
| } | ||
| }); | ||
|
|
||
| // Deletes a thought | ||
| router.delete("/thoughts/:id", authenticateUser, async (req, res) => { | ||
| try { | ||
| const id = req.params.id | ||
| const deletedThought = await Thought.findByIdAndDelete(id) | ||
|
|
||
| if (!deletedThought) { | ||
| return res.status(404).json({ error: `Thought with id ${id} does not exist` }) | ||
| } | ||
| res.json(deletedThought) | ||
| } catch (error) { | ||
| res.status(500).json({ error: "Could not delete thought " }) | ||
| } | ||
| }); | ||
This file contains hidden or 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 |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| import express from "express"; | ||
| import bcrypt from "bcrypt"; | ||
| import { User } from "../schema/User.js"; | ||
| import { authenticateUser } from "../middleware/authMiddleware.js"; | ||
|
|
||
| export const router = express.Router(); | ||
|
|
||
| // Creates a new user. Sign-up | ||
| router.post("/signup", async (req, res) => { | ||
| try { | ||
| const { email, password } = req.body; | ||
|
|
||
| if (!email || !password) { | ||
| return res.status(400).json({ | ||
| success: false, | ||
| message: "Email and password are required" | ||
| }); | ||
| } | ||
|
|
||
| const existingUser = await User.findOne({ email: email.toLowerCase() }) | ||
|
|
||
| if (existingUser) { | ||
| return res.status(400).json({ | ||
| success: false, | ||
| message: "Invalid email or password", | ||
| }); | ||
| } | ||
|
|
||
| const salt = bcrypt.genSaltSync(10) // 10 making it harder to hack the password. | ||
| const hashedPassword = bcrypt.hashSync(password, salt) | ||
| const user = new User({ email, password: hashedPassword }); | ||
|
|
||
| await user.save(); | ||
| res.status(201).json({ | ||
| success: true, | ||
| message: "User created", | ||
| response: { | ||
| email: user.email, | ||
| id: user._id, | ||
| accessToken: user.accessToken, | ||
| } | ||
| }); | ||
|
|
||
| } catch (error) { | ||
| res.status(400).json({ | ||
| success: false, | ||
| message: "Could not create user", | ||
| response: error, | ||
| }); | ||
| } | ||
| }); | ||
|
|
||
| // Log-in endpoint. Finds user that has created an account. | ||
| router.post("/login", async (req, res) => { | ||
| try { | ||
| const { email, password } = req.body; | ||
|
|
||
| if (!email || !password) { | ||
| return res.status(400).json({ | ||
| success: false, | ||
| message: "Email and password are required", | ||
| }); | ||
| } | ||
|
|
||
| const user = await User.findOne({ email: email.toLowerCase() }); | ||
|
|
||
| if (!user || !bcrypt.compareSync(password, user.password)) { | ||
| return res.status(401).json({ | ||
| success: false, | ||
| message: "Invalid email or password", | ||
| }) | ||
| } | ||
| res.json({ | ||
| success: true, | ||
| message: "Login successful", | ||
| response: { | ||
| email: user.email, | ||
| id: user._id, | ||
| accessToken: user.accessToken | ||
| } | ||
| }); | ||
| } catch (error) { | ||
| res.status(500).json({ | ||
| success: false, | ||
| message: "Something went wrong", | ||
| }); | ||
| } | ||
| }); | ||
|
|
||
| // ======= Protected Routes - not in use ======= | ||
| router.get("/secrets", authenticateUser, (req, res) => { | ||
| res.json({ secret: "This is a super secret message." }) | ||
| }); |
This file contains hidden or 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 |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| import { Schema, model } from "mongoose"; | ||
|
|
||
| const thoughtSchema = new Schema({ | ||
| message: { | ||
| type: String, | ||
| required: true | ||
| }, | ||
| hearts: { | ||
| type: Number, | ||
| default: 0, | ||
| }, | ||
| createdAt: { | ||
| type: Date, | ||
| default: () => new Date() | ||
| } | ||
| }) | ||
|
|
||
| export const Thought = model("thought", thoughtSchema); |
This file contains hidden or 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 |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| import { Schema, model } from "mongoose"; | ||
| import crypto from "crypto"; | ||
|
|
||
| const userSchema = new Schema({ | ||
| email: { | ||
| type: String, | ||
| unique: true, | ||
| required: true, | ||
| }, | ||
| password: { | ||
| type: String, | ||
| required: true | ||
| }, | ||
| accessToken: { | ||
| type: String, | ||
| default: () => crypto.randomBytes(128).toString("hex") | ||
| } | ||
| }); | ||
|
|
||
| export const User = model("User", userSchema); |
Oops, something went wrong.
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.
Really stable and structured code overall Marina! Good use of error handling and use of async/await and middleware where is needed!