Skip to content
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
13 changes: 13 additions & 0 deletions instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,19 @@ We mentioned the `Thought` model and its properties a bit earlier. Each of these
- Defaults to the current time
- Should not be assignable when creating a new thought

//seed db
if (process.env.RESET_DB) {
const seedDatabase = async () => {
await HappyThought.deleteMany({})

booksData.forEach((book) => {
new HappyThought(book).save()
})
}

seedDatabase()
}

### Using your API
Once you've created your API, you should deploy it, and update your frontend project to use your own API instead of the old Technigo one. The idea is that if you build this API correctly, **the only thing you should need to change in the frontend code is the URL to the API,** to change it from the Technigo one to the one you deploy.

Expand Down
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",
"type": "module",
"scripts": {
"start": "babel-node server.js",
"dev": "nodemon server.js --exec babel-node"
Expand All @@ -12,9 +13,13 @@
"@babel/core": "^7.17.9",
"@babel/node": "^7.16.8",
"@babel/preset-env": "^7.16.11",
"body-parser": "^1.20.3",
"cors": "^2.8.5",
"express": "^4.17.3",
"mongoose": "^8.0.0",
"dotenv": "^16.4.7",
"express": "^4.21.2",
"express-list-endpoints": "^7.1.1",
"mongodb": "^6.12.0",
"mongoose": "^8.9.1",
"nodemon": "^3.0.1"
}
}
}
101 changes: 98 additions & 3 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,21 @@
import cors from "cors";
import express from "express";
import mongoose from "mongoose";
import expressListEndpoints from "express-list-endpoints";
import dotenv from "dotenv";


dotenv.config();


const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/project-mongo";
mongoose.connect(mongoUrl);
/* mongoose.connect(mongoUrl); */
mongoose.connect(mongoUrl)
.then(() => console.log('Connected to MongoDB'))
.catch(err => {
console.error('Failed to connect to MongoDB:', err);
process.exit(1);
});
mongoose.Promise = Promise;

// Defines the port the app will run on. Defaults to 8080, but can be overridden
Expand All @@ -16,11 +28,94 @@ const app = express();
app.use(cors());
app.use(express.json());

// Start defining your routes here

// happyThought schema/model
const HappyThoughtSchema = new mongoose.Schema({
message: {
type: String,
required: true,
minlength: 5,
maxlength: 140
},
hearts: {
type: Number,
default: 0
},
createdAt: {
type: Date,
default: () => new Date()
}
});

const HappyThought = mongoose.model("HappyThought", HappyThoughtSchema);

// all routes/endpoints
app.get("/", (req, res) => {
res.send("Hello Technigo!");

const endpoints = expressListEndpoints(app);
res.json({
message: "Endpoints for happy thought message:",
endpoints: endpoints
});
});

// Get all happy thoughts
app.get("/happythoughts", async (req, res) => {
try {
const happyThoughts = await HappyThought.find().sort({createdAt: "desc"}).limit(20).exec();
res.status(200).json(happyThoughts);
} catch (error) {
console.error("Error retrieving thoughts", error);
res.status(400).send("Server error");
}
});

// Post a happy thought
app.post("/happythoughts", async (req, res) => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can use hyphens if you need your endpoint to be named with more than one word -> happy-thoughts

try{
const { message } = req.body;
const newHappyThought = await new HappyThought({ message }).save();

res.status(201).json(newHappyThought);
} catch(error) {
res.status(400).json({
message: "Could not save thought",
errors: error.err.errors
});
}
});

// Like a happy thought
app.post("/happythoughts/:id/like", async (req, res) => {
const { id } = req.params;

try {
const updatedThought = await HappyThought.findByIdAndUpdate(
id,
{ $inc: { hearts: 1 } },
{ new: true }
);
Comment on lines +93 to +97

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


if (!updatedThought) {
return res.status(404).json({
success: false,
message: "Thought not found"
});
}

res.status(200).json({
success: true,
response: updatedThought
});
} catch (error) {
res.status(400).json({
success: false,
error: error.message
});
}
});


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