'use strict'; const _ = require('lodash'); const Service = require('egg').Service; const columns = require('../public/query'); const { BusinessError, ErrorCode } = require('naf-core').Error; // 通用列表/多查/全查 查询实现 class QueryService extends Service { constructor(ctx) { super(ctx, 'query'); this.http = this.ctx.service.util.httpUtil; this.spMark = this.ctx.service.special; this.prefix = '/db'; // 默认查询条件 this.defaultType = 'like'; // 强制全等 key 列表 this.eqList = [ 'status' ]; } /** * 常规查询 * @param {Object} param0 表名 * @param {Object} param1 正常query的参数,保函skip(指的是page),limit */ async index({ table }, { skip = 1, limit, ...query } = {}) { query = this.dealQuery(table, query); const data = await this.http.$post(`${this.prefix}/query`, query, { table, page: skip, size: limit }); if (data && data.code) { throw new BusinessError(ErrorCode.SERVICE_FAULT, data.message); } const { list, total } = data; // 在dbToData中找是否有该表需要特殊处理的字段 const resetList = this.spMark.resetDataToFront(list, table); return { data: resetList || [], total }; } /** * 处理参数,给java部分 * 最后形成数组,数组每个元素都是条件,包括查询与排序 * [ * {key:xxx,value:xxx,type:xxx} * ] * @param {String} table 表名 * @param {Object} query 参数 */ dealQuery(table, query) { const arr = _.get(columns, table, []); let order = []; let aboutQuery = []; if (arr.length > 0) { // orderBy分离开,因为与查询条件没关系,与最后数据的过滤有关 order = arr.filter(f => f.type === 'orderBy'); // 取arr,order,between的差集就是正常处理的内容 aboutQuery = _.differenceWith(arr, [ ...order ]); } const nq = []; for (const key in query) { let obj = { key, value: query[key], type: this.defaultType }; const r = aboutQuery.find(f => f.key === key); if (r) obj.type = _.get(r, 'type', this.defaultType); // 特殊处理:如果该key在eqList中,无论什么匹配类型,都改成eq if (this.eqList.includes(key)) obj.type = 'eq'; // 处理key中是否带有@:范围查询的标志,需要把@后面的start/end砍掉 obj = this.spMark.dealMarkQuery(_.cloneDeep(obj)); if (!obj.key) continue; if (obj.value === 'null') { // 特殊处理,如果value为null字符串,需要数据库端进行特殊处理,在这里把类型转换成null类型 obj.type = 'null'; } else if (_.isArray(obj.value)) { // 检查值,如果为数组,则需要将type变成in obj.value = obj.value.join(','); obj.type = 'in'; } nq.push(obj); } // 处理orderBy for (const i of order) { const { key, value } = i; nq.push({ key, value, type: 'orderBy' }); } return nq; } } module.exports = QueryService;