@hlw-midway/core 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +4 -0
  2. package/dist/bin/check.d.ts +4 -0
  3. package/dist/bin/check.js +41 -0
  4. package/dist/bin/entity.d.ts +8 -0
  5. package/dist/bin/entity.js +50 -0
  6. package/dist/bin/index.d.ts +2 -0
  7. package/dist/bin/index.js +49 -0
  8. package/dist/bin/obfuscate.d.ts +1 -0
  9. package/dist/bin/obfuscate.js +69 -0
  10. package/dist/cache/store.d.ts +18 -0
  11. package/dist/cache/store.js +38 -0
  12. package/dist/config/config.default.d.ts +8 -0
  13. package/dist/config/config.default.js +22 -0
  14. package/dist/configuration.d.ts +17 -0
  15. package/dist/configuration.js +106 -0
  16. package/dist/constant/global.d.ts +59 -0
  17. package/dist/constant/global.js +85 -0
  18. package/dist/controller/base.d.ts +107 -0
  19. package/dist/controller/base.js +236 -0
  20. package/dist/decorator/cache.d.ts +2 -0
  21. package/dist/decorator/cache.js +10 -0
  22. package/dist/decorator/controller.d.ts +71 -0
  23. package/dist/decorator/controller.js +169 -0
  24. package/dist/decorator/event.d.ts +21 -0
  25. package/dist/decorator/event.js +39 -0
  26. package/dist/decorator/index.d.ts +22 -0
  27. package/dist/decorator/index.js +120 -0
  28. package/dist/decorator/tag.d.ts +22 -0
  29. package/dist/decorator/tag.js +40 -0
  30. package/dist/decorator/transaction.d.ts +8 -0
  31. package/dist/decorator/transaction.js +10 -0
  32. package/dist/entity/base.d.ts +10 -0
  33. package/dist/entity/base.js +41 -0
  34. package/dist/entity/mongo.d.ts +10 -0
  35. package/dist/entity/mongo.js +35 -0
  36. package/dist/entity/typeorm.d.ts +3 -0
  37. package/dist/entity/typeorm.js +7 -0
  38. package/dist/event/index.d.ts +53 -0
  39. package/dist/event/index.js +188 -0
  40. package/dist/exception/base.d.ts +8 -0
  41. package/dist/exception/base.js +15 -0
  42. package/dist/exception/comm.d.ts +7 -0
  43. package/dist/exception/comm.js +15 -0
  44. package/dist/exception/core.d.ts +7 -0
  45. package/dist/exception/core.js +15 -0
  46. package/dist/exception/filter.d.ts +11 -0
  47. package/dist/exception/filter.js +42 -0
  48. package/dist/exception/validate.d.ts +7 -0
  49. package/dist/exception/validate.js +15 -0
  50. package/dist/index.d.ts +31 -0
  51. package/dist/index.js +60 -0
  52. package/dist/interface.d.ts +432 -0
  53. package/dist/interface.js +24 -0
  54. package/dist/module/config.d.ts +21 -0
  55. package/dist/module/config.js +109 -0
  56. package/dist/module/import.d.ts +64 -0
  57. package/dist/module/import.js +244 -0
  58. package/dist/module/menu.d.ts +54 -0
  59. package/dist/module/menu.js +178 -0
  60. package/dist/rest/eps.d.ts +51 -0
  61. package/dist/rest/eps.js +269 -0
  62. package/dist/service/base.d.ts +167 -0
  63. package/dist/service/base.js +281 -0
  64. package/dist/service/mysql.d.ts +143 -0
  65. package/dist/service/mysql.js +524 -0
  66. package/dist/service/postgres.d.ts +160 -0
  67. package/dist/service/postgres.js +639 -0
  68. package/dist/service/sqlite.d.ts +142 -0
  69. package/dist/service/sqlite.js +560 -0
  70. package/dist/tag/data.d.ts +25 -0
  71. package/dist/tag/data.js +85 -0
  72. package/dist/util/func.d.ts +8 -0
  73. package/dist/util/func.js +44 -0
  74. package/dist/util/location.d.ts +26 -0
  75. package/dist/util/location.js +113 -0
  76. package/index.d.ts +10 -0
  77. package/package.json +68 -0
