想找个koa 操作mysql的github例子,有分享的哥哥吗
想找个koa 操作mysql的github例子,有分享的哥哥吗
3 回复
这个和koa没什么关系,npm搜mysql模块即可
写过一些demo,用的是 bookshelf(看了很多mysql orm 之后觉得这个相对来说好用点) 封装了一下数据库表操作 Table
const path = require('path'),
Helper = require('./helper')
let getTable = ()=> {
return Helper.walk(path.dirname(__dirname) + '/app/models', 1).reduce((result, item)=> {
let modelName = path.basename(item, '.js')
modelName = modelName.split('_').map((item)=> {
return item[0].toUpperCase() + item.substring(1)
}).join('')
result[modelName] = require(item)
return result
}, {})
}
module.exports = getTable()
然后就可以往app/models
下面扔模型了,下面是会有模型 mem.js
const DB = require('../../lib/db')
module.exports = DB.bookshelf.Model.extend({
tableName: 'mem',
constructor: function() {
DB.bookshelf.Model.apply(this, arguments);
this.avatar = this.avatar || 'http://awesomes.img-cn-beijing.aliyuncs.com/mem/151014235057-52.jpg'
}
})
最后在congtroller中调用
exports.post_signup = async (ctx, next) =>{
let body = ctx.request.body
let crypto = require('crypto');
let pwd = crypto.createHash('md5').update(body.pwd).digest('hex');
let param = {
nc: body.nc,
pwd: pwd,
email: body.email
}
await new Table.Mem(param).save()
ctx.body = {status: true}
}
此外还可以构建一些 migration
如 20160616125841_create_table_mem.js
table File 16 lines (11 sloc) 303 Bytes
const knex = require('knex')
exports.up = function(knex, Promise) {
return knex.schema.createTable('mem', function(table) {
table.increments('id').primary();
table.string('email');
table.string('pwd');
table.string('nc', 100);
})
};
exports.down = function(knex, Promise) {
};
@DevinXian 谢啦