BE_Simple API Server_Assignment#4_10.28

송철진·2022년 10월 27일
1

Assignment#4

  • Assignment3에서 만들었던 app.js 파일에 이어서 과제를 진행해주세요.

  • app.js 파일에 게시글 정보 수정 엔드포인트 구현 코드를 작성해주세요.

    • 알맞은 API 호출 URL을 설정하여서 클라이언트와(httpie/postman) 통신을 성공해주세요. 업데이트하는 요청을 보낼때는 http method 중에 PATCH를 사용합니다.

      $ http -v PATCH 127.0.0.1:8000
    • posts 배열에 있는 post 객체의 데이터를 수정하고, 데이터가 수정 될 때의 알맞는 http 상태코드를 반환해주세요.

    • postingId가 1번인 게시물의 내용을 “노드”로 수정한다면, http response로 반환하는 데이터의 형태가 다음과 같은 구조를 갖도록 만들어주세요.

      {
      	"data" : {
      	    "userId"         : 1,
      	    "userName"       : "Rebekah Johnson",
              "postingId"      : 1,
              "postingTitle"   : "간단한 HTTP API 개발 시작!",
      		"postingContent" : "노드"
      	}
      }

1. 전체 소스코드

const http = require("http");
const server = http.createServer();
const users = [
    {
      id: 1,
      name: "Rebekah Johnson",
      email: "Glover12345@gmail.com",
      password: "123qwe",
    },
    {
      id: 2,
      name: "Fabian Predovic",
      email: "Connell29@gmail.com",
      password: "password",
    },
];
  
const posts = [
    {
      id: 1,
      title: "간단한 HTTP API 개발 시작!",
      content: "Node.js에 내장되어 있는 http 모듈을 사용해서 HTTP server를 구현.",
      userId: 1,
    },
    {
      id: 2,
      title: "HTTP의 특성",
      content: "Request/Response와 Stateless!!",
      userId: 1,
    },
];

const data = function(){
    let dataArray = [];
    for(let i = 0; i<posts.length; i++){
        for(let j = 0; j<users.length; j++){
            if (users[j].id === posts[i].userId){
                let userPost = {
                    "userID"           : users[j].id,
                    "userName"         : users[j].name,
                    "postingId"        : posts[i].id,
                    "postingTitle"     : posts[i].title,
                    "postingContent"   : posts[i].content 
                }
                dataArray.push(userPost);
            }
        }
    }
    return dataArray;
}

const httpRequestListener =  function(request, response){
    const { url, method } = request;
    if (method === 'GET'){
        if (url === '/ping'){
            response.writeHead(200, {'Content-Type' : 'appliction/json'});
            response.end(JSON.stringify({message : 'pong'}));
        }else if (url === '/posts/inquire'){
            response.writeHead(200, {'Content-Type' : 'appliction/json'});
            response.end(JSON.stringify({ "data" : data() }));
        }
    }else if(method === "POST"){
        //response.writeHead(200, {'Content-Type':'appliction/json'})
        // url이 /users/signup 이면 회원가입을 실행:
        if (url === "/users/signup") {
            let body = "";

            //콜백함수: 데이터를 모아서 하나의 스트링으로
            request.on("data", (data) => { 
                body += data;
            });

            //콜백함수: 
            request.on("end", ()=>{
                // 하나의 스트링으로 만든 body를 파싱해서 user에 할당
                const user = JSON.parse(body);

                // 전역변수 users에 입력받은 객체를 추가
                users.push({
                    id: user.id,
                    name: user.name,
                    email: user.email,
                    password: user.password,
                });

                // 데이터타입은 json으로 
                response.writeHead(200, {'Content-Type':'appliction/json'});

                // json으로 작성된 stringify(...)의 ...을 응답'body'에 표시
                response.end(JSON.stringify({
                    message : "userCreated",
                    "users" : users
                }));
            });
        // url이 /posts/signup 이면 게시글 입력을 실행:
        }else if(url === "/posts/signup"){
            let body = "";

            //콜백함수: 데이터를 모아서 하나의 스트링으로
            request.on("data", (data) => { 
                body += data;
            });

            //콜백함수: 요청의 body(end)에 대해 실행하겠다?
            request.on("end", ()=>{
                // 스트링 body를 JSON형태로 파싱해서 post에 할당
                const post = JSON.parse(body);

                 // 전역변수 posts에 입력받은 객체를 추가
                posts.push({
                    id: post.id,
                    title: post.title,
                    content: post.content,
                    userId: post.userId,
                });
                // 데이터타입은 json으로 
                response.writeHead(200, {'Content-Type':'appliction/json'});

                // json으로 작성된 stringify()의 객체 내용을 응답'body'에 표시
                response.end(JSON.stringify({
                    message : "postCreated",
                    "posts" : posts }));
            });
        }
    }else if(method === "PATCH"){
        if(url === '/posts/change'){
            let body = "";
            
            //콜백함수: 터미널에 입력된 데이터를 모아서 하나의 스트링으로
            request.on("data", (data) => { 
                body += data;
            });
            
            //콜백함수: 
            request.on("end", ()=>{
                // 스트링 body를 JSON형태로 파싱해서 post에 할당
                const post = JSON.parse(body);

                 // 전역변수 posts에 입력받은 객체를 수정
                 // post에 id값이 없거나 id
                for(let i in posts){
                    /*if
                    
                    (!post.id || (!posts[i].id.includes(post.id)&& i===posts.length-1)){
                        console.log("등록되지 않은 게시물 id입니다!");
                    }else
                    {*/
                        if (posts[i].id === post.id){
                             posts[i].content = post.content;
                        } 
                    /*}*/
                }
                
                response.writeHead(200, {'Content-Type' : 'appliction/json'});
                //response.end(JSON.stringify({ "posts": posts }));
                response.end(JSON.stringify({ "data" : data() }));
            });
        }
    
    }
}
server.on("request", httpRequestListener);

const IP = '127.0.0.1';
const PORT = 8000;

server.listen(PORT, IP, function(){
    console.log(`Listening to request on ip ${IP} & port ${PORT}`);
})

1-1. 추가된 소스코드

if(method === "PATCH"){
    if(url === '/posts/change'){
        let body = "";
        
        request.on("data", (data) => { 
            body += data;
        });
         
        request.on("end", ()=>{
            // 스트링 body를 JSON형태로 파싱해서 post에 할당
            const post = JSON.parse(body);
 
             /* 여기에 '변수post에 id값이 없거나 
             기존에 일치하지 않는 id값에 대해 수정을 요청했을 때'
             에 대한 조건문을 넣어주면 좋겠음! */
          
			// id가 일치하면 content 내용을 바꾼다          
            for(let i in posts){
                if (posts[i].id === post.id){
                    posts[i].content = post.content;
                } 
            }
            response.writeHead(200, {'Content-Type' : 'appliction/json'});
            //response.end(JSON.stringify({ "posts": posts }));
            response.end(JSON.stringify({ "data" : data() }));
            });
        }
    }

2. 리스닝

3. 실행 결과

3-1. users 회원 가입하기

3-2. posts 게시물 등록하기

3-3. data 게시물 조회하기

3-4. data 게시물 수정하기

profile
검색하고 기록하며 학습하는 백엔드 개발자

0개의 댓글