nodejs实现增删改查

timetrack_server.js首先用的mysql数据库,所以引用了mysql模块。然后根据访问类型req.method来判断get还是post操作。然后根据req.url判断调用的方法。db.query创建一个表

var http = require('http')
var work = require('./lib/timetrack')
var mysql = require('mysql')
var db = mysql.createConnection({
    host: '127.0.0.1',
    user: 'admin',
    password: 'admin',
    database: 'timetrack'
})
var server = http.createServer(function (req, res) {
    switch (req.method) {
        case 'POST':
            switch (req.url){
                case '/':
                    work.add(db, req, res)
                    break;
                case  '/archive':
                    work.archive(db, req, res)
                    break;
                case '/delete':
                    work.delete(db, req, res)
                    break;
            }
            break;
        case 'GET':
            switch (req.url) {
                case '/':
                    work.show(db, res)
                    break;
                case '/archived':
                    work.showArchived(db, res)
            }
            break;
    }
})
db.query(
    "CREATE TABLE IF NOT EXISTS WORK (" +
    "id int(10) not null auto_increment ," +
    "hours decimal(5,2) default 0 ," +
    "date DATE ," +
    "archived int(1) default 0 ," +
    "description longtext ," +
    "primary key(id))",
    function (err) {
        if(err) throw err
        console.log('server started')
        server.listen(3000, '127.0.0.1')

    }
)

timetrack.js这里定义具体的方法,所有方法最后都会走到show(),而show()最后调用的是sendHtml()将最终生成的html返回给客户端。parseReceiveData()函数,负责将请求数据转成人看的数据,db.query是操作数据库,其中 ? 是占位符,后面跟上对应的数值。

var qs = require('querystring')
exports.sendHtml = function (res, html) {
    res.setHeader('Content-Type', 'text/html')
    res.setHeader('Content-Length', Buffer.byteLength(html))
    res.end(html)
}
exports.parseReceivedData = function (req, cb) {
    var body = ''
    req.setEncoding('utf8')
    req.on('data',function (chunk) {
        body += chunk
    })
    req.on('end', function () {
        var data = qs.parse(body)
        cb(data)
    })
}
exports.actionForm = function (id, path, lable) {
    var html = '<form method="post" action="'+path+'">' +
        '<input type="hidden" name="id" value="'+id+'">' +
        '<input type="submit" value="'+lable+'">' +
        '</form>'
    return html
}

exports.add = function (db, req, res) {
    exports.parseReceivedData(req, function (work) {
        db.query(
            "insert into work (hours, date, description) " +
            "values (?, ?, ?)",
            [work.hours, work.date, work.description],
            function (err) {
                if(err) throw err
                exports.show(db, res)
            }
        )
    })
}

exports.delete = function (db, req, res) {
    exports.parseReceivedData(req,function (work) {
        console.log(db.query)
        db.query(
            "delete from work where id = ?",
            [work.id],
            function (err) {
                if(err) throw err
                exports.show(db, res)
            }
        )

    })
}
exports.archive = function (db, req, res) {
    exports.parseReceivedData(req, function (work) {
        db.query(
            "update work set archived=1 where id=?",
            [work.id],
            function (err) {
                if(err) throw err
                exports.show(db,res)
            }
        )
    })
}
exports.show = function (db, res, showArchived) {
    var query = 'select * from work where archived = ? order by date desc'
    var archiveValue = (showArchived) ? 1 : 0
    db.query(
        query,
        [archiveValue],
        function (err, rows) {
            console.log(rows)
            if(err) throw err
            html = (showArchived)
            ? ''
            : '<a href="/archived">Archived work</a></br>'
            html += exports.workHitlistHtml(rows)
            html += exports.workFormHtml()
            exports.sendHtml(res, html)
        }
    )
}
exports.showArchived = function (db, res) {
    exports.show(db, res, true)
}
exports.workHitlistHtml = function (rows) {
    var html = '<table>'
    for(var i in rows){
        html += '<tr>'
        html += '<td> '+formatDate(rows[i].date)+' </td>'
        html += '<td>'+rows[i].hours+'</td>'
        html += '<td>'+rows[i].description+'</td>'
        if(!rows[i].archived) {
            html += '<td>'+exports.workArchiveForm(rows[i].id)+'</td>'
        }
        html += '<td>'+exports.workDeleteForm(rows[i].id)+'</td>'
        html += '</tr>'
    }
    html += '</table>'
    return html
}
exports.workFormHtml = function () {
    var html = '<form  method="post" action="/">' +
        '<p>date (yyyy-mm-dd):<br/><input type="text" name="date"></p>' +
        '<p>hours worked: <br/> <input type="text" name="hours"></p>' +
        '<p>description<br/>' +
        '<textarea name="description"></textarea></p>' +
        '<input type="submit" value="add">' +
        '</form>'
    return html
}
exports.workArchiveForm = function (id) {
    return exports.actionForm(id, '/archive', 'Archive')
}
exports.workDeleteForm = function (id) {
    return exports.actionForm(id, '/delete', 'Delete')
}

var formatDate = function (date) {
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? '0' + m : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    return y + '-' + m + '-' + d;
};


 

随机浏览