From 78d5094582b942ba2745264fc938c899700ce550 Mon Sep 17 00:00:00 2001
From: wr1207 <wyun001@163.com>
Date: 星期三, 09 三月 2022 09:42:33 +0800
Subject: [PATCH] add datainterface

---
 src/app/modules/base/utils/mysqlutil.ts         |   92 ++++++++++++++++++
 src/app/modules/base/service/dataapi/dataapi.ts |   55 +++++++++++
 src/app/modules/base/utils/arrayutil.ts         |   25 +++++
 src/app/modules/base/controller/app/comm.ts     |    1 
 src/app/modules/base/controller/admin/comm.ts   |   25 ++++
 src/app/modules/base/utils/dateutil.ts          |   52 ++++++++++
 src/app/modules/base/controller/admin/open.ts   |   24 ++++
 7 files changed, 273 insertions(+), 1 deletions(-)

diff --git a/src/app/modules/base/controller/admin/comm.ts b/src/app/modules/base/controller/admin/comm.ts
index 3446302..9ab7bff 100644
--- a/src/app/modules/base/controller/admin/comm.ts
+++ b/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));
+   }     
+   
+
 }
diff --git a/src/app/modules/base/controller/admin/open.ts b/src/app/modules/base/controller/admin/open.ts
index b5f0ddd..00e32c0 100644
--- a/src/app/modules/base/controller/admin/open.ts
+++ b/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));
+   }     
+
 }
diff --git a/src/app/modules/base/controller/app/comm.ts b/src/app/modules/base/controller/app/comm.ts
index cee1e68..f310209 100644
--- a/src/app/modules/base/controller/app/comm.ts
+++ b/src/app/modules/base/controller/app/comm.ts
@@ -50,4 +50,5 @@
   async uploadMode() {
     return this.ok(this.coolFile.getMode());
   }
+  
 }
diff --git a/src/app/modules/base/service/dataapi/dataapi.ts b/src/app/modules/base/service/dataapi/dataapi.ts
new file mode 100644
index 0000000..eeef886
--- /dev/null
+++ b/src/app/modules/base/service/dataapi/dataapi.ts
@@ -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);
+  }
+
+
+}
diff --git a/src/app/modules/base/utils/arrayutil.ts b/src/app/modules/base/utils/arrayutil.ts
new file mode 100644
index 0000000..be87da1
--- /dev/null
+++ b/src/app/modules/base/utils/arrayutil.ts
@@ -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 ''
+        }
+    }
+
+}
diff --git a/src/app/modules/base/utils/dateutil.ts b/src/app/modules/base/utils/dateutil.ts
new file mode 100644
index 0000000..b06330b
--- /dev/null
+++ b/src/app/modules/base/utils/dateutil.ts
@@ -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
+    }
+
+}
diff --git a/src/app/modules/base/utils/mysqlutil.ts b/src/app/modules/base/utils/mysqlutil.ts
new file mode 100644
index 0000000..932f0aa
--- /dev/null
+++ b/src/app/modules/base/utils/mysqlutil.ts
@@ -0,0 +1,92 @@
+import { Provide } from "@midwayjs/decorator"
+
+@Provide()
+export class MysqlUtil {
+
+    /**
+     * 鐢熸垚select璇彞 [sql_count銆乻ql]
+     * @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銆乻ql]
+     * @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銆乻ql
+     * @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;
+      }
+
+}
\ No newline at end of file

--
Gitblit v1.9.1