생활코딩/node.js-mysql

저자 관련 기능 구현

7he8oy 2021. 1. 12. 19:03

저자 관련 만들기/읽기/수정/삭제 기능을 구현 하였음

const template = require('./template.js');
const db = require('./db');
const url = require('url');
const qs = require('querystring');




exports.authors = function(request, response){
  db.query(`select * from topic`, function(error,topics){
    db.query(`select*from author`, function(error2, authors){
      var list = template.list(topics);
      var title = 'Author List';
      var html = template.HTML(title,template.table(authors)
      ,list,
      `<a href = '/authors/create'>create</a>`);
      response.writeHead(200);
      response.end(html);
    });
  });
}


exports.create = function(request, response){
  db.query(`select * from topic`, function(error,topics){
    db.query(`select * from author`, function(error2, authors){

      var list = template.list(topics);
      var title = 'create-author';
      var html = template.HTML(title,
      `${template.table(authors)}<form action = "/authors/create_process" method = 'post'>
      <p><input type='text' name='name' placeholder = 'name'></p>
      <p><textarea name='profile' rows='10' cols='30' placeholder = 'insert profile here'></textarea>
      </p>
      <p><input type='submit' value = 'create'>
      </p>

      </form>`,list,
      ''
      );
      response.writeHead(200);
      response.end(html);
    });

  });
}

exports.create_process = function(request, response){
  var body = '';
  request.on('data',function(data){
    body = body + data ;
  });
  request.on('end',function(){
    var post = qs.parse(body)
    db.query(`
      insert into author(name, profile)
      values(?, ?)`,
    [post.name, post.profile],
    function(error, results){
      if (error){
        throw error;
      }
    response.writeHead(302,{
      'Location' : `/authors`
    });
    response.end()
    });
  });
}

exports.update = function(request, response){
  var _url = request.url;
  var queryData = url.parse(_url,true/*true는 객체형식으로 받아옴*/).query;
  db.query(`select * from topic`, function(error,topics){
    db.query(`select * from author`, function(error2, authors){
      db.query(`select * from author where id =?`, [queryData.id],function(error3, author){
        var list = template.list(topics);
        var title = 'update-author';
        var html = template.HTML(title,
        `${template.table(authors)}<form action = "/authors/update_process" method = 'post'>
        <p>
          <input type='text' name='name' value = '${author[0].name}'>
        </p>
        <p>
          <input type='hidden' name = 'id' value = '${queryData.id}'>
        </p>
        <p>
          <textarea name='profile' rows='10' cols='30'>${author[0].profile}</textarea>
        </p>
        <p>
          <input type='submit' value = 'update'>
        </p>

        </form>`,list,
        ''
        );
        response.writeHead(200);
        response.end(html);
      });
    });
  });
}

exports.update_process = function(request, response){
  var body = '';
  request.on('data', function(data){
    body = body + data ;
  });
  request.on('end', function(){
    var post = qs.parse(body)
    db.query(`
      update author set name = ?, profile = ? where id = ?`,
      [post.name, post.profile, post.id],
      function(error, result){
        if (error){
          throw error;
        }
      response.writeHead(302, {
        'Location' : `/authors`
      });
      response.end()
    });
  });
}

exports.delete = function(request, response){
  var body = '';
  request.on('data', function(data){
    body = body + data ;
  });
  request.on('end', function(){
    var post = qs.parse(body)
    db.query(`delete from author where id = ?`, [post.id],function(error, results){
      if (error){
        throw error;
      }
      db.query(`delete from topic where author_id =?`, [post.id], function(error2, results){
        if(error2){
          throw error2;
        }
        response.writeHead(302, {
        'Location' : `/authors`
        });
      response.end()
      });

    });
  });
}

그에 따른 main.js 수정본

const http = require('http');
const url = require('url');
const path = require('path');
const topic = require('./lib/topic');
const author = require('./lib/author');

const app = http.createServer(function(request,response){
  var _url = request.url;
  var queryData = url.parse(_url,true/*true는 객체형식으로 받아옴*/).query;
  var pathname = url.parse(_url,true).pathname;

  if(pathname === '/'){
    if(queryData.id === undefined){
      topic.home(response);
    } else {
      topic.desc(request,response)
      };
  } else if(pathname==='/create'){
    topic.create(request,response)
  } else if(pathname === '/create_process'){
    topic.create_process(request, response)
  } else if(pathname === '/update'){
    topic.update(request, response)
  } else if(pathname === '/update_process'){
    topic.update_process(request, response)
  } else if(pathname === '/delete'){
    topic.delete(request, response)
  } else if(pathname === '/authors'){
    author.authors(request, response);
  } else if(pathname ==='/authors/create'){
    author.create(request, response);
  } else if(pathname ===`/authors/create_process`){
    author.create_process(request,response);
  } else if(pathname ==='/authors/delete') {
    author.delete(request, response);
  } else if(pathname === '/authors/update'){
    author.update(request, response);
  } else if(pathname ==='/authors/update_process'){
    author.update_process(request, response);
  } else {
    response.writeHead(404);
    response.end('Not Found')
  }
});
app.listen(3000);


//creat까지 만들었고 update만들기!!

template.js 수정본

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

  }, HTML : function(title,content,list,control){
      return `
      <!doctype html>
      <html>
      <head>
        <title>민석-${title}</title>
        <meta charset = "utf-8">
      </head>
      <body>
      <h1><a href = '/'>HOME</a></h1>
      <p><a href = '/authors'>authors</a>
      </p>
      <p>
        ${list}
      </p>
      <p>
        ${control}
      </p>
      <h2>${title}</h2>
      <p>
        ${content}
      </p>
      </body>
      </html>
      `;
    }, combo : function(name,t,k){
        var combo = `<select name=${name}>`
        var i = 0 ;
        while(i<t.length){
          var selected = '';
          if(k===t[i].id){
            selected = 'selected';
          }
          combo += `<option value = '${t[i].id}' ${selected}>${t[i].name}</option>`;
        i++;
        };
        combo += `</select>`;
      return combo

    }, table: function(t) {
      var i = 0;
      var table = `<table>
                      <th>name</th>
                      <th>profile</th>
                      <th>update</th>
                      <th>delete</th>`;
      while(i<t.length){
        table += `<tr>
                    <td>${t[i].name}</td>
                    <td>${t[i].profile}</td>
                    <td><a href = '/authors/update?id=${t[i].id}'>update</a></td>

                    <td><form action = '/authors/delete' method = 'post' name = 'id'>
                          <input type = 'hidden' name = 'id' value = '${t[i].id}'>
                          <input type = 'submit' value = 'delete'>
                        </form></td>
                  </tr>`
        i++;
      };
      table += `</table><style>
                table, th, td {
                  border: 1px solid black;
                  border-collapse: collapse;
                }
                </style>`
      return table;
    }
}

'생활코딩 > node.js-mysql' 카테고리의 다른 글

sanitize-html  (0) 2021.01.12
SQL injection  (0) 2021.01.12
mysql로 node.js에서 만든 수업을 옮기다.  (0) 2021.01.11
node.js와 mysql 연결하기  (0) 2021.01.07
npm과 package.json  (0) 2021.01.07