tspace-mysql 1.1.8 → 1.1.9

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/README.md CHANGED
@@ -15,7 +15,7 @@ npm install tspace-mysql --save
15
15
  ```
16
16
  ## Basic Usage
17
17
  - [Configuration](#configuration)
18
- - [Running Queries](#running-queryies)
18
+ - [Running Queries](#running-queries)
19
19
  - [Database Transactions](#database-transactions)
20
20
  - [Connection](#connection)
21
21
  - [Backup](#backup)
@@ -37,18 +37,18 @@ npm install tspace-mysql --save
37
37
  ## Configuration
38
38
  Created your environment variables is to use a .env file, you may establish a connection is this:
39
39
  ```js
40
- TSPACE_HOST = localhost
41
- TSPACE_PORT = 3306
42
- TSPACE_USERNAME = root
43
- TSPACE_PASSWORD = password
44
- TSPACE_DATABASE = database
40
+ DB_HOST = localhost
41
+ DB_PORT = 3306
42
+ DB_USERNAME = root
43
+ DB_PASSWORD = password
44
+ DB_DATABASE = database
45
45
 
46
46
  /** default
47
- TSPACE_CONNECTION_LIMIT = 10
48
- TSPACE_CONNECTION_ERROR = true
49
- TSPACE_QUEUE_LIMIT = 25
50
- TSPACE_TIMEOUT = 30000
51
- TSPACE_DATE_STRINGS = true
47
+ DB_CONNECTION_LIMIT = 30
48
+ DB_CONNECTION_ERROR = true
49
+ DB_QUEUE_LIMIT = 25
50
+ DB_TIMEOUT = 30000
51
+ DB_DATE_STRINGS = true
52
52
  */
53
53
 
54
54
  ```
@@ -64,6 +64,16 @@ Once you have configured your database connection, you may run queries is this :
64
64
  | 2 | tspace2 | tspace2@gmail.com |
65
65
  +-------------+--------------+----------------------------+
66
66
 
67
+
68
+ +-------------+--------------+----------------------------+
69
+ | table posts |
70
+ +-------------+--------------+----------------------------+
71
+ | id | user_id | title |
72
+ |-------------|--------------|----------------------------|
73
+ | 1 | 1 | posts tspace |
74
+ | 2 | 2 | posts tspace2 |
75
+ +-------------+--------------+----------------------------+
76
+
67
77
  import { DB } from 'tspace-mysql'
68
78
  (async () => {
69
79
  await new DB('users').findMany() // SELECT * FROM users => Array
@@ -82,21 +92,45 @@ const selectQueries = await new DB('users').select('id','username').findMany()
82
92
  */
83
93
  await new DB('users').except('id','username').findOne()
84
94
  ```
95
+
96
+ Running A OrderBy & GroupBy Query
97
+ ```js
98
+ await new DB('users').orderBy('id','asc').findOne()
99
+ await new DB('users').orderBy('id','desc').findOne()
100
+ await new DB('users').oldest('id').findOne()
101
+ await new DB('users').latest('id').findOne()
102
+
103
+ await new DB('users').groupBy('id').findOne()
104
+ await new DB('users').groupBy('id','usernamename').findOne()
105
+ ```
106
+
107
+ Running A Join Query
108
+ ```js
109
+ await new DB('posts').join('posts.user_id' , 'users.id').findOne()
110
+ await new DB('posts').leftJoin('posts.user_id' , 'users.id').findOne()
111
+ await new DB('posts').rightJoin('posts.user_id' , 'users.id').findOne()
112
+ ```
113
+
85
114
  Running A Where Query
