const express = require("express");
const bodyParser = require("body-parser");
// Requiring mongoose for interacting with mongoDB database
const mongoose = require("mongoose");
const app = express();
// For processing application/json
app.use(bodyParser.json());
// Setting up CORS
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "POST,PUT");
res.setHeader("Access-Control-Allow-Headers", "*");
next();
});
//---- mongo collection setup ----
// schema of our post model
const postSchema = new mongoose.Schema(
{
title: {
type: String,
required: true,
},
content: {
type: String,
required: true,
},
},
{ timestamps: true }
);
// model
const Post = mongoose.model("Post", postSchema);
//for testing purpose - can ignore it
app.get("/test", (req, res, next) => {
res.send("<h1>working</h1>");
});
//-----apis----------
// POST http://localhost:8000/post
app.post("/post", (req, res, next) => {
const newPost = new Post({
title: req.body.title,
content: req.body.content,
});
newPost
.save()
.then((post) => {
return res.status(201).json({ post: post });
})
.catch((err) => {
res.status(500).json({ error: err });
});
});
// GET http://localhost:8000/posts
app.get("/posts", (req, res, next) => {
const requestCount = req.query.count;
Post.find()
.countDocuments()
.then((count) => {
// if requested count is more than actual
// count of posts in database
if (requestCount > count) {
const error = new Error("invalid request in quantity");
error.statusCode = 400;
throw error;
}
// returning posts while limiting the count
return Post.find().limit(Number(requestCount));
})
.then((posts) => {
res.status(200).json({ posts: posts });
})
.catch((err) => {
const status = err.statusCode || 500;
res.status(status).json({ error: err });
});
});
// connecting to database and serving up server
mongoose
.connect("mongodb://localhost:27017/articleDB")
.then(app.listen(8000, () => console.log("listening at port 8000")));