'use strict'; const { CrudService } = require('naf-framework-mongoose-free/lib/service'); const { BusinessError, ErrorCode } = require('naf-core').Error; const _ = require('lodash'); const assert = require('assert'); // mysql数据库操作,针对单表 class MysqlService extends CrudService { constructor(ctx) { super(ctx, 'mysql'); this.db = this.app.mysql; } async create(table, data) { const res = await this.db.insert(table, data); return res; } async delete(table, query = {}) { const res = await this.db.delete(table, query); return res; } async updateById(table, id, data) { const res = await this.db.update(table, { ...data, id }); return res; } async query(table, query = {}, { skip, limit, sort = [], desc } = {}) { const queryParams = {}; if (_.isNumber(skip) || _.isNumber(parseInt(skip))) queryParams.offset = skip; if (_.isNumber(limit) || _.isNumber(parseInt(limit))) queryParams.limit = limit; if (sort) { const orders = []; for (const s of sort) { const item = [ s, desc ? 'desc' : 'asc' ]; orders.push(item); } } const data = await this.db.select(table, { where: query, ...queryParams }); const total = await this.db.count(table, query); return { data, total }; } async fetch(table, query) { const data = await this.db.get(table, query); return data; } } module.exports = MysqlService;