86
115
  ```js
87
116
  const user = await new DB('users').where('id',1).findOne()
88
117
  // user => { id : 1 , username : 'tspace', email : 'tspace@gmail.com'}
89
118
  const users = await new DB('users').where('id','!=',1).findMany()
90
119
  // users => [{ id : 2 , username : 'tspace2' , email : 'tspace2@gmail.com' }]
91
- /**
92
- * @example where
93
- */
120
+
94
121
  const whereIn = await new DB('users').whereIn('id',[1,2]).findMany()
95
122
  const whereBetween = await new DB('users').whereBetween('id',[1,2]).findMany()
96
123
  const whereSubQuery = await new DB('users').whereSubQuery('id','select id from users').findMany()
97
124
  // await new DB('users').whereSubQuery('id',new DB('users').select('id').toString()).findMany()
98
125
  const whereNull = await new DB('users').whereNull('username').findOne()
99
126
  ```
127
+
128
+ Running A Hook Query
129
+ ```js
130
+ const hookResult = (result) => console.log(result)
131
+ const user = await new DB('users').where('id',1).hook(hookResult).findOne()
132
+ ```
133
+
100
134
  Running A Insert Query
101
135
  ```js
102
136
  const user = await new DB('users')
@@ -131,6 +165,16 @@ const users = await new DB('users')
131
165
  },
132
166
  ]).save()
133
167
 
168
+ const users = await new DB('users')
169
+ .where('name','tspace4')
170
+ .where('email','tspace4@gmail.com')
171
+ .createNotExists({
172
+ name :'tspace4',
173
+ email : 'tspace4@gmail.com'
174
+ })
175
+ .save()
176
+ // if has exists return null, if not exists created new data
177
+
134
178
  ```
135
179
  Running A Update Query
136
180
  ```js
@@ -160,7 +204,7 @@ const user = await new DB('users')
160
204
  name : 'tspace1**',
161
205
  email : 'tspace1@gmail.com'
162
206
  }).save()
163
- // user => { username : 'tspace1**', email : 'tspace1@gmail.com'}
207
+ // user => { username : 'tspace1**', email : 'tspace1@gmail.com' }
164
208
  ```
165
209
 
166
210
  Running A Delete Query
@@ -170,7 +214,7 @@ const deleted = await new DB('users').where('id',1).delete()
170
214
  ```
171
215
  ## Database Transactions
172
216
 
173
- Within a database transaction, you may use the:
217
+ Within a Database Transaction, you may use the:
174
218
 
175
219
  ```js
176
220
  const connection = await new DB().beginTransaction()
@@ -209,7 +253,7 @@ try {
209
253
  title : `tspace-post3`
210
254
  }
211
255
  ])
212
- .bind(connection) /** don't forget this /*
256
+ .bind(connection) // don't forget this
213
257
  .save()
214
258
 
215
259
  /**
@@ -232,14 +276,16 @@ try {
232
276
  ## Connection
233
277
  When establishing a connection, you may establish options is this:
234
278
  ```js
279
+ const connection = await new DB().getConnection({
280
+ host: 'localhost',
281
+ port : 3306,
282
+ database: 'database'
283
+ username: 'username',
284
+ password: 'password',
285
+ })
286
+
235
287
  const users = await new DB('users')
236
- .connection({
237
- host: 'localhost',
238
- port : 3306,
239
- database: 'database'
240
- username: 'username',
241
- password: 'password',
242
- })
288
+ .bind(connection)
243
289
  .findMany()
244
290
  // users => [{ .... }]
245
291
  ```
@@ -312,8 +358,8 @@ class User extends Model {
312
358
  super()
313
359
  this.useTimestamp() /** created_at , updated_at
314
360
  /**
315
- * @custom
316
361
  *
362
+ * @Custom
317
363
  *
318
364
  * this.useTimestamp({
319
365
  * createdAt : 'created_at',
@@ -353,11 +399,12 @@ class User extends Model {
353
399
  this.hasOne({ name : 'phone' , model : Phone })
354
400
  }
355
401
  /**
402
+ * Mark a method for relationship
356
403
  * @hasOne Get the phone associated with the user. using function callback
357
404
  * @function
358
405
  */
359
406
  phone (callback ?: Function) {
360
- return this.hasOneQuery({ name : 'phone' , model : Phone } , callback)
407
+ return this.hasOneBuilder({ name : 'phone' , model : Phone } , callback)
361
408
  }