@@ -0,0 +1,142 @@
1
+ import { Application, Context } from '@midwayjs/koa';
2
+ import { TypeORMDataSourceManager } from '@midwayjs/typeorm';
3
+ import { Repository, SelectQueryBuilder } from 'typeorm';
4
+ import { QueryOp } from '../decorator/controller';
5
+ import { HlwEventManager } from '../event';
6
+ /**
7
+ * 服务基类
8
+ */
9
+ export declare abstract class BaseSqliteService {
10
+ private _hlwConfig;
11
+ entity: Repository<any>;
12
+ sqlParams: any;
13
+ typeORMDataSourceManager: TypeORMDataSourceManager;
14
+ hlwEventManager: HlwEventManager;
15
+ allConfig: any;
16
+ setEntity(entity: any): void;
17
+ setCtx(ctx: Context): void;
18
+ baseApp: Application;
19
+ setApp(app: Application): void;
20
+ baseCtx: Context;
21
+ init(): void;
22
+ /**
23
+ * 设置sql
24
+ * @param condition 条件是否成立
25
+ * @param sql sql语句
26
+ * @param params 参数
27
+ */
28
+ setSql(condition: any, sql: any, params: any): any;
29
+ /**
30
+ * 获得查询个数的SQL
31
+ * @param sql
32
+ */
33
+ getCountSql(sql: any): string;
34
+ /**
35
+ * 参数安全性检查
36
+ * @param params
37
+ */
38
+ paramSafetyCheck(params: any): Promise<boolean>;
39
+ /**
40
+ * 原生查询
41
+ * @param sql
42
+ * @param params
43
+ * @param connectionName
44
+ */
45
+ nativeQuery(sql: any, params?: any, connectionName?: any): Promise<any>;
46
+ /**
47
+ * 获得ORM管理
48
+ * @param connectionName 连接名称
49
+ */
50
+ getOrmManager(connectionName?: string): import("typeorm").DataSource;
51
+ /**
52
+ * 操作entity获得分页数据,不用写sql
53
+ * @param find QueryBuilder
54
+ * @param query
55
+ * @param autoSort
56
+ * @param connectionName
57
+ */
58
+ entityRenderPage(find: SelectQueryBuilder<any>, query: any, autoSort?: boolean): Promise<{
59
+ list: any[];
60
+ pagination: {
61
+ page: number;
62
+ size: number;
63
+ total: number;
64
+ };
65
+ }>;
66
+ /**
67
+ * 执行SQL并获得分页数据
68
+ * @param sql 执行的sql语句
69
+ * @param query 分页查询条件
70
+ * @param autoSort 是否自动排序
71
+ * @param connectionName 连接名称
72
+ */
73
+ sqlRenderPage(sql: any, query: any, autoSort?: boolean, connectionName?: any): Promise<{
74
+ list: any;
75
+ pagination: {
76
+ page: number;
77
+ size: number;
78
+ total: number;
79
+ };
80
+ }>;
81
+ /**
82
+ * 检查排序
83
+ * @param sort 排序
84
+ * @returns
85
+ */
86
+ checkSort(sort: any): any;
87
+ /**
88
+ * 获得单个ID
89
+ * @param id ID
90
+ * @param infoIgnoreProperty 忽略返回属性
91
+ */
92
+ info(id: any, infoIgnoreProperty?: string[]): Promise<any>;
93
+ /**
94
+ * 删除
95
+ * @param ids 删除的ID集合 如:[1,2,3] 或者 1,2,3
96
+ */
97
+ delete(ids: any): Promise<void>;
98
+ /**
99
+ * 软删除
100
+ * @param ids 删除的ID数组
101
+ * @param entity 实体
102
+ */
103
+ softDelete(ids: number[], entity?: Repository<any>): Promise<void>;
104
+ /**
105
+ * 根据时区偏移获取日期
106
+ * @param timezone 时区偏移,格式如 '+08:00', '-07:00'
107
+ * @returns Date
108
+ */
109
+ getDateWithTimezone(): Date;
110
+ /**
111
+ * 新增|修改
112
+ * @param param 数据
113
+ */
114
+ addOrUpdate(param: any | any[], type?: 'add' | 'update'): Promise<void>;
115
+ /**
116
+ * 非分页查询
117
+ * @param query 查询条件
118
+ * @param option 查询配置
119
+ * @param connectionName 连接名
120
+ */
121
+ list(query: any, option: any, connectionName?: any): Promise<any>;
122
+ /**
123
+ * 分页查询
124
+ * @param query 查询条件
125
+ * @param option 查询配置
126
+ * @param connectionName 连接名
127
+ */
128
+ page(query: any, option: any, connectionName?: any): Promise<{
129
+ list: any;
130
+ pagination: {
131
+ page: number;
132
+ size: number;
133
+ total: number;
134
+ };
135
+ }>;
136
+ /**
137
+ * 构建查询配置
138
+ * @param query 前端查询
139
+ * @param option
140
+ */
141
+ getOptionFind(query: any, option: QueryOp): Promise<string>;
142
+ }
@@ -0,0 +1,560 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.BaseSqliteService = void 0;
13
+ const core_1 = require("@midwayjs/core");
14
+ const core_2 = require("@midwayjs/core");
15
+ const validate_1 = require("../exception/validate");
16
+ const global_1 = require("../constant/global");
17
+ const SqlString = require("sqlstring");
18
+ const typeorm_1 = require("@midwayjs/typeorm");
19
+ const typeorm_2 = require("typeorm");
20
+ const _ = require("lodash");
21
+ const event_1 = require("../event");
22
+ const moment = require("moment");
23
+ /**
24
+ * 服务基类
25
+ */
26
+ let BaseSqliteService = class BaseSqliteService {
27
+ // 设置模型
28
+ setEntity(entity) {
29
+ this.entity = entity;
30
+ }
31
+ // 设置请求上下文
32
+ setCtx(ctx) {
33
+ this.baseCtx = ctx;
34
+ }
35
+ // 设置应用对象
36
+ setApp(app) {
37
+ this.baseApp = app;
38
+ }
39
+ // 初始化
40
+ init() {
41
+ this.sqlParams = [];
42
+ }
43
+ /**
44
+ * 设置sql
45
+ * @param condition 条件是否成立
46
+ * @param sql sql语句
47
+ * @param params 参数
48
+ */
49
+ setSql(condition, sql, params) {
50
+ let rSql = false;
51
+ if (condition || condition === 0) {
52
+ rSql = true;
53
+ for (let i = 0; i < params.length; i++) {
54
+ const param = params[i];
55
+ if (param instanceof Array) {
56
+ // 将这个? 替换成 $1,$2,$3
57
+ const replaceStr = [];
58
+ for (let j = 0; j < param.length; j++) {
59
+ replaceStr.push('$' + (this.sqlParams.length + j + 1));
60
+ }
61
+ this.sqlParams = this.sqlParams.concat(...params);
62
+ sql = sql.replace('?', replaceStr.join(','));
63
+ }
64
+ else {
65
+ sql = sql.replace('?', '$' + (this.sqlParams.length + 1));
66
+ this.sqlParams.push(param);
67
+ }
68
+ }
69
+ }
70
+ return (rSql ? sql : '').replace(/\$\d+/g, '?');
71
+ }
72
+ /**
73
+ * 获得查询个数的SQL
74
+ * @param sql
75
+ */
76
+ getCountSql(sql) {
77
+ sql = sql
78
+ .replace(new RegExp('LIMIT', 'gm'), 'limit ')
79
+ .replace(new RegExp('\n', 'gm'), ' ');
80
+ if (sql.includes('limit')) {
81
+ const sqlArr = sql.split('limit ');
82
+ sqlArr.pop();
83
+ sql = sqlArr.join('limit ');
84
+ }
85
+ return `select count(*) as count from (${sql}) a`;
86
+ }
87
+ /**
88
+ * 参数安全性检查
89
+ * @param params
90
+ */
91
+ async paramSafetyCheck(params) {
92
+ const lp = params.toLowerCase();
93
+ return !(lp.indexOf('update ') > -1 ||
94
+ lp.indexOf('select ') > -1 ||
95
+ lp.indexOf('delete ') > -1 ||
96
+ lp.indexOf('insert ') > -1);
97
+ }
98
+ /**
99
+ * 原生查询
100
+ * @param sql
101
+ * @param params
102
+ * @param connectionName
103
+ */
104
+ async nativeQuery(sql, params, connectionName) {
105
+ if (_.isEmpty(params)) {
106
+ params = this.sqlParams;
107
+ }
108
+ const newParams = [];
109
+ // sql没处理过?的情况下
110
+ for (const item of params) {
111
+ // 如果是数组,将这个? 替换成 $1,$2,$3
112
+ if (item instanceof Array) {
113
+ const replaceStr = [];
114
+ for (let i = 0; i < item.length; i++) {
115
+ replaceStr.push('$' + (newParams.length + i + 1));
116
+ }
117
+ newParams.push(...item);
118
+ sql = sql.replace('?', replaceStr.join(','));
119
+ }
120
+ else {
121
+ sql = sql.replace('?', '$' + (newParams.length + 1));
122
+ newParams.push(item);
123
+ }
124
+ }
125
+ this.sqlParams = [];
126
+ return await this.getOrmManager(connectionName).query(sql.replace(/\$\d+/g, '?'), newParams || []);
127
+ }
128
+ /**
129
+ * 获得ORM管理
130
+ * @param connectionName 连接名称
131
+ */
132
+ getOrmManager(connectionName = 'default') {
133
+ return this.typeORMDataSourceManager.getDataSource(connectionName);
134
+ }
135
+ /**
136
+ * 操作entity获得分页数据,不用写sql
137
+ * @param find QueryBuilder
138
+ * @param query
139
+ * @param autoSort
140
+ * @param connectionName
141
+ */
142
+ async entityRenderPage(find, query, autoSort = true) {
143
+ const { size = this._hlwConfig.crud.pageSize, page = 1, order = 'id', sort = 'desc', isExport = false, maxExportLimit, } = query;
144
+ const count = await find.getCount();
145
+ let dataFind;
146
+ if (isExport && maxExportLimit > 0) {
147
+ dataFind = find.limit(maxExportLimit);
148
+ }
149
+ else {
150
+ dataFind = find.offset((page - 1) * size).limit(size);
151
+ }
152
+ if (autoSort) {
153
+ find.addOrderBy(order, sort.toUpperCase());
154
+ }
155
+ return {
156
+ list: await dataFind.getRawMany(),
157
+ pagination: {
158
+ page: parseInt(page),
159
+ size: parseInt(size),
160
+ total: count,
161
+ },
162
+ };
163
+ }
164
+ /**
165
+ * 执行SQL并获得分页数据
166
+ * @param sql 执行的sql语句
167
+ * @param query 分页查询条件
168
+ * @param autoSort 是否自动排序
169
+ * @param connectionName 连接名称
170
+ */
171
+ async sqlRenderPage(sql, query, autoSort = true, connectionName) {
172
+ const { size = this._hlwConfig.crud.pageSize, page = 1, order = 'id', sort = 'desc', isExport = false, maxExportLimit, } = query;
173
+ sql = `SELECT * FROM (${sql}) a`;
174
+ if (order && sort && autoSort) {
175
+ if (!(await this.paramSafetyCheck(order + sort))) {
176
+ throw new validate_1.HlwValidateException('非法传参~');
177
+ }
178
+ sql += ` ORDER BY a.${SqlString.escapeId(order)} ${this.checkSort(sort)}`;
179
+ }
180
+ let cutParams = 0;
181
+ if (isExport && maxExportLimit > 0) {
182
+ this.sqlParams.push(parseInt(maxExportLimit));
183
+ cutParams = 1;
184
+ sql += ' LIMIT ? ';
185
+ }
186
+ if (!isExport) {
187
+ this.sqlParams.push((page - 1) * size);
188
+ this.sqlParams.push(parseInt(size));
189
+ cutParams = 2;
190
+ sql += ' LIMIT ?,? ';
191
+ }
192
+ let params = [];
193
+ params = params.concat(this.sqlParams);
194
+ const result = await this.nativeQuery(sql, params, connectionName);
195
+ params = params.slice(0, -cutParams);
196
+ const countResult = await this.nativeQuery(this.getCountSql(sql), params, connectionName);
197
+ return {
198
+ list: result,
199
+ pagination: {
200
+ page: parseInt(page),
201
+ size: parseInt(size),
202
+ total: parseInt(countResult[0] ? countResult[0].count : 0),
203
+ },
204
+ };
205
+ }
206
+ /**
207
+ * 检查排序
208
+ * @param sort 排序
209
+ * @returns
210
+ */
211
+ checkSort(sort) {
212
+ if (!['desc', 'asc'].includes(sort.toLowerCase())) {
213
+ throw new validate_1.HlwValidateException('sort 非法传参~');
214
+ }
215
+ return sort;
216
+ }
217
+ /**
218
+ * 获得单个ID
219
+ * @param id ID
220
+ * @param infoIgnoreProperty 忽略返回属性
221
+ */
222
+ async info(id, infoIgnoreProperty) {
223
+ if (!this.entity)
224
+ throw new validate_1.HlwValidateException(global_1.ERRINFO.NOENTITY);
225
+ if (!id) {
226
+ throw new validate_1.HlwValidateException(global_1.ERRINFO.NOID);
227
+ }
228
+ const info = await this.entity.findOneBy({ id });
229
+ if (info && infoIgnoreProperty) {
230
+ for (const property of infoIgnoreProperty) {
231
+ delete info[property];
232
+ }
233
+ }
234
+ return info;
235
+ }
236
+ /**
237
+ * 删除
238
+ * @param ids 删除的ID集合 如:[1,2,3] 或者 1,2,3
239
+ */
240
+ async delete(ids) {
241
+ var _a;
242
+ if (!this.entity)
243
+ throw new validate_1.HlwValidateException(global_1.ERRINFO.NOENTITY);
244
+ if (ids instanceof String) {
245
+ ids = ids.split(',');
246
+ }
247
+ // 启动软删除发送事件
248
+ if ((_a = this._hlwConfig.crud) === null || _a === void 0 ? void 0 : _a.softDelete) {
249
+ this.softDelete(ids);
250
+ }
251
+ await this.entity.delete(ids);
252
+ }
253
+ /**
254
+ * 软删除
255
+ * @param ids 删除的ID数组
256
+ * @param entity 实体
257
+ */
258
+ async softDelete(ids, entity) {
259
+ const data = await this.entity.find({
260
+ where: {
261
+ id: (0, typeorm_2.In)(ids),
262
+ },
263
+ });
264
+ if (_.isEmpty(data))
265
+ return;
266
+ const _entity = entity ? entity : this.entity;
267
+ const params = {
268
+ data,
269
+ ctx: this.baseCtx,
270
+ entity: _entity,
271
+ };
272
+ if (data.length > 0) {
273
+ this.hlwEventManager.emit(global_1.EVENT.SOFT_DELETE, params);
274
+ }
275
+ }
276
+ /**
277
+ * 根据时区偏移获取日期
278
+ * @param timezone 时区偏移,格式如 '+08:00', '-07:00'
279
+ * @returns Date
280
+ */
281
+ getDateWithTimezone() {
282
+ var _a, _b, _c;
283
+ const timezone = ((_c = (_b = (_a = this.allConfig.typeorm) === null || _a === void 0 ? void 0 : _a.dataSource) === null || _b === void 0 ? void 0 : _b.default) === null || _c === void 0 ? void 0 : _c.timezone) || '+08:00';
284
+ const match = timezone.match(/^([+-])(\d{2}):(\d{2})$/);
285
+ if (!match) {
286
+ throw new validate_1.HlwValidateException('时区格式错误,应为 "+08:00" 这样的格式');
287
+ }
288
+ const [_, sign, hours, minutes] = match;
289
+ const offsetInMinutes = (parseInt(hours) * 60 + parseInt(minutes)) * (sign === '+' ? 1 : -1);
290
+ const date = new Date();
291
+ const utc = date.getTime() + date.getTimezoneOffset() * 60000;
292
+ return new Date(utc + offsetInMinutes * 60000);
293
+ }
294
+ /**
295
+ * 新增|修改
296
+ * @param param 数据
297
+ */
298
+ async addOrUpdate(param, type = 'add') {
299
+ var _a;
300
+ if (!this.entity)
301
+ throw new validate_1.HlwValidateException(global_1.ERRINFO.NOENTITY);
302
+ delete param.createdAt;
303
+ // 判断是否是批量操作
304
+ if (param instanceof Array) {
305
+ param.forEach(item => {
306
+ // 设置时区+08:00
307
+ item.updatedAt = new Date();
308
+ if (type == 'add') {
309
+ item.createdAt = new Date();
310
+ }
311
+ });
312
+ await this.entity.save(param);
313
+ }
314
+ else {
315
+ const upsert = ((_a = this._hlwConfig.crud) === null || _a === void 0 ? void 0 : _a.upsert) || 'normal';
316
+ if (type == 'update') {
317
+ if (upsert == 'save') {
318
+ const info = await this.entity.findOneBy({ id: (0, typeorm_2.Equal)(param.id) });
319
+ if (!info) {
320
+ throw new validate_1.HlwValidateException(global_1.ERRINFO.NOTFOUND);
321
+ }
322
+ param = {
323
+ ...info,
324
+ ...param,
325
+ };
326
+ }
327
+ param.updatedAt = new Date();
328
+ upsert == 'normal'
329
+ ? await this.entity.update(param.id, param)
330
+ : await this.entity.save(param);
331
+ }
332
+ if (type == 'add') {
333
+ param.createdAt = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
334
+ param.updatedAt = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
335
+ upsert == 'normal'
336
+ ? await this.entity.insert(param)
337
+ : await this.entity.save(param);
338
+ }
339
+ }
340
+ }
341
+ /**
342
+ * 非分页查询
343
+ * @param query 查询条件
344
+ * @param option 查询配置
345
+ * @param connectionName 连接名
346
+ */
347
+ async list(query, option, connectionName) {
348
+ if (!this.entity)
349
+ throw new validate_1.HlwValidateException(global_1.ERRINFO.NOENTITY);
350
+ const sql = await this.getOptionFind(query, option);
351
+ return this.nativeQuery(sql, [], connectionName);
352
+ }
353
+ /**
354
+ * 分页查询
355
+ * @param query 查询条件
356
+ * @param option 查询配置
357
+ * @param connectionName 连接名
358
+ */
359
+ async page(query, option, connectionName) {
360
+ if (!this.entity)
361
+ throw new validate_1.HlwValidateException(global_1.ERRINFO.NOENTITY);
362
+ const sql = await this.getOptionFind(query, option);
363
+ return this.sqlRenderPage(sql, query, false, connectionName);
364
+ }
365
+ /**
366
+ * 构建查询配置
367
+ * @param query 前端查询
368
+ * @param option
369
+ */
370
+ async getOptionFind(query, option) {
371
+ let { order = 'id', sort = 'desc', keyWord = '' } = query;
372
+ const sqlArr = ['SELECT'];
373
+ const selects = ['a.*'];
374
+ const find = this.entity.createQueryBuilder('a');
375
+ if (option) {
376
+ if (typeof option === 'function') {
377
+ // @ts-ignore
378
+ option = await option(this.baseCtx, this.baseApp);
379
+ }
380
+ // 判断是否有关联查询,有的话取个别名
381
+ if (!_.isEmpty(option.join)) {
382
+ for (const item of option.join) {
383
+ selects.push(`${item.alias}.*`);
384
+ find[item.type || 'leftJoin'](item.entity, item.alias, item.condition);
385
+ }
386
+ }
387
+ // 默认条件
388
+ if (option.where) {
389
+ const wheres = typeof option.where === 'function'
390
+ ? await option.where(this.baseCtx, this.baseApp)
391
+ : option.where;
392
+ if (!_.isEmpty(wheres)) {
393
+ for (const item of wheres) {
394
+ if (item.length == 2 ||
395
+ (item.length == 3 && (item[2] || item[2] === 0))) {
396
+ for (const key in item[1]) {
397
+ this.sqlParams.push(item[1][key]);
398
+ }
399
+ find.andWhere(item[0], item[1]);
400
+ }
401
+ }
402
+ }
403
+ }
404
+ // 附加排序
405
+ if (!_.isEmpty(option.addOrderBy)) {
406
+ for (const key in option.addOrderBy) {
407
+ if (order && order == key) {
408
+ sort = option.addOrderBy[key].toUpperCase();
409
+ }
410
+ find.addOrderBy(SqlString.escapeId(key), this.checkSort(option.addOrderBy[key].toUpperCase()));
411
+ }
412
+ }
413
+ // 关键字模糊搜索
414
+ if (keyWord || keyWord === 0) {
415
+ keyWord = `%${keyWord}%`;
416
+ find.andWhere(new typeorm_2.Brackets(qb => {
417
+ var _a;
418
+ const keyWordLikeFields = option.keyWordLikeFields || [];
419
+ for (let i = 0; i < ((_a = option.keyWordLikeFields) === null || _a === void 0 ? void 0 : _a.length) || 0; i++) {
420
+ qb.orWhere(`${keyWordLikeFields[i]} like :keyWord`, {
421
+ keyWord,
422
+ });
423
+ this.sqlParams.push(keyWord);
424
+ }
425
+ }));
426
+ }
427
+ // 筛选字段
428
+ if (!_.isEmpty(option.select)) {
429
+ sqlArr.push(option.select.join(','));
430
+ find.select(option.select);
431
+ }
432
+ else {
433
+ sqlArr.push(selects.join(','));
434
+ }
435
+ // 字段全匹配
436
+ if (!_.isEmpty(option.fieldEq)) {
437
+ for (let key of option.fieldEq) {
438
+ const c = {};
439
+ // 如果key有包含.的情况下操作
440
+ if (typeof key === 'string' && key.includes('.')) {
441
+ const keys = key.split('.');
442
+ const lastKey = keys.pop();
443
+ key = { requestParam: lastKey, column: key };
444
+ }
445
+ // 单表字段无别名的情况下操作
446
+ if (typeof key === 'string') {
447
+ if (query[key] || query[key] == 0) {
448
+ c[key] = query[key];
449
+ const eq = query[key] instanceof Array ? 'in' : '=';
450
+ if (eq === 'in') {
451
+ find.andWhere(`${key} ${eq} (:${key})`, c);
452
+ }
453
+ else {
454
+ find.andWhere(`${key} ${eq} :${key}`, c);
455
+ }
456
+ // this.sqlParams.push(query[key]);
457
+ }
458
+ }
459
+ else {
460
+ if (query[key.requestParam] || query[key.requestParam] == 0) {
461
+ c[key.column] = query[key.requestParam];
462
+ const eq = query[key.requestParam] instanceof Array ? 'in' : '=';
463
+ if (eq === 'in') {
464
+ find.andWhere(`${key.column} ${eq} (:${key.column})`, c);
465
+ }
466
+ else {
467
+ find.andWhere(`${key.column} ${eq} :${key.column}`, c);
468
+ }
469
+ }
470
+ }
471
+ }
472
+ }
473
+ // 字段模糊查询
474
+ if (!_.isEmpty(option.fieldLike)) {
475
+ for (let key of option.fieldLike) {
476
+ // 如果key有包含.的情况下操作
477
+ if (typeof key === 'string' && key.includes('.')) {
478
+ const keys = key.split('.');
479
+ const lastKey = keys.pop();
480
+ key = { requestParam: lastKey, column: key };
481
+ }
482
+ // 单表字段无别名的情况下操作
483
+ if (typeof key === 'string') {
484
+ if (query[key] || query[key] == 0) {
485
+ find.andWhere(`${key} like :${key}`, {
486
+ [key]: `%${query[key]}%`,
487
+ });
488
+ this.sqlParams.push(`%${query[key]}%`);
489
+ }
490
+ }
491
+ else {
492
+ if (query[key.requestParam] || query[key.requestParam] == 0) {
493
+ find.andWhere(`${key.column} like :${key.column}`, {
494
+ [key.column]: `%${query[key.requestParam]}%`,
495
+ });
496
+ this.sqlParams.push(`%${query[key.requestParam]}%`);
497
+ }
498
+ }
499
+ }
500
+ }
501
+ }
502
+ else {
503
+ sqlArr.push(selects.join(','));
504
+ }
505
+ // 接口请求的排序
506
+ if (sort && order) {
507
+ const sorts = sort.toUpperCase().split(',');
508
+ const orders = order.split(',');
509
+ if (sorts.length != orders.length) {
510
+ throw new validate_1.HlwValidateException(global_1.ERRINFO.SORTFIELD);
511
+ }
512
+ for (const i in sorts) {
513
+ find.addOrderBy(SqlString.escapeId(orders[i]), this.checkSort(sorts[i]));
514
+ }
515
+ }
516
+ if (option === null || option === void 0 ? void 0 : option.extend) {
517
+ await (option === null || option === void 0 ? void 0 : option.extend(find, this.baseCtx, this.baseApp));
518
+ }
519
+ const sqls = find.getSql().split('FROM');
520
+ sqlArr.push('FROM');
521
+ // 取sqls的最后一个
522
+ sqlArr.push(sqls[sqls.length - 1]);
523
+ return sqlArr.join(' ');
524
+ }
525
+ };
526
+ exports.BaseSqliteService = BaseSqliteService;
527
+ __decorate([
528
+ (0, core_1.Config)('hlw'),
529
+ __metadata("design:type", Object)
530
+ ], BaseSqliteService.prototype, "_hlwConfig", void 0);
531
+ __decorate([
532
+ (0, core_1.Inject)(),
533
+ __metadata("design:type", typeorm_1.TypeORMDataSourceManager)
534
+ ], BaseSqliteService.prototype, "typeORMDataSourceManager", void 0);
535
+ __decorate([
536
+ (0, core_1.Inject)(),
537
+ __metadata("design:type", event_1.HlwEventManager)
538
+ ], BaseSqliteService.prototype, "hlwEventManager", void 0);
539
+ __decorate([
540
+ (0, core_1.Config)(core_1.ALL),
541
+ __metadata("design:type", Object)
542
+ ], BaseSqliteService.prototype, "allConfig", void 0);
543
+ __decorate([
544
+ (0, core_1.App)(),
545
+ __metadata("design:type", Object)
546
+ ], BaseSqliteService.prototype, "baseApp", void 0);
547
+ __decorate([
548
+ (0, core_1.Inject)('ctx'),
549
+ __metadata("design:type", Object)
550
+ ], BaseSqliteService.prototype, "baseCtx", void 0);
551
+ __decorate([
552
+ (0, core_1.Init)(),
553
+ __metadata("design:type", Function),
554
+ __metadata("design:paramtypes", []),
555
+ __metadata("design:returntype", void 0)
556
+ ], BaseSqliteService.prototype, "init", null);
557
+ exports.BaseSqliteService = BaseSqliteService = __decorate([
558
+ (0, core_1.Provide)(),
559
+ (0, core_2.Scope)(core_2.ScopeEnum.Request, { allowDowngrade: true })
560
+ ], BaseSqliteService);