본문 바로가기
Back-End/App

[ NodeJS - APP ] 기능 Refactoring

by 2CHAE._.EUN 2021. 8. 12.

* 해당 포스터는 생활코딩 강의를 정리한 내용입니다.


[ template 기능 정리 정돈하기 ]

 

객체 : 서로 연관된 데이터와 그 데이터를 처리하는 방법인 함수를 그룹핑하여 코드의 복잡성을 낮추는 수납 상자

 

refactoring : 동작 방법은 똑같이 유지하면서 내부의 코드를 더 효율적으로 바꾸는 행위

 

var template = {
  HTML: function(title,list,body, control){
    return `
    <!doctype html>
    <html>
    <head>
    <title>WEB1 - ${title}</title>
    <meta charset="utf-8">
    </head>
    <body>
    <h1><a href="/">WEB</a></h1>
    ${list}
    ${control}

    ${body}
    </body>
    </html>
    `
  },

  list: function(filelist){
    var list = '<ul>';
    var i = 0;
    while( i < filelist.length ){
      list = list + `<li><a href="/?id=${filelist[i]}">${filelist[i]}</a></li>`
      i += 1
    }
    list = list + '</ul>';
    return list;
  }
}

 

객체 사용 방법 : 

 

 var list = template.list(filelist);
 var html = template.HTML(title,list,

                `<h2>${title}</h2>
                <p>${description}</p>`,

                `<a href="/create">create</a>`);

 response.writeHead(200);
 response.end(html);

 

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');

var template = {
  HTML: function(title,list,body, control){
    return `
    <!doctype html>
    <html>
    <head>
    <title>WEB1 - ${title}</title>
    <meta charset="utf-8">
    </head>
    <body>
    <h1><a href="/">WEB</a></h1>
    ${list}
    ${control}

    ${body}
    </body>
    </html>
    `
  },

  list: function(filelist){
    var list = '<ul>';
    var i = 0;
    while( i < filelist.length ){
      list = list + `<li><a href="/?id=${filelist[i]}">${filelist[i]}</a></li>`
      i += 1
    }
    list = list + '</ul>';
    return list;
  }
}

var app = http.createServer(function(request,response){
    var _url = request.url;
    var queryData = url.parse(_url, true).query;
    var pathname = url.parse(_url, true).pathname;

    if( pathname === '/'){
        if( queryData.id === undefined ){ //home

            fs.readdir('./data', function(error, filelist) {
                var title = 'Welcome'
                var description = 'Hello, Node.js'

                // var list = templateList(filelist);
                // var template = templateHTML(title,list,`<h2>${title}</h2>
                // <p>${description}</p>`,`<a href="/create">create</a>`);
                // response.writeHead(200);
                // response.end(template);

                var list = template.list(filelist);
                var html = template.HTML(title,list,`<h2>${title}</h2>
                <p>${description}</p>`,`<a href="/create">create</a>`);

                response.writeHead(200);
                response.end(html);
            })

         } else { //id 페이지를 선택한 페이지

          fs.readdir('./data', function(error, filelist) {

            fs.readFile(`data/${queryData.id}`, 'utf8', function(err,description){
              var list = template.list(filelist);
              var title = queryData.id
              var html = template.HTML(title,list,`<h2>${title}</h2>
                <p>${description}</p>`,
                `<a href="/create">create</a>
                 <a href="/update?id=${title}">update</a>,
                 <form action="delete_process" method="post" onsubmit="delete하기">
                    <input type="hidden" name="id" value="${title}">
                    <input type="submit" value="delete">
                 </form>`);
              response.writeHead(200);
              response.end(html);
            });
          });
        }
    }

    else if( pathname === '/create' ){
      fs.readdir('./data', function(error, filelist) {
          var title = 'WEB-Create'
          var list = template.list(filelist);
          var html = template.HTML(title,list,`
            <form action="http://localhost:3000/create_process" method="post">
            <p><input type="text" name="title" placeholder="title"></p>
            <p>
              <textarea name="description" placeholder="description"></textarea>
            </p>
            <p>
              <input type="submit">
            </p>
            </form>
            `,'');

          response.writeHead(200);
          response.end(html);
      });
    }
    else if( pathname === '/create_process' ){
      var body ='';
      request.on('data',function(data){
        body = body + data
      });
      request.on('end', function(){
        var post = qs.parse(body);
        var title = post.title;
        var description = post.description;
        fs.writeFile(`data/${title}`, description, 'utf8', function(err){
          response.writeHead(302, {Location: `/?id=${title}`});
          response.end();
        })
      });
    }
    else if (pathname === '/update') {
      fs.readdir('./data', function(error, filelist) {

        fs.readFile(`data/${queryData.id}`, 'utf8', function(err,description){
          var list = template.list(filelist);
          var title = queryData.id
          var html = template.HTML(title,list,
            //forn에서 submit을 했을 때 사용자가 정보를 update_process로 보내게 변경
            `<form action="http://localhost:3000/update_process" method="post">
            <input type="hidden" name="id" value="${title}">
            <p><input type="text" name="title" placeholder="title" value='${title}'></p>
            <p>
              <textarea name="description" placeholder="description">${description}</textarea>
            </p>
            <p>
              <input type="submit">
            </p>
            </form>`,
            `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
          )

          response.writeHead(200);
          response.end(html);
        });
      });
    }
    else if (pathname === '/update_process') {
      var body ='';
      request.on('data',function(data){
        body = body + data
      });
      request.on('end', function(){
        var post = qs.parse(body);
        var title = post.title;
        var description = post.description;
        var id = post.id
        fs.rename(`data/${id}`, `data/${title}`, function(error){
          fs.writeFile(`data/${title}`, description, 'utf8', function(err){
              response.writeHead(302, {Location: `/?id=${title}`});
              response.end();
          })
        })
      });
    }
    else if (pathname === '/delete_process') {
      var body ='';
      request.on('data',function(data){
        body = body + data
      });
      request.on('end', function(){
        var post = qs.parse(body);
        var id = post.id
        //id부분만 전송이 되므로 title과 description 변수 필요 없음

        fs.unlink(`data/${id}`, function(error){
          response.writeHead(302, {Location: `/`});
          response.end();
        })

      });
    }
    else {
        response.writeHead(404);
        response.end('Not Found');
    }

});
app.listen(3000);