362
409
  }
363
410
  export default User
@@ -388,11 +435,12 @@ class Post extends Model {
388
435
  this.hasMany({ name : 'comments' , model : Comment })
389
436
  }
390
437
  /**
438
+ *
391
439
  * @hasManyQuery Get the comments for the post. using function callback
392
440
  * @function
393
441
  */
394
442
  comments (callback ?: Function) {
395
- return this.hasManyQuery({ name : 'comments' , model : Comment } , callback)
443
+ return this.hasManyBuilder({ name : 'comments' , model : Comment } , callback)
396
444
  }
397
445
  }
398
446
  export default Post
@@ -423,11 +471,12 @@ class Phone extends Model {
423
471
  this.belognsTo({ name : 'user' , model : User })
424
472
  }
425
473
  /**
474
+ *
426
475
  * @belongsToQuery Get the user that owns the phone.. using function callback
427
476
  * @function
428
477
  */
429
478
  user (callback ?: Function) {
430
- return this.belongsToQuery({ name : 'user' , model : User }, callback)
479
+ return this.belongsToBuilder({ name : 'user' , model : User }, callback)
431
480
  }
432
481
  }
433
482
  export default Phone
@@ -462,7 +511,7 @@ class User extends Model {
462
511
  * @function
463
512
  */
464
513
  roles (callback ?: Function) {
465
- return this.belognsToManyQuery({ model : Role } , callback)
514
+ return this.belognsToManyBuilder({ model : Role } , callback)
466
515
  }
467
516
  }
468
517
  export default User
@@ -529,13 +578,20 @@ whereSensitive(column , operator , value)
529
578
  whereId(id)
530
579
  whereUser(userId)
531
580
  whereEmail(value)
532
- orWhere(column , operator , value)
533
581
  whereIn(column , [])
534
582
  whereNotIn(column , [])
535
583
  whereNull(column)
536
584
  whereNotNull(column)
537
585
  whereBetween (column , [value1 , value2])
586
+ whereQuery(callback)
587
+ whereRaw(sql)
588
+ whereExists(sql)
538
589
  whereSubQuery(colmn , rawSQL)
590
+ whereNotSubQuery(colmn , rawSQL)
591
+ orWhere(column , operator , value)
592
+ orWhereRaw(sql)
593
+ orWhereIn(column , [])
594
+ orWhereSubQuery(colmn , rawSQL)
539
595
  select(column1 ,column2 ,...N)
540
596
  except(column1 ,column2 ,...N)
541
597
  only(column1 ,column2 ,...N)
@@ -557,6 +613,7 @@ updateOrCreate (objects)
557
613
  connection(options)
558
614
  backup({ database , connection })
559
615
  backupToFile({ filePath, database , connection })
616
+ hook((result) => ...) // callback result to function
560
617
 
561
618
  /**
562
619
  * registry relation in your models
@@ -603,9 +660,14 @@ save() /*for action statements insert update or delete */
603
660
  ```
604
661
 
605
662
  ## Cli
606
- To get started, let's install npm install tspace-mysql -g
663
+ To get started, let's install tspace-mysql
607
664
  you may use a basic cli :
608
665
 
666
+ ```sh
667
+ npm install tspace-mysql -g
668
+
669
+ ```
670
+
609
671
  ## Make Model
610
672
  Command will be placed Model in the specific directory
611
673
  ```js
@@ -731,12 +793,12 @@ timestamp ()
731
793
  * @Attrbuites
732
794
  *
733
795
  */
734
- unsigned ()
735
- unique ()
736
- null ()
737
- notNull ()
796
+ unsigned()
797
+ unique()
798
+ null()
799
+ notNull()
738
800
  primary()
