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

Mikas Happy Thoughts Api #512

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
70 changes: 62 additions & 8 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,74 @@ import cors from "cors";
import express from "express";
import mongoose from "mongoose";

const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/project-mongo";
mongoose.connect(mongoUrl);
mongoose.Promise = Promise;

// 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 || 9000;
const app = express();

// Add middlewares to enable cors and json body parsing
app.use(cors());
app.use(express.json());

const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/happy-thoughts";
mongoose.connect(mongoUrl);
mongoose.Promise = Promise;

const HappyThought = mongoose.model("HappyThought", {
message: {
type: String,
required: true,
minlength: 5,
maxlength: 140,
},
hearts: {
type: Number,
default: 0,
},
createdAt: {
type: Date,
default: Date.now,
},
});

app.get("/happy-thoughts", async (req, res) => {
const happyThoughts = await HappyThought.find()
.sort({ createdAt: "desc" })
.limit(20);
res.json(happyThoughts);
});

app.post("/happy-thoughts", async (req, res) => {
const { message } = req.body;
const happyThought = new HappyThought({ message });

try {
const savedThought = await happyThought.save();
res.status(201).json(savedThought);
} catch (err) {
res
.status(400)
.json({ message: "Could not save thought", error: err.errors });
}
});

app.post("/happy-thoughts/:id/like", async (req, res) => {
const { id } = req.params;
const happyThought = await HappyThought.findById(id);

if (!happyThought) {
return res.status(404).json({ message: "Thought not found" });
}

try {
happyThought.hearts += 1;
await happyThought.save();
res.status(200).json(happyThought);
} catch (err) {
res
.status(400)
.json({ message: "Could not like thought", error: err.errors });
}
});

// Start defining your routes here
app.get("/", (req, res) => {
res.send("Hello Technigo!");
Expand Down