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

Jonas Happy thoughts api #510

Open
wants to merge 4 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
11 changes: 8 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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"
}
}
},
"devDependencies": {
"@babel/preset-env": "^7.26.0"
},
"type": "module"
}
114 changes: 102 additions & 12 deletions server.js
Original file line number Diff line number Diff line change
@@ -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}`);
});