generated from Technigo/express-api-starter
-
Notifications
You must be signed in to change notification settings - Fork 31
Week 18 - API, Oscar Liljefors #24
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
osckli990
wants to merge
15
commits into
Technigo:master
Choose a base branch
from
osckli990: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
15 commits
Select commit
Hold shift + click to select a range
68bbe0c
start
osckli990 1c357e0
core api
osckli990 b20ea7d
working api
osckli990 fd37389
mongoose started code
osckli990 45ca1ed
added get, post, patch, and delete routes
osckli990 b143e80
fix
osckli990 25ac40b
being able to like a thought?
osckli990 2f1a16f
fixes and login options
osckli990 3614bbe
Finalizing
osckli990 84a446b
redeploy
osckli990 0c433cc
major fixes
osckli990 9d56b8f
review
osckli990 952f738
changes
osckli990 8b8d3d8
hat
osckli990 cade57e
being able to post thoughts anon
osckli990 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
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 |
|---|---|---|
| @@ -1,22 +1,234 @@ | ||
| import cors from "cors" | ||
| import express from "express" | ||
| import express from "express"; | ||
| import listEndpoints from "express-list-endpoints"; | ||
| import cors from "cors"; | ||
| import mongoose from "mongoose"; | ||
| import crypto from "crypto"; | ||
| import bcrypt from "bcrypt"; | ||
|
|
||
| // 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() | ||
| // Setup | ||
| const port = process.env.PORT || 8080; | ||
| const app = express(); | ||
| const mongoURL = process.env.mongoURL || "mongodb://127.0.0.1/happy-thoughts"; | ||
| mongoose.connect(mongoURL); | ||
| mongoose.Promise = Promise; | ||
|
|
||
| // Add middlewares to enable cors and json body parsing | ||
| app.use(cors()) | ||
| app.use(express.json()) | ||
| app.use(cors()); | ||
| app.use(express.json()); | ||
|
|
||
| // Start defining your routes here | ||
| // Schemas | ||
| const UserSchema = new mongoose.Schema({ | ||
| email: { | ||
| type: String, | ||
| required: [true, "Email is required"], | ||
| unique: true, | ||
| match: [/.+@.+\..+/, "Invalid email format"], | ||
| }, | ||
| password: { | ||
| type: String, | ||
| required: true, | ||
| minlength: 6, | ||
| }, | ||
| accessToken: { | ||
| type: String, | ||
| default: () => crypto.randomBytes(128).toString("hex"), | ||
| }, | ||
| }); | ||
|
|
||
| const ThoughtSchema = new mongoose.Schema({ | ||
| message: { | ||
| type: String, | ||
| required: [true, "Message is required"], | ||
| minlength: 5, | ||
| maxlength: 140, | ||
| }, | ||
| hearts: { | ||
| type: Number, | ||
| default: 0, | ||
| }, | ||
| createdAt: { | ||
| type: Date, | ||
| default: Date.now, | ||
| }, | ||
| createdBy: { | ||
| type: mongoose.Schema.Types.ObjectId, | ||
| ref: "User", | ||
| default: null, | ||
|
Comment on lines
+52
to
+55
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ⭐ |
||
| }, | ||
| }); | ||
|
|
||
| const User = mongoose.model("User", UserSchema); | ||
| const Thought = mongoose.model("Thought", ThoughtSchema); | ||
|
|
||
| // Auth middleware | ||
| const authenticateUser = async (req, res, next) => { | ||
| const accessToken = req.header("Authorization"); | ||
| try { | ||
| const user = await User.findOne({ accessToken }); | ||
| if (user) { | ||
| req.user = user; | ||
| next(); | ||
| } else { | ||
| res.status(401).json({ error: "Please log in to access this resource" }); | ||
| } | ||
| } catch { | ||
| res.status(401).json({ error: "Invalid request" }); | ||
| } | ||
| }; | ||
|
|
||
| // Routes | ||
| app.get("/", (req, res) => { | ||
| res.send("Hello Technigo!") | ||
| }) | ||
| res.json({ | ||
| message: "Welcome to Oscar's Thoughts API!", | ||
| endpoints: listEndpoints(app), | ||
| }); | ||
| }); | ||
|
|
||
| app.get("/thoughts", async (req, res) => { | ||
| const { page = 1, limit = 5 } = req.query; | ||
| try { | ||
| const totalThoughts = await Thought.countDocuments(); | ||
| const thoughts = await Thought.find() | ||
| .sort({ createdAt: -1 }) | ||
| .skip((page - 1) * limit) | ||
| .limit(Number(limit)); | ||
| res.json({ | ||
| page: Number(page), | ||
| totalThoughts, | ||
| totalPages: Math.ceil(totalThoughts / limit), | ||
| results: thoughts, | ||
| }); | ||
| } catch { | ||
| res.status(500).json({ error: "Could not fetch thoughts" }); | ||
| } | ||
| }); | ||
|
|
||
| app.get("/thoughts/:id", async (req, res) => { | ||
| try { | ||
| const thought = await Thought.findById(req.params.id); | ||
| if (!thought) return res.status(404).json({ error: "Thought not found" }); | ||
| res.json(thought); | ||
| } catch { | ||
| res.status(400).json({ error: "Invalid ID" }); | ||
| } | ||
| }); | ||
|
|
||
| app.post("/thoughts", async (req, res) => { | ||
| const { message } = req.body; | ||
| const accessToken = req.header("Authorization"); | ||
|
|
||
| try { | ||
| let createdBy = null; | ||
| if (accessToken) { | ||
| const user = await User.findOne({ accessToken }); | ||
| if (user) { | ||
| createdBy = user._id; | ||
| } | ||
| } | ||
|
|
||
| const newThought = new Thought({ message, createdBy }); | ||
| const savedThought = await newThought.save(); | ||
| res.status(201).json(savedThought); | ||
| } catch (err) { | ||
| res.status(400).json({ error: err.message }); | ||
| } | ||
| }); | ||
|
|
||
| app.post("/thoughts/:id/like", async (req, res) => { | ||
| try { | ||
| const updated = await Thought.findByIdAndUpdate( | ||
| req.params.id, | ||
| { $inc: { hearts: 1 } }, | ||
| { new: true } | ||
| ); | ||
| if (!updated) return res.status(404).json({ error: "Thought not found" }); | ||
| res.status(200).json(updated); | ||
| } catch { | ||
| res.status(400).json({ error: "Invalid ID" }); | ||
| } | ||
| }); | ||
|
|
||
| app.patch("/thoughts/:id", authenticateUser, async (req, res) => { | ||
| try { | ||
| const thought = await Thought.findById(req.params.id); | ||
| if (!thought) return res.status(404).json({ error: "Thought not found" }); | ||
| if ( | ||
| !thought.createdBy || | ||
| thought.createdBy.toString() !== req.user._id.toString() | ||
| ) { | ||
| return res | ||
| .status(403) | ||
| .json({ error: "Not allowed to edit this thought" }); | ||
| } | ||
| thought.message = req.body.message; | ||
| await thought.save(); | ||
| res.json(thought); | ||
| } catch (err) { | ||
| res.status(400).json({ error: err.message }); | ||
| } | ||
| }); | ||
|
|
||
| app.delete("/thoughts/:id", authenticateUser, async (req, res) => { | ||
| try { | ||
| const thought = await Thought.findById(req.params.id); | ||
| if (!thought) return res.status(404).json({ error: "Thought not found" }); | ||
| if ( | ||
| !thought.createdBy || | ||
| thought.createdBy.toString() !== req.user._id.toString() | ||
| ) { | ||
| return res | ||
| .status(403) | ||
| .json({ error: "Not allowed to delete this thought" }); | ||
| } | ||
| await thought.deleteOne(); | ||
| res.status(204).end(); | ||
| } catch { | ||
| res.status(400).json({ error: "Invalid ID" }); | ||
| } | ||
| }); | ||
|
|
||
| app.post("/register", async (req, res) => { | ||
| const { email, password } = req.body; | ||
| try { | ||
| if (!email || !password) | ||
| return res.status(400).json({ error: "All fields are required" }); | ||
|
|
||
| const existing = await User.findOne({ email }); | ||
| if (existing) | ||
| return res | ||
| .status(400) | ||
| .json({ error: "That email address already exists" }); | ||
|
|
||
| const hashed = bcrypt.hashSync(password, bcrypt.genSaltSync()); | ||
| const newUser = await new User({ email, password: hashed }).save(); | ||
|
|
||
| res.status(201).json({ | ||
| email: newUser.email, | ||
| id: newUser._id, | ||
| accessToken: newUser.accessToken, | ||
| }); | ||
| } catch (err) { | ||
| res.status(400).json({ error: err.message }); | ||
| } | ||
| }); | ||
|
|
||
| app.post("/login", async (req, res) => { | ||
| const { email, password } = req.body; | ||
| try { | ||
| const user = await User.findOne({ email }); | ||
| if (!user || !bcrypt.compareSync(password, user.password)) { | ||
| return res.status(401).json({ error: "Invalid email or password" }); | ||
| } | ||
| res.status(200).json({ | ||
| email: user.email, | ||
| id: user._id, | ||
| accessToken: user.accessToken, | ||
| }); | ||
| } catch { | ||
| res.status(400).json({ error: "Something went wrong" }); | ||
| } | ||
| }); | ||
|
|
||
| // Start the server | ||
| // Server startup | ||
| app.listen(port, () => { | ||
| console.log(`Server running on http://localhost:${port}`) | ||
| }) | ||
| console.log(`Server running on http://localhost:${port}`); | ||
| }); | ||
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,23 @@ | ||
| [ | ||
| { | ||
| "id": 1, | ||
| "text": "I love coding!", | ||
| "category": "Project thoughts", | ||
| "hearts": 12, | ||
| "createdAt": "2025-07-20T12:00:00Z" | ||
| }, | ||
| { | ||
| "id": 2, | ||
| "text": "Tacos for lunch today?", | ||
| "category": "Food thoughts", | ||
| "hearts": 5, | ||
| "createdAt": "2025-07-19T15:30:00Z" | ||
| }, | ||
| { | ||
| "id": 3, | ||
| "text": "Remember to water the plants.", | ||
| "category": "Home thoughts", | ||
| "hearts": 3, | ||
| "createdAt": "2025-07-18T08:15:00Z" | ||
| } | ||
| ] |
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.
⭐