wr1207
2022-03-09 78d5094582b942ba2745264fc938c899700ce550
add datainterface
3个文件已修改
4个文件已添加
274 ■■■■■ 已修改文件
src/app/modules/base/controller/admin/comm.ts 25 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/app/modules/base/controller/admin/open.ts 24 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/app/modules/base/controller/app/comm.ts 1 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/app/modules/base/service/dataapi/dataapi.ts 55 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/app/modules/base/utils/arrayutil.ts 25 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/app/modules/base/utils/dateutil.ts 52 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/app/modules/base/utils/mysqlutil.ts 92 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/app/modules/base/controller/admin/comm.ts
@@ -1,10 +1,11 @@
import { Provide, Inject, Get, Post, Body, ALL } from '@midwayjs/decorator';
import { Provide, Inject, Get, Post, Body, ALL, Query } from '@midwayjs/decorator';
import { Context } from 'egg';
import { CoolController, BaseController, ICoolFile } from '@cool-midway/core';
import { BaseSysUserEntity } from '../../entity/sys/user';
import { BaseSysLoginService } from '../../service/sys/login';
import { BaseSysPermsService } from '../../service/sys/perms';
import { BaseSysUserService } from '../../service/sys/user';
import { DataService } from '../../service/dataapi/dataapi';
/**
 * Base 通用接口 一般写不需要权限过滤的接口
@@ -20,6 +21,9 @@
  @Inject()
  baseSysLoginService: BaseSysLoginService;
  @Inject()
  dataService: DataService;
  @Inject()
  ctx: Context;
@@ -90,4 +94,23 @@
    await this.baseSysLoginService.logout();
    return this.ok();
  }
  /**
   * 获得数据
   */
   @Get('/getdata', { summary: '数据接口' })
   async getData(@Query(ALL) params: any) {
     console.log('-------------------------------------------------------');
     return this.ok(await this.dataService.getData(params));
   }
  /**
   * 获得数据
   */
   @Get('/postdata', { summary: '数据接口' })
   async postData(@Query(ALL) params: any) {
     return this.ok(await this.dataService.getData(params));
   }
}
src/app/modules/base/controller/admin/open.ts
@@ -12,6 +12,7 @@
import { LoginDTO } from '../../dto/login';
import { BaseSysLoginService } from '../../service/sys/login';
import { BaseSysParamService } from '../../service/sys/param';
import { DataService } from '../../service/dataapi/dataapi';
/**
 * 不需要登录的后台接口
@@ -24,6 +25,9 @@
  @Inject()
  baseSysParamService: BaseSysParamService;
  @Inject()
  dataService: DataService;
  @Inject()
  ctx: Context;
@@ -76,4 +80,24 @@
  async refreshToken(@Query() refreshToken: string) {
    return this.ok(await this.baseSysLoginService.refreshToken(refreshToken));
  }
  /**
   * 获得数据
   */
   @Get('/getdata', { summary: '数据接口' })
   async getData(@Query(ALL) params: any) {
     console.log('-------------------------------------------------------');
     console.log(params);
     return this.ok(await this.dataService.getData(params));
   }
  /**
   * 获得数据
   */
   @Get('/postdata', { summary: '数据接口' })
   async postData(@Query(ALL) params: any) {
     return this.ok(await this.dataService.getData(params));
   }
}
src/app/modules/base/controller/app/comm.ts
@@ -50,4 +50,5 @@
  async uploadMode() {
    return this.ok(this.coolFile.getMode());
  }
}
src/app/modules/base/service/dataapi/dataapi.ts
New file
@@ -0,0 +1,55 @@
import { Inject, Provide } from '@midwayjs/decorator';
import { BaseService, ICoolCache, } from '@cool-midway/core';
import * as _ from 'lodash';
import { MysqlUtil } from '../../utils/mysqlutil';
/**
 * 系统用户
 */
@Provide()
export class DataService extends BaseService {
  @Inject('cool:cache')
  coolCache: ICoolCache;
  @Inject()
  mysqlUtil: MysqlUtil;
  /**
   * 分页查询
   * @param query
   */
  async getData(query) {
    // const { keyWord, status, departmentIds = [] } = query;
    // const permsDepartmentArr = await this.baseSysPermsService.departmentIds(
    //   this.ctx.admin.userId
    // ); // 部门权限
    const bidsql = `select * from t_sys_business_config where id_='${query.bid}' limit 0,1`;
    const bid_obj_ = await this.nativeQuery(bidsql);
    let sqlObj = this.mysqlUtil.create_sql(bid_obj_[0], query?.pageindex || null , query?.pagesize || null, query);
    if (sqlObj?.status == 0) {
        return sqlObj?.msg;
    }
    return this.sqlRenderPage(sqlObj?.sql, query);
  }
  /**
   * 分页查询
   * @param query
   */
   async updateData(query) {
    // const { keyWord, status, departmentIds = [] } = query;
    // const permsDepartmentArr = await this.baseSysPermsService.departmentIds(
    //   this.ctx.admin.userId
    // ); // 部门权限
    const bidsql = `select * from t_sys_business_config where id_='${query.bid}' limit 0,1`;
    const bid_obj_ = await this.nativeQuery(bidsql);
    let sqlObj = this.mysqlUtil.create_sql(bid_obj_[0], query?.pageindex || null , query?.pagesize || null, query);
    if (sqlObj?.status == 0) {
        return sqlObj?.msg;
    }
    return this.sqlRenderPage(sqlObj?.sql, query);
  }
}
src/app/modules/base/utils/arrayutil.ts
New file
@@ -0,0 +1,25 @@
import { Provide } from "@midwayjs/decorator"
/**
 * 系统用户
 */
