JustPaste.it
const express = require("express");
const path = require("path");
const app = express();
const port = 8081;
const { v4: uuidv4 } = require("uuid");

const comments = [
  { id: uuidv4(), user: "yanto", text: "Assalamualaikum" },
  { id: uuidv4(), user: "kipli", text: "Jos" },
  { id: uuidv4(), user: "fauzan", text: "oyi" },
  { id: uuidv4(), user: "anu", text: "aslole" },
  { id: uuidv4(), user: "alibaba", text: "kerja bagus" },
  { id: uuidv4(), user: "yitnoo", text: "ehehe" },
];

app.set("view engine", "ejs"); //sintaks di express untuk mengatur view engine
//mengeset agar bisa mengarah ke folder views saat merunning di parent folder LatEjs dan tidak terjadi error
// otomatis menambahkan /c/JavaScript/codepolitan/NodeJs/views
app.set("views", path.join(__dirname, "/views"));

app.use(express.json()); //untuk parsing data json
app.use(express.urlencoded({ extended: true }));

app.get("/order", (req, res) => {
  res.send("berhasil menggunakan method get");
});
app.get("/comments", (req, res) => {
  res.render("comments/index", { comments });
});
app.get("/comments/:id", (req, res) => {
  const { id } = req.params;
  console.log(id);
  const comment = comments.find((c) => c.id === id);
  console.log(comment);
  res.render("comments/show", { comment });
});
//menampilkan tampilan membuat komen
app.get("/comments/create", (req, res) => {
  res.render("comments/create");
});

app.post("/comments", (req, res) => {
  const { user, text } = req.body;
  comments.push({ user, text, id: uuidv4() });
  // const comment = req.body;
  // comments.push({ ...comment });
  //meredirect ke halaman comments awal
  res.redirect("/comments");
});
app.post("/order", (req, res) => {
  const { name, qty } = req.body;
  console.log(req.body);
  res.send(`nama ${name}-jumlah${qty}`);
});

app.listen(port, () => {
  console.log(`started on http://localhost:${port}`);
});