프로그래밍/Web

make my own API

studylida 2024. 3. 14. 21:00

index.js

import express from "express";
import bodyParser from "body-parser";

const app = express();
const port = 4000;

// In-memory data store
let posts = [
  {
    id: 1,
    title: "The Rise of Decentralized Finance",
    content:
      "Decentralized Finance (DeFi) is an emerging and rapidly evolving field in the blockchain industry. It refers to the shift from traditional, centralized financial systems to peer-to-peer finance enabled by decentralized technologies built on Ethereum and other blockchains. With the promise of reduced dependency on the traditional banking sector, DeFi platforms offer a wide range of services, from lending and borrowing to insurance and trading.",
    author: "Alex Thompson",
    date: "2023-08-01T10:00:00Z",
  },
  {
    id: 2,
    title: "The Impact of Artificial Intelligence on Modern Businesses",
    content:
      "Artificial Intelligence (AI) is no longer a concept of the future. It's very much a part of our present, reshaping industries and enhancing the capabilities of existing systems. From automating routine tasks to offering intelligent insights, AI is proving to be a boon for businesses. With advancements in machine learning and deep learning, businesses can now address previously insurmountable problems and tap into new opportunities.",
    author: "Mia Williams",
    date: "2023-08-05T14:30:00Z",
  },
  {
    id: 3,
    title: "Sustainable Living: Tips for an Eco-Friendly Lifestyle",
    content:
      "Sustainability is more than just a buzzword; it's a way of life. As the effects of climate change become more pronounced, there's a growing realization about the need to live sustainably. From reducing waste and conserving energy to supporting eco-friendly products, there are numerous ways we can make our daily lives more environmentally friendly. This post will explore practical tips and habits that can make a significant difference.",
    author: "Samuel Green",
    date: "2023-08-10T09:15:00Z",
  },
];

let lastId = 3;

// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

//Write your code here//

//CHALLENGE 1: GET All posts
app.get("/posts", (req, res) => {
  console.log(posts);
  res.json(posts);
});

//CHALLENGE 2: GET a specific post by id

app.get("/posts/:id", (req, res) => {
  const curId = parseInt(req.params.id);
  const searchId = posts.findIndex((post) => post.id === curId);
  if(searchId > -1) {
    res.json(posts[searchId]);
  } else {
    return res.status(404).json({ message: "Post not found" });
  }
});

// /edit/:id가 아니었음..........

//CHALLENGE 3: POST a new post

app.post("/posts", (req, res) => {
  let curId = lastId+1;

  let curTitle;
  if(req.body.title) {
    curTitle = req.body.title;
  } else {
    curTitle = "TBD";
  }

  let curContent;
  if(req.body.content) {
    curContent = req.body.content;
  } else {
    curContent = "TBD";
  }

  let curAuthor;
  if(req.body.author) {
    curAuthor = req.body.author;
  } else {
    curAuthor = "TBD";
  }

  let curDate = new Date().toISOString();

  let newPost = {
    id: curId,
    title: curTitle,
    content: curContent,
    author: curAuthor,
    date: curDate,
  };

  posts.push(newPost);
  lastId++;
  res.json(newPost);

});

//CHALLENGE 4: PATCH a post when you just want to update one parameter

app.patch("/posts:id", (req, res) => {


  let curId = parseInt(req.params.id);

  let curTitle;
  if(req.body.title) {
    curTitle = req.body.title;
  }

  let curContent;
  if(req.body.content) {
    curContent = req.body.content;
  } 

  let curAuthor;
  if(req.body.author) {
    curAuthor = req.body.author;
  } 

  let curDate = req.body.date;

  const newPost = {
    id: curId,
    title: curTitle,
    content: curContent,
    author: curAuthor,
    date: curDate
  };
  const searchId = posts.findIndex((post) => post.id === curId);
  posts[searchId] = newPost;
  console.log(newPost);
  res.json(newPost);
});

//CHALLENGE 5: DELETE a specific post by providing the post id.

app.delete("/posts/:id", (req, res) => {
  const index = posts.findIndex((p) => p.id === parseInt(req.params.id));
  if (index === -1) return res.status(404).json({ message: "Post not found" });

  posts.splice(index, 1);
  res.json({ message: "Post deleted" });
})


