컴퓨터/nodejs

nodejs mysql 생활코딩 저자테이블 만들기

풍경소리^^ 2023. 4. 5. 17:25

Node.js & MySQL - 15. 저자 관리 기능 구현

https://www.youtube.com/watch?v=c13mdXV_YWg&list=PLuHgQVnccGMAicFFRh8vFFFtLLlNojWUh&index=20 

lib-template_table.js--------------------

module.exports = {
  Html: function(title, body, control){
    return `
    <!doctype html>
    <html>
    <head>
      <title>WEB2 - Auth table</title>
      <meta charset="utf-8">
    </head>
    <body>
      <a href="/">WEB</a>
      <h1><a href="/author">author</a></h1>
      ${control}
      ${body}
    </body>
    </html>
    `;
  }, authorTable:function(authors){
    var tag = `
        <table>
          <tr>
            <td>저자</td>
            <td>프로필</td>
            <td>수정</td>
            <td>삭제</td>
          </tr>
      `;
      var i = 0;
      while(i < authors.length){
        tag += `
          <tr>
            <td>${authors[i].name}</td>
            <td>${authors[i].profile}</td>
            <td><a href="/author/update?id=${authors[i].id}">update</a></td>
            <td>
              <form action="/author/delete_process" method="post">
                <input type="hidden" name="id" value="${authors[i].id}">
                <input type="submit" value="delete">
              </form>
            </td>
          </tr>
        `
        i++;
      }
      tag += '</table>';
      return tag;
    }
}

lib-author_table.js--------------------

var db = require('./db');
var template_table = require('./template_table.js');
var qs = require('querystring');
var url = require('url');

exports.home = function(request, response){ // API 여러개 제공
  db.query(`SELECT * FROM author`, function(error2, authors){
    var title = 'author';
    var html = template_table.Html(title,
      `
        ${template_table.authorTable(authors)}
        <style>
          table{
            border-collapse: collapse;
          }
          td{
            border: 1px solid black;
          }
        </style>
        <form action="/author/create_process" method="post">
          <p>
            <input type="text" name="name" placeholder="name">
          </p>
          <p>
            <textarea name="profile" placeholder="description"></textarea>
          </p>
        <p>
          <input type="submit" value="create">
        </p>
        </form>
        `,
        ``
    );
    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, result) {
        if(error){
          throw error;
        }
        response.writeHead(302, {Location: `/author`});
        response.end();
      }
    )
  });
}

exports.update = function(request, response){ // API 여러개 제공
  db.query(`SELECT * FROM author`, function(error2, authors){
    var _url = request.url;
    var queryData = url.parse(_url, true).query;
    db.query(`SELECT * FROM author WHERE id=?`, [queryData.id], function(error3, author){
      var title = 'author';
    var html = template_table.Html(title,
      `
        ${template_table.authorTable(authors)}
        <style>
          table{
            border-collapse: collapse;
          }
          td{
            border: 1px solid black;
          }
        </style>
        <form action="/author/update_process" method="post">
          <p>
            <input type="hidden" name="id" value="${queryData.id}">
          </p>
          <p>
            <input type="text" name="name" value="${author[0].name}" placeholder="name">
          </p>
          <p>
            <textarea name="profile" placeholder="description">${author[0].profile}</textarea>
          </p>
          <p>
            <input type="submit" value="update">
          </p>
        </form>
      `,
      ``
    );
    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: `/author`});
        response.end();
      }
    )
  });
}
exports.delete_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(`
      DELETE FROM author WHERE id=?`, 
      [post.id],
      function(error, result) {
        if(error){
          throw error;
        }
        response.writeHead(302, {Location: `/author`});
        response.end();
      }
    )
  });
}

main_table.js--------------------

var http = require('http');
var url = require('url');
var author_table = require('./lib/author_table')

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 === '/author'){
    author_table.home(request, response);
  } else if(pathname === '/author/create_process'){
    author_table.create_process(request, response);
  } else if(pathname === '/author/update'){
    author_table.update(request, response);
  } else if(pathname === '/author/update_process'){
    author_table.update_process(request, response);
  } else if(pathname === '/author/delete_process'){
    author_table.delete_process(request, response);
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

lib-db.js--------------------

var mysql = require('mysql');

var db = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '비밀번호',
  database : '데이터베이스이름',
  multipleStatements: true
});
db.connect();

module.exports = db; // 하나만 꺼내어 놓는다면

====================