@Provide()
export class DateUtil {
    /**
    * 拼接数组
    * @param values 待拼接数组
    * @param separator 分隔符
    */
    array_connect(values, separator) {
        if (values.length) {
            let str = ''
            for (var idx in values) {
                str += `'${values[idx]}'${separator}`
            }
            return str.substring(0, str.length - 1)
        } else {
            return ''
        }
    }
}
src/app/modules/base/utils/dateutil.ts
New file
@@ -0,0 +1,52 @@
import { Provide } from "@midwayjs/decorator"
/**
 * 系统用户
 */
@Provide()
export class DateUtil {
    date_format(date_str, format) {
        // = 'YY-MM-DD hh:mm:ss'
        let date = new Date(date_str)
        let year = date.getFullYear(),
            month = date.getMonth() + 1, //月份是从0开始的
            day = date.getDate(),
            hour = date.getHours(),
            min = date.getMinutes(),
            sec = date.getSeconds()
        let preArr = Array.apply(null, Array(10)).map(function (elem, index) {
            return '0' + index
        }) ////开个长度为10的数组 格式为 00 01 02 03
        let newTime = format
            .replace(/YY/g, year)
            .replace(/MM/g, preArr[month] || month)
            .replace(/DD/g, preArr[day] || day)
            .replace(/hh/g, preArr[hour] || hour)
            .replace(/mm/g, preArr[min] || min)
            .replace(/ss/g, preArr[sec] || sec)
        return newTime
    }
    /**
     * 当月第一天和最后一天
     * @param {*} date
     */
    month_first_end(date) {
        let M = typeof date == 'undefined' ? new Date() : date.getMonth()
        let Y = typeof date == 'undefined' ? new Date() : date.getFullYear()
        let day = new Date(Y, M + 1, 0).getDate()
        let enddate = new Date(Y, M, day)
        let result = {
            start: this.date_format(new Date(Y, M, 1), 'YY-MM-DD'),
            end: this.date_format(enddate, 'YY-MM-DD')
        }
        return result
    }
}
src/app/modules/base/utils/mysqlutil.ts
New file
@@ -0,0 +1,92 @@
import { Provide } from "@midwayjs/decorator"
@Provide()
export class MysqlUtil {
    /**
     * 生成select语句 [sql_count、sql]
     * @param {Object} obj select_ from_ where_ order_ server_paging pageindex_ pagesize_
     */
    create_sql(obj, pageindex_, pagesize_, query) {
        let str_select_ = [];
        let str_select_count = [];
        str_select_.push(`${obj.select_} ${obj.from_} ${obj.where_} ${obj.order_}`);
        str_select_count.push(`select count(1) as counter ${obj.from_} ${obj.where_} ${obj.order_}`);
        if (obj.server_paging == '1') {
            let pageindex = Number.isNaN(Number(pageindex_)) ? Number(pageindex_) : 1;
            let pagesize = Number.isNaN(Number(pagesize_)) ? Number(pagesize_) : 10;
            let limit_begin = (pageindex - 1) * pagesize;
            str_select_.push(` limit ${limit_begin} , ${pagesize}`);
        }
        return this.replaceParams([str_select_.join(''), str_select_count.join('')], query)
    }
    /**
     * 生成select语句 [sql_count、sql]
     * @param {Object} obj select_ from_ where_ order_ server_paging pageindex_ pagesize_
     */
    create_sync_sql(obj) {
        let str_select_ = [];
        let str_sync = [];
        str_select_.push(`${obj.select_} ${obj.from_} ${obj.where_} ${obj.order_}`);
        str_sync.push(`${obj.insert_} ${obj.column_} ${obj.values_} ${obj.updateDuplicate_}`);
        return [str_sync.join(''), str_select_.join('')]
    }
    /**
     * 生成sql
     * @param [] strs 要处理的数据 sql_count、sql
     * @param {JSON} reqParams 请求参数
     */
    replaceParams(str, reqParas) {
        let pattern = /([#|$](\s{0,}){(\s{0,})(.*?)(\s{0,})})/g;
        let match = str[0].match(pattern);
        let status = 1;
        let msg = '';
        if (!match) {
        } else {
            for (let index = 0; index < match.length; index++) {
                let paramName = this.getBraceStr(match[index]).replace(/\s*/g, "")
                if (!(paramName in reqParas)) {
                    status = 0;
                    msg = 'parameter ' + paramName + ' is not provided';
                }
                str[0] = str[0].replace(match[index], reqParas[paramName]);
                str[1] = str[1].replace(match[index], reqParas[paramName]);
            }
        }
        return { "status": status, 'sql_count': str[1], 'sql': str[0], 'msg': msg };
    }
    /**
    * 取出大括号内的内容
    * @param text
    * @returns {string}
    */
    getBraceStr(text) {
        let result = ''
        if (this.isObjEmpty(text))
            return result
        let regex = /\{(.+?)\}/g;
        let options = text.match(regex)
        if (!this.isObjEmpty(options)) {
            let option = options[0]
            if (!this.isObjEmpty(option)) {
                result = option.substring(1, option.length - 1)
            }
        }
        return result
    }
    isObjEmpty(obj) {
        var name;
        for (name in obj) {
          return false;
        }
        return true;
      }
}