typespeed 2.5.0 → 2.5.1

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 (94) hide show
  1. package/CHANGELOG.md +1 -0
  2. package/dist/default/rabbitmq.class.js +18 -1
  3. package/dist/default/redis.class.js +14 -1
  4. package/dist/default/socket-io.class.js +53 -4
  5. package/dist/typespeed.d.ts +7 -7
  6. package/package.json +6 -2
  7. package/.github/workflows/test.yml +0 -50
  8. package/app/nodemon.json +0 -5
  9. package/app/package.json +0 -17
  10. package/app/src/aop-test.class.ts +0 -29
  11. package/app/src/config-development.json +0 -26
  12. package/app/src/config-production.json +0 -15
  13. package/app/src/config.json +0 -50
  14. package/app/src/custom-log.class.ts +0 -33
  15. package/app/src/entities/mutil-users.class.ts +0 -5
  16. package/app/src/entities/user-dto.class.ts +0 -3
  17. package/app/src/first-page.class.ts +0 -46
  18. package/app/src/jwt-authentication.class.ts +0 -30
  19. package/app/src/main.ts +0 -24
  20. package/app/src/second-page.class.ts +0 -43
  21. package/app/src/test-bind.class.ts +0 -41
  22. package/app/src/test-database.class.ts +0 -81
  23. package/app/src/test-log.class.ts +0 -11
  24. package/app/src/test-mq.class.ts +0 -21
  25. package/app/src/test-orm.class.ts +0 -63
  26. package/app/src/test-redis.class.ts +0 -45
  27. package/app/src/test-request.class.ts +0 -37
  28. package/app/src/test-socket.class.ts +0 -56
  29. package/app/src/user-model.class.ts +0 -50
  30. package/app/src/views/index.html +0 -1
  31. package/app/src/views/socket.html +0 -23
  32. package/app/src/views/upload.html +0 -14
  33. package/app/static/favicon.ico +0 -0
  34. package/app/static/k.jpg +0 -0
  35. package/app/tsconfig.json +0 -20
  36. package/introduction/decorator/example-import.class.ts +0 -6
  37. package/introduction/decorator/main-app.ts +0 -6
  38. package/introduction/decorator/main-decorator.ts +0 -108
  39. package/introduction/decorator/main-import.ts +0 -1
  40. package/introduction/decorator/main-reflect.ts +0 -25
  41. package/introduction/decorator-next/dist/main.js +0 -116
  42. package/introduction/decorator-next/package.json +0 -14
  43. package/introduction/decorator-next/src/main.ts +0 -64
  44. package/introduction/decorator-next/tsconfig.json +0 -17
  45. package/introduction/decorator-next//346/225/231/347/250/213.md +0 -384
  46. package/introduction/tsconfig.json +0 -23
  47. package/introduction/web-services/db-init.ts +0 -39
  48. package/introduction/web-services/db-singleton.ts +0 -59
  49. package/introduction/web-services/http-if.ts +0 -10
  50. package/introduction/web-services/http-init.ts +0 -6
  51. package/introduction/web-services/http-router.ts +0 -28
  52. package/src/bind.decorator.ts +0 -50
  53. package/src/core.decorator.ts +0 -184
  54. package/src/database.decorator.ts +0 -446
  55. package/src/decorator-utils.ts +0 -53
  56. package/src/default/default-authentication.class.ts +0 -10
  57. package/src/default/express-server.class.ts +0 -150
  58. package/src/default/log-default.class.ts +0 -9
  59. package/src/default/node-cache.class.ts +0 -40
  60. package/src/default/pages/404.html +0 -226
  61. package/src/default/pages/500.html +0 -713
  62. package/src/default/rabbitmq.class.ts +0 -61
  63. package/src/default/read-write-db.class.ts +0 -53
  64. package/src/default/redis.class.ts +0 -79
  65. package/src/default/socket-io.class.ts +0 -81
  66. package/src/factory/authentication-factory.class.ts +0 -9
  67. package/src/factory/cache-factory.class.ts +0 -7
  68. package/src/factory/data-source-factory.class.ts +0 -4
  69. package/src/factory/log-factory.class.ts +0 -8
  70. package/src/factory/server-factory.class.ts +0 -6
  71. package/src/route.decorator.ts +0 -334
  72. package/src/scaffold/command.ts +0 -40
  73. package/src/scaffold/templates/front-page.class.ts.tpl +0 -12
  74. package/src/scaffold/templates/main.ts.tpl +0 -13
  75. package/src/scaffold/templates/nodemon.json.tpl +0 -7
  76. package/src/scaffold/templates/package.json.tpl +0 -16
  77. package/src/scaffold/templates/tsconfig.json.tpl +0 -17
  78. package/src/typespeed.d.ts +0 -403
  79. package/src/typespeed.ts +0 -139
  80. package/test/bind.test.ts +0 -28
  81. package/test/database.test.ts +0 -76
  82. package/test/decorator-utils.test.ts +0 -42
  83. package/test/first-page.test.ts +0 -42
  84. package/test/hooks.ts +0 -13
  85. package/test/mq.test.ts +0 -17
  86. package/test/orm.test.ts +0 -66
  87. package/test/redis.test.ts +0 -48
  88. package/test/request.test.ts +0 -51
  89. package/test/second-page.test.ts +0 -50
  90. package/test/socket.test.ts +0 -60
  91. package/test-env/docker-compose.test.yml +0 -31
  92. package/test-env/mysql-init/init.sql +0 -8
  93. package/test-env//346/234/254/345/234/260Docker/346/265/213/350/257/225/346/226/271/346/241/210.md +0 -69
  94. package/tsconfig.json +0 -25
