본문 바로가기
WEB/Nodejs-mysql

[Nodejs-mysql] 테이블 만들고 모듈 분리하기

by Ellen571 2020. 8. 7.

[생활코딩] 저자 목록 보기 기능 구현

 

 

main.js

var author = require('./lib/author');

else if(pathname === '/author'){
      author.home(request,response);
}

 

lib/author.js

var db = require('./db');
var template = require('./template.js');

exports.home = function(request, response){
    db.query('SELECT*FROM topic', function(error, topics){
        db.query('SELECT*FROM author', function(error2, authors){
        // author데이터 불러와 authors에 넣기
        
            var title = 'Author';
            var list = template.list(topics);
            var html = template.HTML(title, list,
                `
                    ${template.authorTable(authors)}
                    <style>
                        table { border-collapse: collapse}
                        td {border: 1px solid #333; padding: 5px 10px}
                    <style>
                `,
                `<a href="/create">create</a>`
            );
            // template의 authorTable 불러오고 인자로 authors 넘기기
            
            response.writeHead(200);
            response.end(html);
        });
    });
}

 

lib/template.js

module.exports = {
  HTML:function(title, list, body, control){...},
  list:function(topics){...},
  authorSelect:function(authors, author_id){...},
  authorTable:function(authors){ // 매개변수 authors로 인자값 받기
    var tag = '<table>';
    var i = 0;
    
    // authors값 테이블로 만들기
    while(i < authors.length){
        tag += `
            <tr>
                <td>${authors[i].name}</td>
                <td>${authors[i].profile}</td>
                <td>update</td>
                <td>delete</td>
            </tr>
        `;
        i++;
    };
    tag += '</table>';
    return tag;
  }
}
반응형