使用koa,knex操作数据库 发表于 2018-06-10 | 更新于 2023-01-11 使用koa,knex操作数据库 重新整理了一下增删改查的方法,中间没有做任何安全判断,但是个人使用感觉很方便 knex官网 另一篇knex入门 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102/** * mysql helper * author: luzhongk@126.com */const db = require('../utils/mysql.js') // knexconst moment = require('moment')function formatData(data = []) { const FORMAT = 'YYYY-MM-DD HH:mm:ss' data.forEach(item => { if (item.create_time) { item.create_time = moment(item.create_time).format(FORMAT) } if (item.update_time) { item.update_time = moment(item.update_time).format(FORMAT) } }) return data}/** * 分页查询 * @param ctx (koa ctx对象) * @param dbName (数据库名字) * @param condition (查询条件) * @returns {Promise<Object>} */const list = async (ctx, dbName, condition = {}) => { let { page = 1, size = 1000 } = ctx.query if (page < 1) page = 1 const getContent = db(dbName) .select() .limit(size) .offset((page - 1) * size) .where(condition) .orderBy('create_time', 'desc') const getTotal = db(dbName).where(condition).count('id as total') const [content, total] = await Promise.all([getContent, getTotal]) const data = { content: formatData(content), total: total.length ? total[0].total : 0 } ctx.state.data = data return data}/** * 添加数据 * @param ctx * @param dbName (数据库成功) * @param body (插入内容,或者使用发送的body) * @returns {Promise<Number>} (id) */const add = async (ctx, dbName, body) => { const data = await db(dbName).insert(body || ctx.request.body) ctx.state.data = data return data}/** * 更新数据 * @param ctx * @param dbName * @param body (插入内容,或者使用发送的body) * @returns {Promise<null Number>} */const update = async (ctx, dbName, body) => { const data = body || ctx.request.body const { id } = data if (!id) ctx.throw(400, 'id not found') delete data.id const res = await db(dbName).update(data).where({ id }) ctx.state.data = res return res}/** * 删除数据 * @param ctx * @param dbName * @param removeId * @returns {Promise<*>} */const remove = async (ctx, dbName, removeId) => { const { id } = {removeId} || ctx.params || ctx.query if (!id) ctx.throw(400, 'id not found') if (id === 'all') { const data = await db(dbName).truncate() // 清空表 ctx.state.data = '成功' return data } else { const data = await db(dbName).where('id', id).del() ctx.state.data = data return data }}module.exports = { list, add, update, remove} 使用 在koa实例对象app中注入 12// 注入工具类app.context.dbHelper = dbHelper 使用demo 1234567891011121314151617/** * 临时日志 */const dbName = 'kuan_logger';module.exports = { async list(ctx) { await ctx.dbHelper.list(ctx, dbName); }, async remove(ctx) { await ctx.dbHelper.remove(ctx, dbName); }, async add(ctx) { await ctx.dbHelper.add(ctx, dbName); }};