speed 1.1.8 → 1.2.2

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.
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2021 jake
3
+ Copyright (c) 2022 speed
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,332 +1,2 @@
1
- ## SpeedSQL
2
-
3
- [![typescript](https://badgen.net/badge/icon/TypeScript?icon=typescript&label)](https://www.npmjs.com/package/speed)
4
- [![npm](https://badgen.net/npm/v/speed?color=cyan)](https://www.npmjs.com/package/speed)
5
- [![publis size](https://badgen.net/packagephobia/publish/speed?color=green)](https://www.npmjs.com/package/speed)
6
- [![downloads](https://badgen.net/npm/dt/speed?color=pink)](https://www.npmjs.com/package/speed)
7
- [![license](https://badgen.net/github/license/speedphp/speedsql)](https://github.com/SpeedPHP/speedsql/blob/main/LICENSE)
8
-
9
- SQL injection for NestJS, similar mybatis.
10
-
11
- ### Introduction
12
-
13
- - Follow NestJS Module injection mode.
14
- - With the TypeScript Decorators, same as Java annotations.
15
- - Similar to MyBatis used in Java.
16
- - Support for the Prepared Statements.
17
- - Support for Entity Injection.
18
- - Support the Connection pools by mysql2 within.
19
-
20
- ### Support Decorators
21
-
22
- `@Param`, `@ResultType`, `@Select`, `@Insert`, `@Update`, `@Delete`.
23
-
24
- ### Install as a dependency
25
-
26
- Setup SpeedSQL (NPM named `speed`) as dependency in *package.json* file `dependencies`
27
-
28
- ```
29
- "dependencies": {
30
- "speed": "latest"
31
- }
32
- ```
33
-
34
- ### Quick Start
35
-
36
- - Prepare some entities and configurations.
37
-
38
- *db.provider.ts*
39
- ```
40
- import { createPool, Pool } from 'speed';
41
-
42
- export const DbProviders = [
43
- {
44
- provide: 'SPEED_POOL',
45
- useFactory: async (): Promise<Pool> => {
46
- return await createPool({
47
- host: 'localhost',
48
- user: 'root',
49
- port: 3306,
50
- password: 'qwer1234',
51
- database: 'test',
52
- });
53
- },
54
- },
55
- ];
56
- ```
57
- *entity/param.dto.ts*
58
- ```
59
- export class ParamDto {
60
- constructor(public name: string, public age: number) {}
61
- }
62
- ```
63
- *entity/user.dto.ts*
64
- ```
65
- export class UserDto {
66
- constructor(public name: string, public age: number) {}
67
- }
68
- ```
69
-
70
- * * *
71
-
72
- - Import into the Module of NestJS
73
-
74
-
75
- *app.mudule.ts*
76
- ```
77
- import { Module } from '@nestjs/common';
78
- import { AppController } from './app.controller';
79
- import { AppService } from './app.service';
80
- import { SpeedService } from 'speed';
81
- import { DbProviders } from './db.providers';
82
-
83
- @Module({
84
- imports: [],
85
- controllers: [AppController],
86
- providers: [AppService, SpeedService, ...DbProviders],
87
- })
88
- export class AppModule {}
89
- ```
90
-
91
- * * *
92
-
93
- - Define SpeedSQL within Services, use the Decorators as MyBatis.
94
-
95
- *app.service.ts*
96
- ```
97
- import { Injectable } from '@nestjs/common';
98
- import { Delete, Update, Param, ResultType, Insert } from 'speed';
99
- import { UserDto } from './entity/user.dto';
100
- import { ParamDto } from './entity/param.dto';
101
-
102
- @Injectable()
103
- export class AppService {
104
- @Update('update user set age = #{age} where name = #{name}')
105
- setUserAge(@Param('name') name: string, @Param('age') age: number): number {return;}
106
-
107
- @Delete('delete from user where name = #{name}')
108
- deleteUser(@Param('name') name: string): number {return;}
109
-
110
- @ResultType(UserDto)
111
- @Select('select `name`, `age` from `user` where `uid` = #{uid} and `name` = #{name}')
112
- getRecords(paramDto: ParamDto): UserDto[] {return;}
113
-
114
- @Insert('insert into user (name, age) value (#{name}, #{age})')
115
- addUser(user: UserDto): number {return;}
116
- }
117
- ```
118
-
119
- * * *
120
-
121
- - Use Your Services.
122
-
123
- *app.controller.ts*
124
- ```
125
- import { Controller, Get } from '@nestjs/common';
126
- import { AppService } from './app.service';
127
- import { ParamDto } from './entity/param.dto';
128
- import { UserDto } from "./entity/create-cat.dto";
129
-
130
- @Controller()
131
- export class AppController {
132
- constructor(private readonly appService: AppService) {}
133
-
134
- @Get()
135
- async getHello() {
136
- await this.appService.setUserAge("zzz", 20);
137
- return "hello world";
138
- }
139
- }
140
-
141
- ```
142
-
143
- ### Configuration
144
-
145
- The Connection pools configuration is exactly the same as mysql2's [createPool\(\)](https://github.com/sidorares/node-mysql2#using-promise-wrapper).
146
-
147
- The usual format is as follows:
148
-
149
- ```
150
- {
151
- host: '127.0.0.1',
152
- user: 'root',
153
- port: 3306,
154
- password: '123456',
155
- database: 'test',
156
- }
157
- ```
158
-
159
- * * *
160
- Like common NestJS Modules, SpeedSQL uses [Asynchronous providers](https://docs.nestjs.com/fundamentals/async-providers) to inject it's Connection Pool for startup.
161
-
162
- - Make file ```db.provider.ts```
163
- ```
164
- import { createPool, Pool } from 'speed';
165
-
166
- export const DbProviders = [
167
- {
168
- provide: 'SPEED_POOL',
169
- useFactory: async (): Promise<Pool> => {
170
- return await createPool({
171
- host: 'localhost',
172
- user: 'root',
173
- port: 3306,
174
- password: 'qwer1234',
175
- database: 'test',
176
- });
177
- },
178
- },
179
- ];
180
- ```
181
- - Put ```db.provider.ts``` in NestJS app src dir and set it as a provider.
182
- ```
183
- import { Module } from '@nestjs/common';
184
- import { AppController } from './app.controller';
185
- import { AppService } from './app.service';
186
- import { SpeedService } from 'speed';
187
- import { DbProviders } from './db.providers';
188
-
189
- @Module({
190
- imports: [],
191
- controllers: [AppController],
192
- providers: [AppService, SpeedService, ...DbProviders],
193
- })
194
- export class AppModule {}
195
- ```
196
-
197
- ### Parameter with named (for Prepared Statements)
198
-
199
- `@Param` define the named parameters.
200
-
201
- As with MyBatis, SpeedSQL is possible to pass a value to a bind parameter as a named parameter to ensure readability and prevent SQL Injection attacks.
202
-
203
- Unlike [Prepared Statements](https://github.com/sidorares/node-mysql2#using-prepared-statements) in mysql2, SpeedSQL can be pass param value with named to make SQL more clearer.
204
-
205
- **Parameter with named value can support ```@Select```, ```@Insert```, ```@Update```, ```@Delete``` all the CRUD operations.**
206
-
207
- * * *
208
-
209
- SpeedSQL has two Parameter with named modes.
210
-
211
- > Note that you can only choose ONE of the modes at ONE statement.
212
-
213
- **Object as Parameters**
214
-
215
- - Creates a conditional entity class with the same attribute and parameter names.
216
-
217
- ```
218
- export class ParamDto {
219
- constructor(public name: string, public age: number) {}
220
- }
221
- ```
222
-
223
- - Inject values as parameter entities.
224
-
225
- ```
226
- import { ResultType, Select } from 'speed';
227
-
228
-
229
- @ResultType(UserDto)
230
- @Select('select `name`, `age` from `user` where `uid` = #{uid} and `name` = #{name}')
231
- getRecords(paramDto: ParamDto): UserDto[]{return;}
232
- ```
233
- - So we can start to use.
234
- ```
235
- const users: UserDto[] = await this.appService.getRecords(
236
- new ParamDto("zzz", 10)
237
- );
238
- ```
239
-
240
- **Named Value as Parameters**
241
-
242
- Annotate the parameter value name with the parameter annotation '@Param', which corresponds to the SQL value name.
243
-
244
- ```
245
- import { ResultType, Select, Param } from 'speed';
246
-
247
- @ResultType(UserDto)
248
- @Select(select `name`, `age` from `user` where `uid` = #{uid} and `name` = #{name}')
249
- getRecords(@Param('uid') uid:number, @Param('name') name:string): UserDto[]{return;}
250
- ```
251
- So we can start to use.
252
- ```
253
- const users: UserDto[] = await this.appService.getRecords('zzz', 10);
254
- ```
255
-
256
- ### @Select
257
-
258
- SpeedSQL uses ```@ResultType``` to annotate the resulting entity.
259
-
260
- `@ResultType` define the data entity for @Selete returns.
261
-
262
- Select returns an array of annotated entity (```@ResultType```).
263
-
264
- - Create a entity:
265
-
266
- ```
267
- export class UserDto {
268
- constructor(public name: string, public age: number) {}
269
- }
270
- ```
271
- - And Select.
272
- ```
273
- import { ResultType, Select, Param } from 'speed';
274
-
275
-
276
- @ResultType(UserDto)
277
- @Select('select `name`, `age` from user where uid = #{uid} and name = #{name} ')
278
- getRecords(@Param('uid') uid:number, @Param('name') name:string): UserDto[] {return;}
279
- ```
280
- - The return Array will contains entities, and field name will correspond to the attributes of the entity.
281
-
282
- If the field name and attribute are not the same, the value of different name will be lost. The solution is to use SQL's ```AS``` to alias the field name to correspond to the attributes of the entity.
283
-
284
-
285
- ```
286
- import { ResultType, Select, Param } from 'speed';
287
-
288
- @ResultType(UserDto)
289
- @Select('select `realname` as `name`, `age` from user where uid = #{uid} and name = #{name} ')
290
- getRecords(@Param('uid') uid:number, @Param('name') name:string): UserDto[] {return;}
291
- ```
292
-
293
-
294
- ### @Insert
295
-
296
- Parameter with named is also supported in ```@Insert```.
297
-
298
- The ```@Insert``` return value is <u>the new inserted ID</u>, which can also be ignored.
299
-
300
- ```
301
- import { Insert } from 'speed';
302
-
303
- @Insert('insert into user (name, age) value (#{name}, #{age})')
304
- addUser(user: UserDto): number {return;}
305
- ```
306
-
307
- ### @Update and @Delete
308
-
309
- Parameter with named is also supported in ```@Update``` and ```@Delete```.
310
-
311
- The ```@Update``` and ```@Delete``` returns number is <u>the effected rows</u>, which can also be ignored.
312
-
313
- ```
314
- import { Delete, Update, Param } from 'speed';
315
-
316
- @Update('update user set age = #{age} where name = #{name}')
317
- setUserAge(@Param('name') name: string, @Param('age') age: number): number {return;}
318
-
319
- @Delete('delete from user where name = #{name}')
320
- deleteUser(@Param('name') name: string): number {return;}
321
- ```
322
-
323
-
324
- ### About
325
-
326
- Github:[https://github.com/speedphp/speedsql](https://github.com/speedphp/speedsql)
327
-
328
- The SpeedSQL project follows the open source agreement of the ```MIT License```.
329
-
330
- Thanks: [NestJS](https://nestjs.com/),[mysql2](https://github.com/sidorares/node-mysql2),[MyBatis](https://mybatis.org/).
331
-
332
- Issue: [https://github.com/SpeedPHP/speedsql/issues](https://github.com/SpeedPHP/speedsql/issues)
1
+ # speed
2
+ Framework for TypeScript
package/package.json CHANGED
@@ -1,27 +1,8 @@
1
1
  {
2
2
  "name": "speed",
3
- "version": "1.1.8",
4
- "description": "SQL injection for NestJS, similar mybatis.",
5
- "author": "speedphp",
6
- "license": "MIT License",
7
- "repository": {
8
- "type": "git",
9
- "url": "https://github.com/speedphp/speedsql.git"
10
- },
11
- "dependencies": {
12
- "mysql2": "~2.3.0"
13
- },
14
- "keywords": [
15
- "mybatis",
16
- "nestjs",
17
- "database",
18
- "orm",
19
- "typescript",
20
- "decorator",
21
- "autoware",
22
- "inject",
23
- "mysql2",
24
- "mysql",
25
- "speedsql"
26
- ]
3
+ "version": "1.2.2",
4
+ "description": "A new Framework for TypeScript.",
5
+ "author": "speed",
6
+ "license": "MIT License"
7
+
27
8
  }
package/index.d.ts DELETED
@@ -1,2 +0,0 @@
1
- export * from './speed.decorator';
2
- export * from './speed.service';
package/index.js DELETED
@@ -1,15 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
- }) : (function(o, m, k, k2) {
6
- if (k2 === undefined) k2 = k;
7
- o[k2] = m[k];
8
- }));
9
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
- };
12
- Object.defineProperty(exports, "__esModule", { value: true });
13
- __exportStar(require("./speed.decorator"), exports);
14
- __exportStar(require("./speed.service"), exports);
15
- //# sourceMappingURL=index.js.map
package/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,oDAAkC;AAClC,kDAAgC"}
package/index.ts DELETED
@@ -1,2 +0,0 @@
1
- export * from './speed.decorator';
2
- export * from './speed.service';
@@ -1,7 +0,0 @@
1
- declare function log(message?: any, ...optionalParams: any[]): void;
2
- declare function ResultType(constructorFunction: any): (target: any, propertyKey: string) => void;
3
- declare function Param(name: string): (target: any, propertyKey: string | symbol, parameterIndex: number) => void;
4
- declare function Insert(sql: string): (target: any, propertyKey: string, descriptor: PropertyDescriptor) => void;
5
- declare function Update(sql: string): (target: any, propertyKey: string, descriptor: PropertyDescriptor) => void;
6
- declare function Select(sql: string): (target: any, propertyKey: string, descriptor: PropertyDescriptor) => void;
7
- export { log, Param, ResultType, Select, Insert, Update, Update as Delete };
@@ -1,109 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Delete = exports.Update = exports.Insert = exports.Select = exports.ResultType = exports.Param = exports.log = void 0;
4
- const speed_service_1 = require("./speed.service");
5
- const paramMetadataKey = Symbol('param');
6
- function log(message, ...optionalParams) {
7
- console.log(message, ...optionalParams);
8
- }
9
- exports.log = log;
10
- function ResultType(constructorFunction) {
11
- const newConstructorFunction = function (...args) {
12
- const func = function () {
13
- return new constructorFunction(...args);
14
- };
15
- func.prototype = constructorFunction.prototype;
16
- return new func();
17
- };
18
- newConstructorFunction.prototype = constructorFunction.prototype;
19
- return function (target, propertyKey) {
20
- speed_service_1.resultTypeMap.set([target.constructor.name, propertyKey].toString(), newConstructorFunction());
21
- };
22
- }
23
- exports.ResultType = ResultType;
24
- function Param(name) {
25
- return function (target, propertyKey, parameterIndex) {
26
- const existingParameters = Reflect.getOwnMetadata(paramMetadataKey, target, propertyKey) || [];
27
- existingParameters.push([name, parameterIndex]);
28
- Reflect.defineMetadata(paramMetadataKey, existingParameters, target, propertyKey);
29
- };
30
- }
31
- exports.Param = Param;
32
- function convertSQLParams(args, target, propertyKey, decoratorSQL) {
33
- const queryValues = [];
34
- let argsVal;
35
- if (typeof args[0] === 'object') {
36
- argsVal = new Map(Object.getOwnPropertyNames(args[0]).map((valName) => [
37
- valName,
38
- args[0][valName],
39
- ]));
40
- }
41
- else {
42
- const existingParameters = Reflect.getOwnMetadata(paramMetadataKey, target, propertyKey);
43
- argsVal = new Map(existingParameters.map(([argName, argIdx]) => [argName, args[argIdx]]));
44
- }
45
- const regExp = /#{(\w+)}/;
46
- let match;
47
- while (match = regExp.exec(decoratorSQL)) {
48
- const [replaceTag, matchName] = match;
49
- decoratorSQL = decoratorSQL.replace(new RegExp(replaceTag, 'g'), '?');
50
- queryValues.push(argsVal.get(matchName));
51
- }
52
- return [decoratorSQL, queryValues];
53
- }
54
- async function queryForExecute(sql, args, target, propertyKey) {
55
- let sqlValues = [];
56
- let newSql = sql;
57
- if (args.length > 0) {
58
- [newSql, sqlValues] = convertSQLParams(args, target, propertyKey, sql);
59
- }
60
- const [result] = await speed_service_1.speedPromisePool.query(newSql, sqlValues);
61
- return result;
62
- }
63
- function Insert(sql) {
64
- return function (target, propertyKey, descriptor) {
65
- descriptor.value = async (...args) => {
66
- const result = await queryForExecute(sql, args, target, propertyKey);
67
- return result.insertId;
68
- };
69
- };
70
- }
71
- exports.Insert = Insert;
72
- function Update(sql) {
73
- return function (target, propertyKey, descriptor) {
74
- descriptor.value = async (...args) => {
75
- const result = await queryForExecute(sql, args, target, propertyKey);
76
- return result.affectedRows;
77
- };
78
- };
79
- }
80
- exports.Update = Update;
81
- exports.Delete = Update;
82
- function Select(sql) {
83
- return function (target, propertyKey, descriptor) {
84
- descriptor.value = async (...args) => {
85
- let sqlValues = [];
86
- if (args.length > 0) {
87
- [sql, sqlValues] = convertSQLParams(args, target, propertyKey, sql);
88
- }
89
- const [rows] = await speed_service_1.speedPromisePool.query(sql, sqlValues);
90
- if (Object.keys(rows).length === 0) {
91
- return;
92
- }
93
- const records = [];
94
- const resultType = speed_service_1.resultTypeMap.get([target.constructor.name, propertyKey].toString());
95
- for (const rowIndex in rows) {
96
- const entity = Object.create(resultType);
97
- Object.getOwnPropertyNames(resultType).forEach(function (propertyRow) {
98
- if (rows[rowIndex].hasOwnProperty(propertyRow)) {
99
- Object.defineProperty(entity, propertyRow, Object.getOwnPropertyDescriptor(rows[rowIndex], propertyRow));
100
- }
101
- });
102
- records.push(entity);
103
- }
104
- return records;
105
- };
106
- };
107
- }
108
- exports.Select = Select;
109
- //# sourceMappingURL=speed.decorator.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"speed.decorator.js","sourceRoot":"","sources":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,CAAC,MAAM,GAAG,CAAC,EAAE;gBACnB,CAAC,GAAG,EAAE,SAAS,CAAC,GAAG,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,GAAG,CAAC,CAAC;aACrE;YACD,MAAM,CAAC,IAAI,CAAC,GAAG,MAAM,gCAAgB,CAAC,KAAK,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;YAC5D,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE;gBAClC,OAAO;aACR;YACD,MAAM,OAAO,GAAG,EAAE,CAAC;YACnB,MAAM,UAAU,GAAG,6BAAa,CAAC,GAAG,CAChC,CAAC,MAAM,CAAC,WAAW,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC,QAAQ,EAAE,CACpD,CAAC;YACF,KAAK,MAAM,QAAQ,IAAI,IAAI,EAAE;gBAC3B,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;gBACzC,MAAM,CAAC,mBAAmB,CAAC,UAAU,CAAC,CAAC,OAAO,CAAC,UAAU,WAAW;oBAClE,IAAI,IAAI,CAAC,QAAQ,CAAC,CAAC,cAAc,CAAC,WAAW,CAAC,EAAE;wBAC9C,MAAM,CAAC,cAAc,CACjB,MAAM,EACN,WAAW,EACX,MAAM,CAAC,wBAAwB,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,WAAW,CAAC,CAC/D,CAAC;qBACH;gBACH,CAAC,CAAC,CAAC;gBACH,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;aACtB;YACD,OAAO,OAAO,CAAC;QACjB,CAAC,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC;AAEgC,wBAAM"}
@@ -1,174 +0,0 @@
1
- import { speedPromisePool, resultTypeMap } from './speed.service';
2
- import { ResultSetHeader } from 'mysql2';
3
-
4
- const paramMetadataKey = Symbol('param');
5
-
6
- function log(message?: any, ...optionalParams: any[]) {
7
- console.log(message, ...optionalParams);
8
- }
9
-
10
- function ResultType(constructorFunction) {
11
- const newConstructorFunction: any = function (...args) {
12
- const func: any = function () {
13
- return new constructorFunction(...args);
14
- };
15
- func.prototype = constructorFunction.prototype;
16
- return new func();
17
- };
18
- newConstructorFunction.prototype = constructorFunction.prototype;
19
- return function (target, propertyKey: string) {
20
- resultTypeMap.set(
21
- [target.constructor.name, propertyKey].toString(),
22
- newConstructorFunction(),
23
- );
24
- //never return
25
- };
26
- }
27
-
28
- function Param(name: string) {
29
- return function (
30
- target: any,
31
- propertyKey: string | symbol,
32
- parameterIndex: number,
33
- ) {
34
- const existingParameters: [string, number][] =
35
- Reflect.getOwnMetadata(paramMetadataKey, target, propertyKey) || [];
36
- existingParameters.push([name, parameterIndex]);
37
- Reflect.defineMetadata(
38
- paramMetadataKey,
39
- existingParameters,
40
- target,
41
- propertyKey,
42
- );
43
- };
44
- }
45
-
46
- function convertSQLParams(
47
- args: any[],
48
- target: any,
49
- propertyKey: string,
50
- decoratorSQL: string,
51
- ): [string, any[]] {
52
- const queryValues = [];
53
- let argsVal;
54
- if (typeof args[0] === 'object') {
55
- argsVal = new Map(
56
- Object.getOwnPropertyNames(args[0]).map((valName) => [
57
- valName,
58
- args[0][valName],
59
- ]),
60
- );
61
- } else {
62
- const existingParameters: [string, number][] = Reflect.getOwnMetadata(
63
- paramMetadataKey,
64
- target,
65
- propertyKey,
66
- );
67
- argsVal = new Map(
68
- existingParameters.map(([argName, argIdx]) => [argName, args[argIdx]]),
69
- );
70
- }
71
- const regExp = /#{(\w+)}/;
72
- let match;
73
- while(match = regExp.exec(decoratorSQL)){
74
- const [replaceTag, matchName] = match;
75
- decoratorSQL = decoratorSQL.replace(new RegExp(replaceTag, 'g'), '?');
76
- queryValues.push(argsVal.get(matchName));
77
- }
78
- // [...decoratorSQL.matchAll(regExp)].forEach((match) => {
79
- // const [replaceTag, matchName] = match;
80
- // decoratorSQL = decoratorSQL.replace(new RegExp(replaceTag, 'g'), '?');
81
- // queryValues.push(argsVal.get(matchName));
82
- // });
83
- return [decoratorSQL, queryValues];
84
- }
85
-
86
- async function queryForExecute(
87
- sql: string,
88
- args: any[],
89
- target,
90
- propertyKey: string,
91
- ): Promise<ResultSetHeader> {
92
- let sqlValues = [];
93
- let newSql = sql;
94
- if (args.length > 0) {
95
- [newSql, sqlValues] = convertSQLParams(args, target, propertyKey, sql);
96
- }
97
- const [result] = await speedPromisePool.query(newSql, sqlValues);
98
- return <ResultSetHeader>result;
99
- }
100
-
101
- function Insert(sql: string) {
102
- return function (
103
- target,
104
- propertyKey: string,
105
- descriptor: PropertyDescriptor,
106
- ) {
107
- descriptor.value = async (...args: any[]) => {
108
- const result: ResultSetHeader = await queryForExecute(
109
- sql,
110
- args,
111
- target,
112
- propertyKey,
113
- );
114
- return result.insertId;
115
- };
116
- };
117
- }
118
-
119
- function Update(sql: string) {
120
- return function (
121
- target,
122
- propertyKey: string,
123
- descriptor: PropertyDescriptor,
124
- ) {
125
- descriptor.value = async (...args: any[]) => {
126
- const result: ResultSetHeader = await queryForExecute(
127
- sql,
128
- args,
129
- target,
130
- propertyKey,
131
- );
132
- return result.affectedRows;
133
- };
134
- };
135
- }
136
-
137
- function Select(sql: string) {
138
- return function (
139
- target,
140
- propertyKey: string,
141
- descriptor: PropertyDescriptor,
142
- ) {
143
- descriptor.value = async (...args: any[]) => {
144
- let sqlValues = [];
145
- if (args.length > 0) {
146
- [sql, sqlValues] = convertSQLParams(args, target, propertyKey, sql);
147
- }
148
- const [rows] = await speedPromisePool.query(sql, sqlValues);
149
- if (Object.keys(rows).length === 0) {
150
- return;
151
- }
152
- const records = [];
153
- const resultType = resultTypeMap.get(
154
- [target.constructor.name, propertyKey].toString(),
155
- );
156
- for (const rowIndex in rows) {
157
- const entity = Object.create(resultType);
158
- Object.getOwnPropertyNames(resultType).forEach(function (propertyRow) {
159
- if (rows[rowIndex].hasOwnProperty(propertyRow)) {
160
- Object.defineProperty(
161
- entity,
162
- propertyRow,
163
- Object.getOwnPropertyDescriptor(rows[rowIndex], propertyRow),
164
- );
165
- }
166
- });
167
- records.push(entity);
168
- }
169
- return records;
170
- };
171
- };
172
- }
173
-
174
- export { log, Param, ResultType, Select, Insert, Update, Update as Delete };
@@ -1,9 +0,0 @@
1
- import { Pool, createPool } from 'mysql2';
2
- import { Pool as PromisePool } from 'mysql2/promise';
3
- declare let speedPromisePool: PromisePool;
4
- declare const resultTypeMap: Map<string, any>;
5
- export declare class SpeedService {
6
- private pool;
7
- constructor(pool: Pool);
8
- }
9
- export { speedPromisePool, resultTypeMap, createPool, Pool };
package/speed.service.js DELETED
@@ -1,37 +0,0 @@
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
- var __param = (this && this.__param) || function (paramIndex, decorator) {
12
- return function (target, key) { decorator(target, key, paramIndex); }
13
- };
14
- var _a;
15
- Object.defineProperty(exports, "__esModule", { value: true });
16
- exports.Pool = exports.createPool = exports.resultTypeMap = exports.speedPromisePool = exports.SpeedService = void 0;
17
- const common_1 = require("@nestjs/common");
18
- const mysql2_1 = require("mysql2");
19
- Object.defineProperty(exports, "Pool", { enumerable: true, get: function () { return mysql2_1.Pool; } });
20
- Object.defineProperty(exports, "createPool", { enumerable: true, get: function () { return mysql2_1.createPool; } });
21
- let speedPromisePool;
22
- exports.speedPromisePool = speedPromisePool;
23
- const resultTypeMap = new Map();
24
- exports.resultTypeMap = resultTypeMap;
25
- let SpeedService = class SpeedService {
26
- constructor(pool) {
27
- this.pool = pool;
28
- exports.speedPromisePool = speedPromisePool = pool.promise();
29
- }
30
- };
31
- SpeedService = __decorate([
32
- (0, common_1.Injectable)(),
33
- __param(0, (0, common_1.Inject)('SPEED_POOL')),
34
- __metadata("design:paramtypes", [typeof (_a = typeof mysql2_1.Pool !== "undefined" && mysql2_1.Pool) === "function" ? _a : Object])
35
- ], SpeedService);
36
- exports.SpeedService = SpeedService;
37
- //# sourceMappingURL=speed.service.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"speed.service.js","sourceRoot":"","sources":["speed.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,2CAAoD;AACpD,mCAA0C;AAYY,qFAZ7C,aAAI,OAY6C;AAAhB,2FAZ3B,mBAAU,OAY2B;AATpD,IAAI,gBAA6B,CAAC;AASzB,4CAAgB;AARzB,MAAM,aAAa,GAAG,IAAI,GAAG,EAAe,CAAC;AAQlB,sCAAa;AALxC,IAAa,YAAY,GAAzB,MAAa,YAAY;IACrB,YAA0C,IAAU;QAAV,SAAI,GAAJ,IAAI,CAAM;QAChD,2BAAA,gBAAgB,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC;IACtC,CAAC;CACJ,CAAA;AAJY,YAAY;IADxB,IAAA,mBAAU,GAAE;IAEI,WAAA,IAAA,eAAM,EAAC,YAAY,CAAC,CAAA;yDAAe,aAAI,oBAAJ,aAAI;GAD3C,YAAY,CAIxB;AAJY,oCAAY"}
package/speed.service.ts DELETED
@@ -1,14 +0,0 @@
1
- import { Inject, Injectable } from '@nestjs/common';
2
- import { Pool, createPool } from 'mysql2';
3
- import { Pool as PromisePool } from 'mysql2/promise';
4
-
5
- let speedPromisePool: PromisePool;
6
- const resultTypeMap = new Map<string, any>();
7
-
8
- @Injectable()
9
- export class SpeedService {
10
- constructor(@Inject('SPEED_POOL') private pool: Pool) {
11
- speedPromisePool = pool.promise();
12
- }
13
- }
14
- export { speedPromisePool, resultTypeMap, createPool, Pool };
package/tsconfig.json DELETED
@@ -1,25 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "module": "commonjs",
4
- "declaration": true,
5
- "removeComments": true,
6
- "emitDecoratorMetadata": true,
7
- "experimentalDecorators": true,
8
- "allowSyntheticDefaultImports": true,
9
- "target": "es2017",
10
- "sourceMap": true,
11
- "outDir": "./",
12
- "baseUrl": "./",
13
- "skipLibCheck": true,
14
- "strictNullChecks": false,
15
- "noImplicitAny": false,
16
- "forceConsistentCasingInFileNames": false,
17
- "noFallthroughCasesInSwitch": false,
18
- "types": []
19
- },
20
- "files": [
21
- "index.ts",
22
- "speed.decorator.ts",
23
- "speed.service.ts"
24
- ]
25
- }