739
- default (string)
740
- defaultTimestamp ()
741
- autoIncrement ()
801
+ default(string)
802
+ defaultTimestamp()
803
+ autoIncrement()
742
804
  ```
@@ -0,0 +1,4 @@
1
+ declare const _default: (cmd: {
2
+ [x: string]: any;
3
+ }) => void;
4
+ export default _default;
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const model_1 = __importDefault(require("../models/model"));
7
+ const pluralize_1 = __importDefault(require("pluralize"));
8
+ const lib_1 = require("../../lib");
9
+ exports.default = (cmd) => {
10
+ const { dir, cwd, type, fs, npm } = cmd;
11
+ if (dir) {
12
+ try {
13
+ fs.accessSync(cwd + `/${dir}`, fs.F_OK, {
14
+ recursive: true
15
+ });
16
+ }
17
+ catch (e) {
18
+ fs.mkdirSync(cwd + `/${dir}`, {
19
+ recursive: true
20
+ });
21
+ }
22
+ }
23
+ const snake2Pascal = (data) => {
24
+ let str = data.split('_');
25
+ for (let i = 0; i < str.length; i++) {
26
+ str[i] = str[i].slice(0, 1).toUpperCase() + str[i].slice(1, str[i].length);
27
+ }
28
+ return str.join('');
29
+ };
30
+ new lib_1.DB().rawQuery('SHOW TABLES')
31
+ .then(tables => {
32
+ var _a;
33
+ for (let i = 0; i < tables.length; i++) {
34
+ const table = String((_a = Object.values(tables[i])) === null || _a === void 0 ? void 0 : _a.shift());
35
+ const model = snake2Pascal(pluralize_1.default.singular(table));
36
+ const data = (0, model_1.default)(model, npm);
37
+ fs.writeFile(`${dir}/${model}.${type !== null && type !== void 0 ? type : 'ts'}`, data, (err) => {
38
+ if (err)
39
+ throw err;
40
+ });
41
+ console.log(`Model : '${model}' created successfully`);
42
+ }
43
+ console.log('\nGenerate Models has completed');
44
+ })
45
+ .catch(err => console.log(err));
46
+ };
package/dist/cli/index.js CHANGED
@@ -3,30 +3,36 @@
3
3
  var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  return (mod && mod.__esModule) ? mod : { "default": mod };
5
5
  };
6
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
6
7
  Object.defineProperty(exports, "__esModule", { value: true });
7
8
  const fs_1 = __importDefault(require("fs"));
8
9
  const make_1 = __importDefault(require("./models/make"));
9
10
  const make_2 = __importDefault(require("./tables/make"));
10
11
  const make_3 = __importDefault(require("./migrate/make"));
12
+ const make_4 = __importDefault(require("./generate/make"));
13
+ const query_1 = __importDefault(require("./query"));
11
14
  const commands = {
15
+ 'query': query_1.default,
12
16
  'make:model': make_1.default,
13
17
  'make:table': make_2.default,
14
18
  'make:migration': make_2.default,
15
- 'migrate': make_3.default
19
+ 'migrate': make_3.default,
20
+ 'generate:models': make_4.default
16
21
  };
17
22
  try {
18
- const name = process.argv.slice(2)?.find(data => {
19
- return data?.includes('--name=');
20
- })?.replace('--name=', '') ?? null;
21
- const migrate = process.argv.slice(2)?.includes('--m') ?? false;
22
- const dir = process.argv.slice(2)?.find(data => {
23
- return data?.includes('--dir=');
24
- })?.replace('--dir=', '/') ?? null;
25
- let type = process.argv.slice(2)?.find(data => {
26
- return data?.includes('--type=');
27
- })?.replace('--type=', '.') ?? '.ts';
23
+ const name = (_c = (_b = (_a = process.argv.slice(2)) === null || _a === void 0 ? void 0 : _a.find(data => {
24
+ return data === null || data === void 0 ? void 0 : data.includes('--name=');
25
+ })) === null || _b === void 0 ? void 0 : _b.replace('--name=', '')) !== null && _c !== void 0 ? _c : null;
26
+ const sql = (_d = process.argv.slice(3)[0]) !== null && _d !== void 0 ? _d : '';
27
+ const migrate = (_f = (_e = process.argv.slice(2)) === null || _e === void 0 ? void 0 : _e.includes('--m')) !== null && _f !== void 0 ? _f : false;
28
+ const dir = (_j = (_h = (_g = process.argv.slice(2)) === null || _g === void 0 ? void 0 : _g.find(data => {
29
+ return data === null || data === void 0 ? void 0 : data.includes('--dir=');
30
+ })) === null || _h === void 0 ? void 0 : _h.replace('--dir=', '/')) !== null && _j !== void 0 ? _j : null;
31
+ let type = (_m = (_l = (_k = process.argv.slice(2)) === null || _k === void 0 ? void 0 : _k.find(data => {
32
+ return data === null || data === void 0 ? void 0 : data.includes('--type=');
33
+ })) === null || _l === void 0 ? void 0 : _l.replace('--type=', '.')) !== null && _m !== void 0 ? _m : '.ts';
28
34
  type = ['.js', '.ts'].includes(type) ? type : '.ts';
29
- const file = process.argv.slice(3)?.shift() ?? '';
35
+ const file = (_o = process.argv.slice(3)[0]) !== null && _o !== void 0 ? _o : '';
30
36
  const cmd = {
31
37
  name,
32
38
  file,
@@ -35,10 +41,11 @@ try {
35
41
  type,
36
42
  cwd: process.cwd(),
37
43
  fs: fs_1.default,
44
+ sql,
38
45
  npm: 'tspace-mysql'
39
46
  };
40
47
  commands[process.argv[2]](cmd);
41
48
  }
42
49
  catch (err) {
43
- console.log(`readme https://www.npmjs.com/package/tspace-mysql`);
50
+ console.log(`Readme https://www.npmjs.com/package/tspace-mysql`);
44
51
  }