app.listen(port, () => {
  console.log(`API is running at http://localhost:${port}`);
});

 

 

 

 

server.js

import express from "express";
import bodyParser from "body-parser";
import axios from "axios";

const app = express();
const port = 3000;
const API_URL = "http://localhost:4000";

app.use(express.static("public"));

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// Route to render the main page
app.get("/", async (req, res) => {
  try {
    const response = await axios.get(`${API_URL}/posts`);
    console.log(response);
    res.render("index.ejs", { posts: response.data });
  } catch (error) {
    res.status(500).json({ message: "Error fetching posts" });
  }
});

// Route to render the edit page
app.get("/new", (req, res) => {
  res.render("modify.ejs", { heading: "New Post", submit: "Create Post" });
});

app.get("/edit/:id", async (req, res) => {
  try {
    const response = await axios.get(`${API_URL}/posts/${req.params.id}`);
    console.log(response.data);
    res.render("modify.ejs", {
      heading: "Edit Post",
      submit: "Update Post",
      post: response.data,
    });
  } catch (error) {
    res.status(500).json({ message: "Error fetching post" });
  }
});

// Create a new post
app.post("/api/posts", async (req, res) => {
  try {
    const response = await axios.post(`${API_URL}/posts`, req.body);
    console.log(response.data);
    res.redirect("/");
  } catch (error) {
    res.status(500).json({ message: "Error creating post" });
  }
});

// Partially update a post
app.post("/api/posts/:id", async (req, res) => {
  console.log("called");
  try {
    const response = await axios.patch(
      `${API_URL}/posts/${req.params.id}`,
      req.body
    );
    console.log(response.data);
    res.redirect("/");
  } catch (error) {
    res.status(500).json({ message: "Error updating post" });
  }
});

// Delete a post
app.get("/api/posts/delete/:id", async (req, res) => {
  try {
    await axios.delete(`${API_URL}/posts/${req.params.id}`);
    res.redirect("/");
  } catch (error) {
    res.status(500).json({ message: "Error deleting post" });
  }
});

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

 

 

index.ejs

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Blog</title>
  <link rel="stylesheet" href="/styles/main.css">
  <!-- <script src="https://unpkg.com/axios/dist/axios.min.js"></script> -->
</head>

<body>
  <div class="container">
    <h1>My Blog</h1>
    <a id="newPostBtn" href="/new">New Post</a>
    <ul id="postsList">
      <% posts.forEach(post=> { %>
        <li>
          <h2>
            <%=post.title%>
          </h2>
          <small>
            <%=post.date %>
          </small>
          <p>
            <%=post.content%>
          </p>
          <small>By: <%=post.author%> </small>
          <a class="edit" href="/edit/<%= post.id %>">Edit</a>
          <a class="delete" href="/api/posts/delete/<%= post.id %>">Delete</a>
        </li>
        <% }); %>
    </ul>
  </div>

</body>

</html>

modify.ejs

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Edit Blog</title>
  <link rel="stylesheet" href="/styles/main.css">
</head>

<body>
  <div class="container">
    <h1>
      <%= heading %>
    </h1>

    <% if (locals.post) { %>
      <form id="editForm" method="post" action="/api/posts/<%=post.id%>">
        <input type="text" name="title" value="<%=post.title %>">
        <textarea name="content" rows="10"><%=post.content %></textarea>
        <input type="text" name="author" value="<%=post.author %>">
        <button class="full-width" type="submit">
          <%= submit %>
        </button>
      </form>
      <% } else {%>
        <form id="newPostForm" method="post" action="/api/posts">
          <input type="text" name="title" placeholder="Title" required>
          <textarea name="content" placeholder="Content" required rows="10"></textarea>
          <input type="text" name="author" placeholder="Author" required>
          <button class="full-width" type="submit">
            <%= submit %>
          </button>
        </form>
        <% } %>

  </div>
</body>

</html>

'프로그래밍 > Web' 카테고리의 다른 글

travel tracker 20240326  (2) 2024.03.26
travel tracker 20240325  (0) 2024.03.26
DIY API  (0) 2024.03.14
axios 예제  (0) 2024.03.13
What is Javascript?  (0) 2023.05.25