@@ -1,446 +0,0 @@
1
- import { ResultSetHeader } from 'mysql2';
2
- import { log, getBean } from './core.decorator';
3
- import { isStd, getStdArgs } from './decorator-utils';
4
- import { getBindMapping } from './bind.decorator';
5
- import CacheFactory from './factory/cache-factory.class';
6
- import DataSourceFactory from './factory/data-source-factory.class';
7
-
8
- const paramMetadataKey = Symbol('param');
9
- const resultTypeMap = new Map<string, object>();
10
- const cacheDefindMap = new Map<string, number>();
11
- const tableVersionMap = new Map<string, number>();
12
- let cacheBean: CacheFactory;
13
-
14
- function insert(sql: string) {
15
- return (...args: any[]): any => {
16
- if (isStd(args)) {
17
- const [, ctx] = getStdArgs(args);
18
- const propertyKey = String(ctx.name);
19
- return async function (this: any, ...callArgs: any[]) {
20
- const result: ResultSetHeader = await queryForExecute(sql, callArgs, this, propertyKey);
21
- if (cacheBean && result.affectedRows > 0) {
22
- const [tableName, tableVersion] = getTableAndVersion("insert", sql);
23
- tableVersionMap.set(tableName, tableVersion + 1);
24
- }
25
- return result.insertId;
26
- };
27
- }
28
- const target = args[0];
29
- const propertyKey = args[1] as string;
30
- const descriptor = args[2] as PropertyDescriptor;
31
- descriptor.value = async (...callArgs: any[]) => {
32
- const result: ResultSetHeader = await queryForExecute(sql, callArgs, target, propertyKey);
33
- if (cacheBean && result.affectedRows > 0) {
34
- const [tableName, tableVersion] = getTableAndVersion("insert", sql);
35
- tableVersionMap.set(tableName, tableVersion + 1);
36
- }
37
- return result.insertId;
38
- };
39
- };
40
- }
41
-
42
- function update(sql: string) {
43
- return (...args: any[]): any => {
44
- if (isStd(args)) {
45
- const [, ctx] = getStdArgs(args);
46
- const propertyKey = String(ctx.name);
47
- return async function (this: any, ...callArgs: any[]) {
48
- const result: ResultSetHeader = await queryForExecute(sql, callArgs, this, propertyKey);
49
- if (cacheBean && result.affectedRows > 0) {
50
- const [tableName, tableVersion] = getTableAndVersion("update", sql);
51
- tableVersionMap.set(tableName, tableVersion + 1);
52
- }
53
- return result.affectedRows;
54
- };
55
- }
56
- const target = args[0];
57
- const propertyKey = args[1] as string;
58
- const descriptor = args[2] as PropertyDescriptor;
59
- descriptor.value = async (...callArgs: any[]) => {
60
- const result: ResultSetHeader = await queryForExecute(sql, callArgs, target, propertyKey);
61
- if (cacheBean && result.affectedRows > 0) {
62
- const [tableName, tableVersion] = getTableAndVersion("update", sql);
63
- tableVersionMap.set(tableName, tableVersion + 1);
64
- }
65
- return result.affectedRows;
66
- };
67
- };
68
- }
69
-
70
- function remove(sql: string) {
71
- return (...args: any[]): any => {
72
- if (isStd(args)) {
73
- const [, ctx] = getStdArgs(args);
74
- const propertyKey = String(ctx.name);
75
- return async function (this: any, ...callArgs: any[]) {
76
- const result: ResultSetHeader = await queryForExecute(sql, callArgs, this, propertyKey);
77
- if (cacheBean && result.affectedRows > 0) {
78
- const [tableName, tableVersion] = getTableAndVersion("delete", sql);
79
- tableVersionMap.set(tableName, tableVersion + 1);
80
- }
81
- return result.affectedRows;
82
- };
83
- }
84
- const target = args[0];
85
- const propertyKey = args[1] as string;
86
- const descriptor = args[2] as PropertyDescriptor;
87
- descriptor.value = async (...callArgs: any[]) => {
88
- const result: ResultSetHeader = await queryForExecute(sql, callArgs, target, propertyKey);
89
- if (cacheBean && result.affectedRows > 0) {
90
- const [tableName, tableVersion] = getTableAndVersion("delete", sql);
91
- tableVersionMap.set(tableName, tableVersion + 1);
92
- }
93
- return result.affectedRows;
94
- };
95
- };
96
- }
97
-
98
- function select(sql: string) {
99
- return (...args: any[]): any => {
100
- if (isStd(args)) {
101
- const [, ctx] = getStdArgs(args);
102
- const propertyKey = String(ctx.name);
103
- return async function (this: any, ...callArgs: any[]) {
104
- const [newSql, sqlValues] = convertSQLParams(sql, this, propertyKey, callArgs);
105
- const resultType = resultTypeMap.get([this.constructor.name, propertyKey].toString());
106
- if (cacheBean && cacheDefindMap.has([this.constructor.name, propertyKey].toString())) {
107
- const [tableName, tableVersion] = getTableAndVersion("select", newSql);
108
- const cacheKey = JSON.stringify([tableName, tableVersion, newSql, sqlValues]);
109
- if (cacheBean.get(cacheKey)) {
110
- return cacheBean.get(cacheKey);
111
- } else {
112
- const rows = await actionQuery(newSql, sqlValues, resultType);
113
- cacheBean.set(cacheKey, rows, cacheDefindMap.get([this.constructor.name, propertyKey].toString()));
114
- return rows;
115
- }
116
- } else {
117
- return await actionQuery(newSql, sqlValues, resultType);
118
- }
119
- };
120
- }
121
- const target = args[0];
122
- const propertyKey = args[1] as string;
123
- const descriptor = args[2] as PropertyDescriptor;
124
- descriptor.value = async (...callArgs: any[]) => {
125
- const [newSql, sqlValues] = convertSQLParams(sql, target, propertyKey, callArgs);
126
- const resultType = resultTypeMap.get([target.constructor.name, propertyKey].toString());
127
- if (cacheBean && cacheDefindMap.has([target.constructor.name, propertyKey].toString())) {
128
- const [tableName, tableVersion] = getTableAndVersion("select", newSql);
129
- const cacheKey = JSON.stringify([tableName, tableVersion, newSql, sqlValues]);
130
- if (cacheBean.get(cacheKey)) {
131
- return cacheBean.get(cacheKey);
132
- } else {
133
- const rows = await actionQuery(newSql, sqlValues, resultType);
134
- cacheBean.set(cacheKey, rows, cacheDefindMap.get([target.constructor.name, propertyKey].toString()));
135
- return rows;
136
- }
137
- } else {
138
- return await actionQuery(newSql, sqlValues, resultType);
139
- }
140
- };
141
- }
142
- }
143
-
144
- function resultType(dataClass) {
145
- return function (...args: any[]): any {
146
- if (isStd(args)) {
147
- const [, ctx] = getStdArgs(args);
148
- ctx.addInitializer(function (this: any) {
149
- resultTypeMap.set([this.constructor.name, String(ctx.name)].toString(), dataClass);
150
- });
151
- return;
152
- }
153
- const target = args[0];
154
- const propertyKey = args[1] as string;
155
- resultTypeMap.set([target.constructor.name, propertyKey].toString(), dataClass);
156
- //never return
157
- };
158
- }
159
-
160
- function param(name: string) {
161
- return function (target: any, propertyKey: string | symbol, parameterIndex: number) {
162
- const existingParameters: [string, number][] = Reflect.getOwnMetadata(paramMetadataKey, target, propertyKey) || [];
163
- existingParameters.push([name, parameterIndex]);
164
- Reflect.defineMetadata(paramMetadataKey, existingParameters, target, propertyKey);
165
- };
166
- }
167
-
168
- async function queryForExecute(sql: string, args: any[], target, propertyKey: string): Promise<ResultSetHeader> {
169
- const [newSql, sqlValues] = convertSQLParams(sql, target, propertyKey, args);
170
- return actionExecute(newSql, sqlValues);
171
- }
172
-
173
- async function actionExecute(newSql, sqlValues): Promise<ResultSetHeader> {
174
- const writeConnection = await getBean(DataSourceFactory).writeConnection();
175
- const [result] = await writeConnection.query(newSql, sqlValues);
176
- return <ResultSetHeader>result;
177
- }
178
-
179
- async function actionQuery(newSql, sqlValues, dataClassType?) {
180
- const readConnection = await getBean(DataSourceFactory).readConnection();
181
- const [rows] = await readConnection.query(newSql, sqlValues);
182
- if (rows === null || Object.keys(rows).length === 0){
183
- return null;
184
- } else if (!dataClassType) {
185
- return rows;
186
- }
187
- const records = [];
188
- for (const rowIndex in rows) {
189
- const entity = new dataClassType();
190
- Object.getOwnPropertyNames(entity).forEach((propertyRow) => {
191
- if (rows[rowIndex].hasOwnProperty(propertyRow)) {
192
- Object.defineProperty(entity, propertyRow, Object.getOwnPropertyDescriptor(rows[rowIndex], propertyRow));
193
- }
194
- });
195
- records.push(entity);
196
- }
197
- return Object.keys(records).length === 0 ? null : records;
198
- }
199
-
200
- function convertSQLParams(decoratorSQL: string, target: any, propertyKey: string, args: any[]): [string, any[]] {
201
- const queryValues = [];
202
- if (args.length > 0) {
203
- let argsVal;
204
- if (typeof args[0] === 'object') {
205
- argsVal = new Map(Object.getOwnPropertyNames(args[0]).map((valName) => [valName, args[0][valName]]));
206
- } else {
207
- // 优先 @param(legacy reflect-metadata),否则回退 @bind(方法级声明,标准模式)
208
- let existingParameters: [string, number][] = Reflect.getOwnMetadata(paramMetadataKey, target, propertyKey);
209
- if (!existingParameters) {
210
- const bindMapping = getBindMapping(target.constructor.name, propertyKey);
211
- if (bindMapping) {
212
- existingParameters = Object.entries(bindMapping)
213
- .filter(([, value]) => typeof value === "number")
214
- .map(([name, value]) => [name, value as number]);
215
- }
216
- }
217
- argsVal = new Map((existingParameters || []).map(([argName, argIdx]) => [argName, args[argIdx]]));
218
- }
219
- const regExp = /#{(\w+)}/;
220
- let match;
221
- while (match = regExp.exec(decoratorSQL)) {
222
- const [replaceTag, matchName] = match;
223
- decoratorSQL = decoratorSQL.replace(new RegExp(replaceTag, 'g'), '?');
224
- queryValues.push(argsVal.get(matchName));
225
- }
226
- }
227
- return [decoratorSQL, queryValues];
228
- }
229
-
230
- function cache(ttl: number) {
231
- return function (...args: any[]): any {
232
- if (isStd(args)) {
233
- const [, ctx] = getStdArgs(args);
234
- ctx.addInitializer(function (this: any) {
235
- cacheDefindMap.set([this.constructor.name, String(ctx.name)].toString(), ttl);
236
- if (cacheBean == null) {
237
- const cacheFactory = getBean(CacheFactory);
238
- if (cacheFactory || cacheFactory["factory"]) {
239
- cacheBean = cacheFactory["factory"];
240
- }
241
- }
242
- });
243
- return;
244
- }
245
- const target = args[0];
246
- const propertyKey = args[1] as string;
247
- cacheDefindMap.set([target.constructor.name, propertyKey].toString(), ttl);
248
- if (cacheBean == null) {
249
- const cacheFactory = getBean(CacheFactory);
250
- if (cacheFactory || cacheFactory["factory"]) {
251
- cacheBean = cacheFactory["factory"];
252
- }
253
- }
254
- }
255
- }
256
-
257
- function getTableAndVersion(name: string, sql: string): [string, number] {
258
- const regExpMap = {
259
- insert: /insert\sinto\s+([\w`\'\"]+)/i,
260
- update: /update\s+([\w`\'\"]+)/i,
261
- delete: /delete\sfrom\s+([\w`\'\"]+)/i,
262
- select: /\s+from\s+([\w`\'\"]+)/i
263
- }
264
- const macths = sql.match(regExpMap[name]);
265
- if (macths && macths.length > 1) {
266
- const tableName = macths[1].replace(/[`\'\"]/g, "");
267
- const tableVersion = tableVersionMap.get(tableName) || 1;
268
- tableVersionMap.set(tableName, tableVersion);
269
- log(tableVersionMap);
270
- return [tableName, tableVersion];
271
- } else {
272
- throw new Error("can not find table name");
273
- }
274
- }
275
-
276
-
277
- class Model {
278
-
279
- public page = null;
280
- private table: string;
281
-
282
- constructor(table?: string) {
283
- if (table) this.table = table;
284
- }
285
-
286
- async findAll<T>(conditions: object | string, sort: string | object = '', fields: string | [string] = '*', limit?: number | object): Promise<T[]> {
287
- const { sql, values } = this.where(conditions);
288
- if (typeof fields !== 'string') {
289
- fields = fields.join(", ");
290
- }
291
- if (typeof sort !== 'string') {
292
- sort = Object.keys(sort).map(s => {
293
- return s + (sort[s] === 1 ? " ASC" : " DESC");
294
- }).join(", ");
295
- }
296
- let newSql = 'SELECT ' + fields + ' FROM ' + this.table + ' WHERE ' + sql + " ORDER BY " + sort;
297
- if (typeof limit === 'number') {
298
- newSql += ' LIMIT ' + limit
299
- } else if (typeof limit === 'object') {
300
- const total = await actionQuery('SELECT COUNT(*) AS M_COUNTER FROM ' + this.table + ' WHERE ' + sql, values);
301
- if (total === null || total[0] === undefined || total[0]['M_COUNTER'] === 0) {
302
- return [];
303
- }
304
- if (limit['pageSize'] !== undefined && limit['pageSize'] < total[0]['M_COUNTER']) {
305
- const pager = this.pager(limit["page"] || 1, total[0]['M_COUNTER'], limit["pageSize"] || 10, limit["scope"] || 10);
306
- newSql += ' LIMIT ' + pager['offset'] + ',' + pager['limit'];
307
- this.page = pager;
308
- }
309
- }
310
- return <T[]>await actionQuery(newSql, values);
311
- }
312
-
313
- async create(rows): Promise<number> {
314
- let newSql = "";
315
- let values = [];
316
- if (!Array.isArray(rows)) {
317
- rows = [rows];
318
- }
319
- const firstRow = rows[0];
320
- newSql += 'INSERT INTO ' + this.table + ' (' + Object.keys(firstRow).map((field) => '`' + field + '`').join(', ') + ') VALUES';
321
- rows.forEach((row) => {
322
- const valueRow = [];
323
- Object.keys(row).map((field) => {
324
- values.push(row[field]);
325
- valueRow.push('?');
326
- });
327
- newSql += '(' + valueRow.map((value) => '?').join(', ') + ')' + (rows.indexOf(row) === rows.length - 1 ? '' : ',');
328
- });
329
- const result: ResultSetHeader = await actionExecute(newSql, values);
330
- return result.insertId;
331
- }
332
-
333
- async find<T>(conditions, sort, fields = '*'): Promise<T> {
334
- const result = await this.findAll(conditions, sort, fields, 1);
335
- return result != null && result.length > 0 ? <T>result[0] : null;
336
- }
337
-
338
- async update(conditions, fieldToValues): Promise<number> {
339
- const { sql, values } = this.where(conditions);
340
- const newSql = 'UPDATE ' + this.table + ' SET ' + Object.keys(fieldToValues).map((field) => { return '`' + field + '` = ? ' }).join(', ') + ' WHERE ' + sql;
341
- const result: ResultSetHeader = await actionExecute(newSql, Object.values(fieldToValues).concat(values));
342
- return result.affectedRows;
343
- }
344
-
345
- async delete(conditions): Promise<number> {
346
- const { sql, values } = this.where(conditions);
347
- const newSql = 'DELETE FROM ' + this.table + ' WHERE ' + sql;
348
- const result: ResultSetHeader = await actionExecute(newSql, values);
349
- return result.affectedRows;
350
- }
351
-
352
- async findCount(conditions): Promise<number> {
353
- const { sql, values } = this.where(conditions);
354
- const newSql = 'SELECT COUNT(*) AS M_COUNTER FROM ' + this.table + ' WHERE ' + sql;
355
- const result = await actionQuery(newSql, values);
356
- return result != null && result[0] != undefined ? result[0]['M_COUNTER'] : 0;
357
- }
358
-
359
- async incr(conditions, field, optval = 1): Promise<number> {
360
- const { sql, values } = this.where(conditions);
361
- const newSql = 'UPDATE ' + this.table + ' SET `' + field + '` = `' + field + '` + ? WHERE ' + sql;
362
- values.unshift(optval); // increase at the top
363
- const result: ResultSetHeader = await actionExecute(newSql, values);
364
- return result.affectedRows;
365
- }
366
-
367
- async decr(conditions, field, optval = 1): Promise<number> {
368
- return await this.incr(conditions, field, -optval);
369
- }
370
-
371
- pager(page, total, pageSize = 10, scope = 10) {
372
- this.page = null
373
- if (total === undefined) throw new Error('Pager total would not be undefined')
374
- if (total > pageSize) {
375
- let totalPage = Math.ceil(total / pageSize)
376
- page = Math.min(Math.max(page, 1), total)
377
- this.page = {
378
- 'total': total,
379
- 'pageSize': pageSize,
380
- 'totalPage': totalPage,
381
- 'firstPage': 1,
382
- 'prevPage': ((1 == page) ? 1 : (page - 1)),
383
- 'nextPage': ((page == totalPage) ? totalPage : (page + 1)),
384
- 'lastPage': totalPage,
385
- 'currentPage': page,
386
- 'allPages': [],
387
- 'offset': (page - 1) * pageSize,
388
- 'limit': pageSize
389
- }
390
- if (totalPage <= scope) {
391
- this.page.allPages = this.range(1, totalPage)
392
- } else if (page <= scope / 2) {
393
- this.page.allPages = this.range(1, scope)
394
- } else if (page <= totalPage - scope / 2) {
395
- let right = page + (scope / 2)
396
- this.page.allPages = this.range(right - scope + 1, right)
397
- } else {
398
- this.page.allPages = this.range(totalPage - scope + 1, totalPage)
399
- }
400
- }
401
- return this.page
402
- }
403
-
404
- private where(conditions: object | string): { sql: string, values: any[] } {
405
- const result = { sql: '', values: [] };
406
- if (typeof conditions === 'object') {
407
- Object.keys(conditions).map((field) => {
408
- if (result["sql"].length > 0) {
409
- result["sql"] += " AND "
410
- }
411
- if (typeof conditions[field] === 'object') {
412
- if (field === '$or') {
413
- let orSql = "";
414
- conditions[field].map((item) => {
415
- const { sql, values } = this.where(item);
416
- orSql += (orSql.length > 0 ? " OR " : "") + `(${sql})`;
417
- result["values"] = result["values"].concat(values);
418
- });
419
- result["sql"] += `(${orSql})`;
420
- } else {
421
- const operatorTemplate = { $lt: "<", $lte: "<=", $gt: ">", $gte: ">=", $ne: "!=", $like: "LIKE" };
422
- Object.keys(conditions[field]).map((operator, index) => {
423
- if (operatorTemplate[operator]) {
424
- const operatorValue = operatorTemplate[operator];
425
- result["sql"] += (index ? " AND " : "") + ` ${field} ${operatorValue} ? `;
426
- result["values"].push(conditions[field][operator]);
427
- }
428
- });
429
- }
430
- } else {
431
- result["sql"] += ` ${field} = ? `;
432
- result["values"].push(conditions[field]);
433
- }
434
- });
435
- } else {
436
- result["sql"] = conditions;
437
- }
438
- return result
439
- }
440
-
441
- private range(start, end) {
442
- return [...Array(end - start + 1).keys()].map(i => i + start);
443
- }
444
- }
445
-
446
- export { insert, update, remove, select, param, resultType, cache, Model };
@@ -1,53 +0,0 @@
1
- /**
2
- * 装饰器双签名感知工具。
3
- *
4
- * typespeed 2.5.x 起,装饰器同时支持两套运行时签名:
5
- * - legacy(experimentalDecorators: true,2.4.x 现状):
6
- * 类装饰器 (ctor);方法/属性装饰器 (target, key);带 descriptor 的方法 (target, key, descriptor);参数 (target, key, index)
7
- * - 标准(TC39 装饰器提案,当前 Stage 2.7,experimentalDecorators: false):
8
- * 统一 (value, context),context 恒为带 kind 字段的对象
9
- *
10
- * 装饰器函数本质是普通函数,运行时收到什么签名由「调用方(用户代码)」的编译模式决定,
11
- * 因此库可以单份源码、运行时按签名形态分流:legacy 分支逻辑与 2.4.x 逐字一致,标准分支为新增。
12
- */
13
-
14
- /** 标准装饰器 context 的 kind 取值(TS/Babel 2022-03 版语义) */
15
- export type StdDecoratorKind = "class" | "method" | "getter" | "setter" | "field" | "accessor";
16
-
17
- /** 标准装饰器 context 的宽松类型描述(不依赖 esnext.decorators lib,保持 ES2017 可编译) */
18
- export interface StdDecoratorContext {
19
- kind: StdDecoratorKind;
20
- name?: string | symbol;
21
- static?: boolean;
22
- private?: boolean;
23
- access?: { get?: boolean; set?: boolean };
24
- metadata?: Record<PropertyKey, unknown>;
25
- addInitializer(fn: (this: any) => void): void;
26
- }
27
-
28
- /**
29
- * 判断装饰器收到的运行时参数是否为标准装饰器签名 (value, context)。
30
- *
31
- * 判据(与 `2.5.x-新版装饰器使用方案.md` 一致):
32
- * 参数个数 === 2 且第二个参数是「带 string 类型 kind 字段」的对象。
33
- *
34
- * 为什么这个判据可靠:
35
- * - legacy 类装饰器只有 1 参 → 不满足 length === 2
36
- * - legacy 方法/属性装饰器第二参是 string 的 key → 不是对象
37
- * - legacy 带 descriptor 的方法 / 参数装饰器是 3 参 → 不满足 length === 2
38
- * - 标准模式第二参恒是带 kind 的对象 → 命中
39
- */
40
- export function isStd(args: unknown[]): boolean {
41
- return args.length === 2
42
- && typeof args[1] === "object"
43
- && args[1] !== null
44
- && typeof (args[1] as { kind?: unknown }).kind === "string";
45
- }
46
-
47
- /**
48
- * 从标准装饰器参数中解出 (value, context)。
49
- * 仅应在 isStd(args) 为 true 时调用。
50
- */
51
- export function getStdArgs(args: unknown[]): [any, StdDecoratorContext] {
52
- return [args[0], args[1] as StdDecoratorContext];
53
- }
@@ -1,10 +0,0 @@
1
- import AuthenticationFactory from "../factory/authentication-factory.class";
2
- import { bean } from "../core.decorator";
3
-
4
- export default class DefaultAuthentication extends AuthenticationFactory{
5
- @bean
6
- public getAuthentication(): AuthenticationFactory {
7
- return new DefaultAuthentication();
8
- }
9
- }
10
-
@@ -1,150 +0,0 @@
1
- import * as fs from "fs";
2
- import * as express from "express";
3
- import * as consolidate from "consolidate";
4
- import * as serveFavicon from "serve-favicon";
5
- import * as compression from "compression";
6
- import * as cookieParser from "cookie-parser";
7
- import * as expressSession from "express-session";
8
- import * as connectRedis from "connect-redis";
9
- import ServerFactory from "../factory/server-factory.class";
10
- import { setRouter } from "../route.decorator";
11
- import { SocketIo } from "../default/socket-io.class";
12
- import { value } from "../typespeed";
13
- import { bean, error, autoware, resource } from "../core.decorator";
14
- import { Redis } from "./redis.class";
15
- import AuthenticationFactory from "../factory/authentication-factory.class";
16
-
17
- export default class ExpressServer extends ServerFactory {
18
-
19
- @value("view")
20
- public view: string;
21
-
22
- @value("static")
23
- private static: string;
24
-
25
- @value("favicon")
26
- private favicon: string;
27
-
28
- @value("compression")
29
- private compression: object;
30
-
31
- @value("cookie")
32
- private cookieConfig: object;
33
-
34
- @value("session")
35
- private session: object;
36
-
37
- @value("redis")
38
- private redisConfig: object;
39
-
40
- @value("socket")
41
- private socketIoConfig: object;
42
-
43
- @value("MAIN_PATH")
44
- private mainPath: string;
45
-
46
- @autoware
47
- private redisClient: Redis;
48
-
49
- @autoware
50
- public authentication: AuthenticationFactory;
51
-
52
- @bean
53
- public getSever(): ServerFactory {
54
- const server = new ExpressServer();
55
- server.app = express();
56
- return server;
57
- }
58
-
59
- public setMiddleware(middleware: any) {
60
- this.middlewareList.push(middleware);
61
- }
62
-
63
- public start(port: number): any {
64
- this.middlewareList.forEach(middleware => {
65
- this.app.use(middleware);
66
- });
67
-
68
- this.setDefaultMiddleware();
69
- if(this.socketIoConfig) {
70
- const newSocketApp = SocketIo.setIoServer(this.app, this.socketIoConfig);
71
- return newSocketApp.listen(port);
72
- }else{
73
- return this.app.listen(port);
74
- }
75
- }
76
-
77
- private setDefaultMiddleware() {
78
- this.app.use(express.urlencoded({ extended: true }));
79
- this.app.use(express.json());
80
- if (this.view) {
81
- const viewConfig = this.view;
82
- this.app.engine(viewConfig["suffix"], consolidate[viewConfig["engine"]]);
83
- this.app.set('view engine', viewConfig["suffix"]);
84
- this.app.set('views', this.mainPath + viewConfig["path"]);
85
- }
86
-
87
- if (this.session) {
88
- const sessionConfig = this.session;
89
- if (sessionConfig["trust proxy"] === 1) {
90
- this.app.set('trust proxy', 1);
91
- }
92
- if (this.redisConfig) {
93
- const RedisStore = connectRedis(expressSession);
94
- sessionConfig["store"] = new RedisStore({ client: this.redisClient });
95
- }
96
-
97
- this.app.use(expressSession(sessionConfig));
98
- }
99
-
100
- if (this.favicon) {
101
- const faviconPath = this.mainPath + this.favicon;
102
- this.app.use(serveFavicon(faviconPath));
103
- }
104
-
105
- if (this.compression) {
106
- this.app.use(compression(this.compression));
107
- }
108
-
109
- if (this.cookieConfig) {
110
- this.app.use(cookieParser(this.cookieConfig["secret"] || undefined, this.cookieConfig["options"] || {}));
111
- }
112
-
113
- this.app.use(this.authentication.preHandle);
114
-
115
- if (this.static) {
116
- const staticPath = this.mainPath + this.static;
117
- this.app.use(express.static(staticPath))
118
- }
119
- setRouter(this.app);
120
- this.app.use(this.authentication.afterCompletion);
121
-
122
- const errorPageDir = __dirname + "/pages";
123
- this.app.use((req, res) => {
124
- error("404 not found, for page: " + req.url);
125
- res.status(404);
126
- if (req.accepts('html')) {
127
- res.type('html').send(fs.readFileSync(errorPageDir + "/404.html", "utf-8"));
128
- } else if (req.accepts('json')) {
129
- res.json({ error: 'Not found' });
130
- } else {
131
- res.type('txt').send('Not found');
132
- }
133
- });
134
-
135
- this.app.use((err, req, res, next) => {
136
- if (!err) {
137
- next();
138
- }
139
- error(err);
140
- res.status(err.status || 500);
141
- if (req.accepts('html')) {
142
- res.type('html').send(fs.readFileSync(errorPageDir + "/500.html", "utf-8"));
143
- } else if (req.accepts('json')) {
144
- res.json({ error: 'Internal Server Error' });
145
- } else {
146
- res.type('txt').send('Internal Server Error');
147
- }
148
- });
149
- }
150
- }
@@ -1,9 +0,0 @@
1
- import { bean } from "../core.decorator";
2
- import LogFactory from "../factory/log-factory.class";
3
-
4
- export default class LogDefault extends LogFactory {
5
- @bean
6
- createLog(): LogFactory {
7
- return new LogDefault();
8
- }
9
- }