'use strict'; /** * 业务逻辑基类 * * @author Mai * @date 2018/4/19 * @version */ const Service = require('egg').Service; // sql拼装器 const SqlBuilder = require('../lib/sql_builder'); class BaseService extends Service { /** * 构造函数 * * @param {Object} ctx - egg全局context * @return {void} */ constructor(ctx) { super(ctx); this.db = this.app.mysql; this.sqlBuilder = null; } /** * 设置表名 * * @param {String} table - 表名 * @return {void} */ set tableName(table) { this._table = this.app.config.tablePrefix + table; } /** * 获取表名 * * @return {String} - 返回表名 */ get tableName() { return this._table; } /** * 初始化sqlBuilder * * @return {void} */ initSqlBuilder() { if (this.sqlBuilder === null) { this.sqlBuilder = new SqlBuilder(); } } /** * 根据id查找数据 * * @param {Number} id - 数据库中的id * @return {Object} - 返回单条数据 */ async getDataById(id) { return await this.db.get(this.tableName, { id }); } /** * 根据条件查找单条数据 * * @param {Object} condition - 筛选条件 * @return {Object} - 返回单条数据 */ async getDataByCondition(condition) { return await this.db.get(this.tableName, condition); } /** * 根据条件查找数据 * * @param {Object} condition - 筛选条件 * @return {Array} - 返回数据 */ async getAllDataByCondition(condition) { return await this.db.select(this.tableName, condition); } /** * 根据id删除数据 * * @param {Number} id - 数据库中的id * @return {boolean} - 返回是否删除成功 */ async deleteById(id) { const result = await this.db.delete(this.tableName, { id }); return result.affectedRows > 0; } /** * 获取总数 * * @param {Object} option - 过滤条件(参考select方法中的condition) * @return {Number} - 返回查找的总数 */ async count(option = {}) { const result = await this.db.count(this.tableName, option); return result; } /** * 获取分页数据 * * @param {Object} condition - 搜索条件 * @return {Array} - 返回分页数据 */ async getList(condition) { const page = this.ctx.page; // 分页设置 condition.limit = condition.limit === undefined ? this.app.config.pageSize : condition.limit; condition.offset = condition.offset === undefined ? this.app.config.pageSize * (page - 1) : condition.offset; if (this.ctx.sort !== undefined && this.ctx.sort.length > 0) { condition.orders = [this.ctx.sort]; } const list = await this.db.select(this.tableName, condition); return list; } /** * 在事务中写入数据 * * @param {Array|Object} datas * @param transaction - 事务 * @returns {Promise} */ async insertData(data, transaction) { const datas = data instanceof Array ? data : [data]; const insertResult = await transaction.insert(this.tableName, datas); if (insertResult.affectedRows !== datas.length) { throw '写入错误'; } } /** * 在事务中删除数据 * * @param {Array|Object} datas * @param transaction - 事务 * @returns {Promise} */ async deleteData(data, transaction) { const count = await this.count(data); const deleteResult = await transaction.delete(this.tableName, data); if (deleteResult.affectedRows !== count) { throw '删除错误'; } } } module.exports = BaseService;