123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126 |
- 'use strict';
- /**
- * 业务逻辑基类
- *
- * @author CaiAoLin
- * @date 2017/10/11
- * @version
- */
- const Service = require('egg').Service;
- // 数据模型基类
- class BaseService extends Service {
- /**
- * 构造函数
- *
- * @param {Object} ctx - egg全局context
- * @return {void}
- */
- constructor(ctx) {
- super(ctx);
- this.db = this.app.mysql;
- this.cache = this.app.redis;
- }
- /**
- * 设置表名
- *
- * @param {String} table - 表名
- * @return {void}
- */
- set tableName(table) {
- this._table = this.app.config.tablePrefix + table;
- }
- /**
- * 获取表名
- *
- * @return {String} - 返回表名
- */
- get tableName() {
- return this._table;
- }
- /**
- * 根据id查找数据
- *
- * @param {Number} id - 数据库中的id
- * @return {Object} - 返回单条数据
- */
- async getDataById(id) {
- return await this.db.get(this.tableName, { id });
- }
- /**
- * 根据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;
- }
- /**
- * 获取分页数据(SqlBuilder版本)
- *
- * @return {Array} - 返回分页数据
- */
- async getListWithBuilder() {
- // 由于egg-mysql不提供like、不等于操作,所以需要自己组sql
- if (this.sqlBuilder === null) {
- return [];
- }
- // 分页相关
- this.sqlBuilder.limit = this.app.config.pageSize;
- this.sqlBuilder.offset = this.app.config.pageSize * (this.ctx.page - 1);
- // 数据筛选
- if (this.ctx.sort !== undefined && this.ctx.sort.length > 0) {
- this.sqlBuilder.orderBy = [this.ctx.sort];
- }
- const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
- const list = await this.db.query(sql, sqlParam);
- return list;
- }
- /**
- * 获取分页数据
- *
- * @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;
- }
- }
- module.exports = BaseService;
|