Node.js & RESTful API - Wiki Project


Posted by pei_______ on 2022-06-24


Express - Routing
Robo 3T


app.js - constant

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const ejs = require("ejs");

const app = express();

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(express.static("public"));

mongoose.connect("mongodb://localhost:27017/wikiDB");

const articleSchema = new mongoose.Schema({
  title: String,
  content: String
})

const Article = mongoose.model("Article", articleSchema);

Requests Targetting all Articles

////////////////////////////Requests Targetting all Articles

app.route("/articles")

  // 01. /articles [GET] - Fetches all the articles
  .get(function(req, res) {

    Article.find(

      // 1st input:  callback function
      function(err, articles) {

      if (err) {
        res.send(err);
      } else {
        res.send(articles);
      };
    });
  })

  // 02. /articles [POST] - Creates one new article
  .post(function(req, res) {

    const newArticle = new Article({
      title: req.body.title,
      content: req.body.content
    });

    newArticle.save(

      // 1st input:  callback function
      function(err) {

      if (!err) {
        res.send("Successfully added new article.");
      } else {
        res.send(err);
      }
    });
  })

  // 03. /articles [DELETE] - Deletes all the articles
  .delete(function(req, res) {

    Article.deleteMany(

      // 1st input:  callback function
      function(err) {

      if (!err) {
        res.send("Successfully delete all articles.")
      } else {
        res.send(err);
      }
    });
  });

Requests Targetting A Specific Article

/////////////////////////// Requests Targetting A Specific Article

app.route("/articles/:articleTitle")

  // 04. /articles/<title> [GET] - Fetches the articles with <title>
  .get(function(req, res) {

    Article.findOne(

      // 1st input:  condition
      {title: req.params.articleTitle},

      // 2nd input:  callback function
      function(err, foundArticles) {

      if (!foundArticles) {
        res.send("No article matched that title was found.")
      } else {
        res.send(foundArticles);
      }
    })
  })

// 05. /articles/<title> [PUT] - Rewrite entire article with <title>
  .put(function(req, res) {

      Article.replaceOne(

        // 1st input:  condition
        {title: req.params.articleTitle},

        // 2nd input:  update items, *** will delete if empty
        {title: req.body.title,
          content: req.body.content},

        // 3rd input:  callback function
        function(err) {

          if (!err) {
            console.log(req.body.title);
            console.log(req.body.content);
            res.send("Successfully updated the article.");
          } else {
            res.send(err);
          }
        }
      )
  })

// 06. /articles/<title> [PATCH] - Updates partial article with <title>
  .patch(function(req, res) {

    Article.updateOne(

      // 1st input:  condition
      {title: req.params.articleTitle},

      // 2nd input: only update field
      {$set : req.body},

      // 3rd input:  callback function
      function(err) {

        if (!err) {
          res.send("Successfully updated the article.");
        } else {
          res.send(err);
        }
      }
    )
  })

// 07. /articles/<title> [DELETE] - Deletes the article with <title>
  .delete(function(req, res){

    Article.deleteOne(

      // 1st input:  condition
      {title: req.params.articleTitle},

      // 2nd input:  callback function
      function(err) {

        if (!err) {
          res.send("Successfully delete the article.");
        } else {
          res.send(err);
        }
      }
    )
  })

app.js - constant

app.listen(3000, function() {
  console.log("Server started on port 3000");
});









Related Posts

[心得] - Final Project 實作心得

[心得] - Final Project 實作心得

[ week 1 ] 教教蔡哥學 Git

[ week 1 ] 教教蔡哥學 Git

JS30 Day 21 筆記

JS30 Day 21 筆記


Comments