@@ -2,22 +2,23 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const child_process_1 = require("child_process");
4
4
  exports.default = (formCommand) => {
5
+ var _a, _b, _c;
5
6
  const { type, dir, cwd, fs } = formCommand;
6
7
  try {
7
8
  if (dir == null)
8
9
  throw new Error('Not found directory');
9
10
  const path = `${cwd}/${dir}`;
10
- const files = fs.readdirSync(path) ?? [];
11
- if (!files?.length)
11
+ const files = (_a = fs.readdirSync(path)) !== null && _a !== void 0 ? _a : [];
12
+ if (!(files === null || files === void 0 ? void 0 : files.length))
12
13
  console.log('this folder is empty');
13
14
  const cmd = type === '.js' ? 'node' : 'ts-node';
14
15
  for (const _file of files) {
15
16
  const run = (0, child_process_1.exec)(`${cmd} ${path}/${_file}`);
16
- run?.stdout?.on('data', (data) => {
17
+ (_b = run === null || run === void 0 ? void 0 : run.stdout) === null || _b === void 0 ? void 0 : _b.on('data', (data) => {
17
18
  if (data)
18
19
  console.log(data);
19
20
  });
20
- run?.stderr?.on('data', (err) => {
21
+ (_c = run === null || run === void 0 ? void 0 : run.stderr) === null || _c === void 0 ? void 0 : _c.on('data', (err) => {
21
22
  if (err)
22
23
  console.error(err);
23
24
  });
@@ -1,4 +1,4 @@
1
- declare const _default: (formCommand: {
1
+ declare const _default: (cmd: {
2
2
  [x: string]: any;
3
3
  }) => void;
4
4
  export default _default;
@@ -6,8 +6,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  const model_1 = __importDefault(require("./model"));
7
7
  const table_1 = __importDefault(require("../tables/table"));
8
8
  const pluralize_1 = __importDefault(require("pluralize"));
9
- exports.default = (formCommand) => {
10
- const { file, migrate, dir, type, cwd, fs, npm } = formCommand;
9
+ exports.default = (cmd) => {
10
+ const { file, migrate, dir, type, cwd, fs, npm } = cmd;
11
11
  if (dir) {
12
12
  try {
13
13
  fs.accessSync(cwd + `/${dir}`, fs.F_OK, {
@@ -14,10 +14,9 @@ class ${model} extends Model {
14
14
  * this.usePrimaryKey('id') // => runing a uuid (universally unique identifier) when insert new data
15
15
  * this.useTimestamp({ createdAt : 'created_at' , updatedAt : 'updated_at' }) // runing a timestamp when insert or update
16
16
  * this.useSoftDelete()
17
- * this.useDisableSoftDeleteInRelations()
18
- * this.useTable('Users')
19
- * this.useTableSingular()
20
- * this.useTablePlural()
17
+ * this.useTable('users')
18
+ * this.useTableSingular() // 'user'
19
+ * this.useTablePlural() // 'users'
21
20
  * this.usePattern('snake_case')
22
21
  * this.useUUID('uuid')
23
22
  * this.useRegistry()
@@ -0,0 +1,4 @@
1
+ declare const _default: (cmd: {
2
+ [x: string]: any;
3
+ }) => void;
4
+ export default _default;
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const lib_1 = require("../../lib");
4
+ exports.default = (cmd) => {
5
+ const { sql } = cmd;
6
+ new lib_1.DB().rawQuery(sql).then(result => console.log(result));
7
+ };
@@ -1,29 +1,4 @@
1
- export interface PoolCallback {
2
- query: (sql: string, callback: (err: any, result: any) => void) => void;
3
- release: () => void;
4
- }
5
- export interface ConnectionTransaction {
6
- query: (sql: string) => Promise<any>;
7
- startTransaction: () => Promise<any>;
8
- commit: () => Promise<any>;
9
- rollback: () => Promise<any>;
10
- }
11
- export interface Connection {
12
- query: (sql: string) => Promise<any>;
13
- connection: () => Promise<ConnectionTransaction>;
14
- }
15
- export interface Options {
16
- [key: string]: any;
17
- connectionLimit?: number;
18
- dateStrings?: boolean;
19
- waitForConnections?: boolean;
20
- charset?: string;
21
- host: string;
22
- port: number;
23
- database: string;
24
- user: string;
25
- password: string;
26
- }
1
+ import { Connection, Options } from '../tspace/Interface';
27
2
  export declare class PoolConnection {
28
3
  private OPTIONS;
29
4
  /**
@@ -31,12 +6,6 @@ export declare class PoolConnection {
31
6
  * @Init a options connection pool
32
7
  */
33
8
  constructor(options?: Options);
34
- /**
35
- *
36
- * Set a options connection pool
37
- * @return {this} this
38
- */
39
- options(options: Options): this;
40
9
  /**
41
10
  *
42
11
  * Get a connection to database
@@ -49,6 +18,13 @@ export declare class PoolConnection {
49
18
  private _loadOptions;
50
19
  private _messageError;
51
20
  }
21
+ /**
22
+ *
23
+ * Connection to database when service is started
24
+ * @return {Connection} Connection
25
+ * @property {Function} Connection.query
26
+ * @property {Function} Connection.connection
27
+ */
52
28
  declare const pool: Connection;
53
29
  export { pool as Pool };
54
30
  export default pool;
@@ -6,31 +6,19 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.Pool = exports.PoolConnection = void 0;
7
7
  const fs_1 = __importDefault(require("fs"));
8
8
  const path_1 = __importDefault(require("path"));
9
- const env_1 = __importDefault(require("../config/env"));
9
+ const options_1 = __importDefault(require("./options"));
10
10
  const mysql2_1 = require("mysql2");
11
11
  class PoolConnection {
12
- OPTIONS = this._loadOptions();
13
12
  /**
14
13
  *
15
14
  * @Init a options connection pool
16
15
  */
17
16
  constructor(options) {
17
+ this.OPTIONS = this._loadOptions();
18
18
  if (options) {
19
- this.OPTIONS = new Map(Object.entries({
20
- ...Object.fromEntries(this.OPTIONS),
21
- ...JSON.parse(JSON.stringify(options))
22
- }));
19
+ this.OPTIONS = new Map(Object.entries(Object.assign(Object.assign({}, Object.fromEntries(this.OPTIONS)), JSON.parse(JSON.stringify(options)))));
23
20
  }
24
21
  }
25
- /**
26
- *
27
- * Set a options connection pool
28
- * @return {this} this
29
- */
30
- options(options) {
31
- this.OPTIONS = new Map(Object.entries(options));
32
- return this;
33
- }
34
22
  /**
35
23
  *
36
24
  * Get a connection to database
@@ -40,17 +28,17 @@ class PoolConnection {
40
28
  */
41
29
  connection() {
42
30
  const pool = (0, mysql2_1.createPool)(Object.fromEntries(this.OPTIONS));
43
- const conn = pool.getConnection((err, _) => {
44
- if (!err)
45
- return;
46
- const message = this._messageError.bind(this);
47
- if (!env_1.default.CONNECTION_ERROR)
48
- return;
49
- process.nextTick(() => {
50
- console.log(message());
51
- return process.exit();
31
+ if (options_1.default.CONNECTION_ERROR) {
32
+ pool.getConnection((err, _) => {
33
+ if (err == null || !err)
34
+ return;
35
+ const message = this._messageError.bind(this);
36
+ process.nextTick(() => {
37
+ console.log(message());
38
+ return process.exit();
39
+ });
52
40
  });
53
- });
41
+ }
54
42
  return {
55
43
  query: (sql) => {
56
44
  return new Promise((resolve, reject) => {
@@ -91,19 +79,21 @@ class PoolConnection {
91
79
  }
92
80
  _defaultOptions() {
93
81
  return new Map(Object.entries({
94
- connectionLimit: Number(env_1.default.CONNECTION_LIMIT),
95
- dateStrings: Boolean(env_1.default.DATE_STRINGS),
96
- connectTimeout: Number(env_1.default.TIMEOUT),
97
- waitForConnections: true,
98
- queueLimit: Number(env_1.default.QUEUE_LIMIT),
99
- charset: 'utf8mb4',
100
- host: String(env_1.default.HOST),
101
- port: Number.isNaN(Number(env_1.default.PORT))
82
+ connectionLimit: Number(options_1.default.CONNECTION_LIMIT),
83
+ dateStrings: Boolean(options_1.default.DATE_STRINGS),
84
+ connectTimeout: Number(options_1.default.TIMEOUT),
85
+ waitForConnections: Boolean(options_1.default.WAIT_FOR_CONNECTIONS),
86
+ queueLimit: Number(options_1.default.QUEUE_LIMIT),
87
+ charset: String(options_1.default.CHARSET),
88
+ host: String(options_1.default.HOST),
89
+ port: Number.isNaN(Number(options_1.default.PORT))
102
90
  ? 3306
103
- : Number(env_1.default.PORT),
104
- database: String(env_1.default.DATABASE),
105
- user: String(env_1.default.USERNAME),
106
- password: String(env_1.default.PASSWORD) === '' ? '' : String(env_1.default.PASSWORD)
91
+ : Number(options_1.default.PORT),
92
+ database: String(options_1.default.DATABASE),
93
+ user: String(options_1.default.USERNAME),
94
+ password: String(options_1.default.PASSWORD) !== ''
95
+ ? String(options_1.default.PASSWORD)
96
+ : ''
107
97
  }));
108
98
  }
109
99
  _loadOptions() {
@@ -135,6 +125,13 @@ class PoolConnection {
135
125
  }
136
126
  }
137
127
  exports.PoolConnection = PoolConnection;
128
+ /**
129
+ *
130
+ * Connection to database when service is started
131
+ * @return {Connection} Connection
132
+ * @property {Function} Connection.query
133
+ * @property {Function} Connection.connection
134
+ */
138
135
  const pool = new PoolConnection().connection();
139
136
  exports.Pool = pool;
140
137
  exports.default = pool;
@@ -0,0 +1,4 @@
1
+ declare const _default: Readonly<{
2
+ [x: string]: any;
3
+ }>;
4
+ export default _default;