tspace-mysql 1.3.4 → 1.3.5

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.
@@ -15,8 +15,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.Model = void 0;
16
16
  const pluralize_1 = __importDefault(require("pluralize"));
17
17
  const DB_1 = require("./DB");
18
+ const Schema_1 = require("./Schema");
18
19
  const AbstractModel_1 = require("./AbstractModel");
19
20
  const ProxyHandler_1 = require("./ProxyHandler");
21
+ const StateHandler_1 = require("./StateHandler");
20
22
  class Model extends AbstractModel_1.AbstractModel {
21
23
  constructor() {
22
24
  super();
@@ -36,30 +38,84 @@ class Model extends AbstractModel_1.AbstractModel {
36
38
  /**
37
39
  *
38
40
  * define for initialize of models
41
+ * @example
42
+ * class User extends Model {
43
+ * define() {
44
+ * this.useUUID()
45
+ * this.usePrimaryKey('id')
46
+ * this.useTimestamp()
47
+ * this.useSoftDelete()
48
+ * }
49
+ * }
39
50
  * @return {void} void
40
51
  */
41
52
  define() { }
42
53
  /**
43
54
  *
44
- * boot for initialize of models
55
+ * boot for initialize of models like constructor()
56
+ * @example
57
+ * class User extends Model {
58
+ * boot() {
59
+ * this.useUUID()
60
+ * this.usePrimaryKey('id')
61
+ * this.useTimestamp()
62
+ * this.useSoftDelete()
63
+ * }
64
+ * }
45
65
  * @return {void} void
46
66
  */
47
67
  boot() { }
48
68
  /**
49
69
  *
50
- * Assign function callback in model
70
+ * Assign auto create table when not exists table
71
+ * @param {object} schema using Blueprint for schema
72
+ * @example
73
+ * import { Blueprint } from 'tspace-mysql'
74
+ * class User extends Model {
75
+ * constructor() {
76
+ * this.useCreateTableIfNotExists ({
77
+ * id : new Blueprint().int().notNull().primary().autoIncrement(),
78
+ * uuid : new Blueprint().varchar(50).null(),
79
+ * email : new Blueprint().varchar(50).null(),
80
+ * name : new Blueprint().varchar(255).null(),
81
+ * created_at : new Blueprint().timestamp().null(),
82
+ * updated_at : new Blueprint().timestamp().null()
83
+ * })
84
+ * }
85
+ * }
86
+ * @return {this} this
87
+ */
88
+ useCreateTableIfNotExists(schema) {
89
+ this.$state.set('CREATE_TABLE', schema);
90
+ return this;
91
+ }
92
+ /**
93
+ *
94
+ * Assign function callback in model like constructor()
95
+ * @example
96
+ * class User extends Model {
97
+ * constructor() {
98
+ * this.useRegistry()
99
+ * }
100
+ * }
51
101
  * @return {this} this
52
102
  */
53
103
  useRegistry() {
54
- this.$state.set('REGISTRY', Object.assign(Object.assign({}, this.$state.get('REGISTRY')), { attach: this._attach, detach: this._detach }));
104
+ this.$state.set('REGISTRY', Object.assign(Object.assign({}, this.$state.get('REGISTRY')), { '$attach': this._attach, '$detach': this._detach }));
55
105
  return this;
56
106
  }
57
107
  /**
58
108
  *
59
109
  * Assign model calling all relationships in model
110
+ * @example
111
+ * class User extends Model {
112
+ * constructor() {
113
+ * this.useLoadRelationInRegistry()
114
+ * }
115
+ * }
60
116
  * @return {this} this
61
117
  */
62
- useLoadRelationInRegistry() {
118
+ useLoadRelationsInRegistry() {
63
119
  const relations = this.$state.get('RELATION').map((r) => String(r.name));
64
120
  if (relations.length)
65
121
  this.with(...Array.from(new Set(relations)));
@@ -68,6 +124,12 @@ class Model extends AbstractModel_1.AbstractModel {
68
124
  /**
69
125
  *
70
126
  * Assign model built-in relation functions to a results
127
+ * @example
128
+ * class User extends Model {
129
+ * constructor() {
130
+ * this.useBuiltInRelationsFunction()
131
+ * }
132
+ * }
71
133
  * @return {this} this
72
134
  */
73
135
  useBuiltInRelationFunctions() {
@@ -77,6 +139,13 @@ class Model extends AbstractModel_1.AbstractModel {
77
139
  /**
78
140
  *
79
141
  * Assign primary column in model
142
+ * @param {string} primary
143
+ * @example
144
+ * class User extends Model {
145
+ * constructor() {
146
+ * this.usePrimaryKey()
147
+ * }
148
+ * }
80
149
  * @return {this} this
81
150
  */
82
151
  usePrimaryKey(primary) {
@@ -86,6 +155,12 @@ class Model extends AbstractModel_1.AbstractModel {
86
155
  /**
87
156
  * Assign generate uuid when creating in model
88
157
  * @param {string?} column [column=uuid] make new name column for custom column replace uuid with this
158
+ * @example
159
+ * class User extends Model {
160
+ * constructor() {
161
+ * this.useUUID()
162
+ * }
163
+ * }
89
164
  * @return {this} this
90
165
  */
91
166
  useUUID(column) {
@@ -106,6 +181,12 @@ class Model extends AbstractModel_1.AbstractModel {
106
181
  *
107
182
  * Assign in model use pattern [snake_case , camelCase]
108
183
  * @param {string} pattern
184
+ * @example
185
+ * class User extends Model {
186
+ * constructor() {
187
+ * this.usePattern('camelCase')
188
+ * }
189
+ * }
109
190
  * @return {this} this
110
191
  */
111
192
  usePattern(pattern) {
@@ -121,7 +202,13 @@ class Model extends AbstractModel_1.AbstractModel {
121
202
  *
122
203
  * Assign in model show data not be deleted
123
204
  * Relations has reference this method
124
- * @param {string?} column
205
+ * @param {string?} column default deleted_at
206
+ * @example
207
+ * class User extends Model {
208
+ * constructor() {
209
+ * this.useSoftDelete('delete_at')
210
+ * }
211
+ * }
125
212
  * @return {this} this
126
213
  */
127
214
  useSoftDelete(column) {
@@ -136,6 +223,15 @@ class Model extends AbstractModel_1.AbstractModel {
136
223
  * @param {object} timestampFormat
137
224
  * @property {string} timestampFormat.createdAt - change new name column replace by default [created at]
138
225
  * @property {string} timestampFormat.updatedAt - change new name column replace by default updated at
226
+ * @example
227
+ * class User extends Model {
228
+ * constructor() {
229
+ * this.useTimestamp({
230
+ * createdAt : 'createdAt',
231
+ * updatedAt : 'updatedAt'
232
+ * })
233
+ * }
234
+ * }
139
235
  * @return {this} this
140
236
  */
141
237
  useTimestamp(timestampFormat) {
@@ -152,6 +248,12 @@ class Model extends AbstractModel_1.AbstractModel {
152
248
  *
153
249
  * Assign table name in model
154
250
  * @param {string} table table name in database
251
+ * @example
252
+ * class User extends Model {
253
+ * constructor() {
254
+ * this.useTable('setTableNameIsUser') // => 'setTableNameIsUser'
255
+ * }
256
+ * }
155
257
  * @return {this} this
156
258
  */
157
259
  useTable(table) {
@@ -161,6 +263,12 @@ class Model extends AbstractModel_1.AbstractModel {
161
263
  /**
162
264
  *
163
265
  * Assign table name in model with signgular pattern
266
+ * @example
267
+ * class User extends Model {
268
+ * constructor() {
269
+ * this.useTableSingular() // => 'user'
270
+ * }
271
+ * }
164
272
  * @return {this} this
165
273
  */
166
274
  useTableSingular() {
@@ -172,6 +280,12 @@ class Model extends AbstractModel_1.AbstractModel {
172
280
  /**
173
281
  *
174
282
  * Assign table name in model with pluarl pattern
283
+ * @example
284
+ * class User extends Model {
285
+ * constructor() {
286
+ * this.useTablePlural() // => 'users'
287
+ * }
288
+ * }
175
289
  * @return {this} this
176
290
  */
177
291
  useTablePlural() {
@@ -183,7 +297,18 @@ class Model extends AbstractModel_1.AbstractModel {
183
297
  /**
184
298
  *
185
299
  * Assign schema column in model for validation data types
186
- * @param {Object<Function>} schema types (String Number and Date)
300
+ * @param {Object<NumberConstructor | StringConstructor | DateConstructor>} schema types (String Number and Date)
301
+ * @example
302
+ * class User extends Model {
303
+ * constructor() {
304
+ * this.useSchema({
305
+ * id : Number,
306
+ * email : String,
307
+ * name : String,
308
+ * date : Date
309
+ * })
310
+ * }
311
+ * }
187
312
  * @return {this} this
188
313
  */
189
314
  useSchema(schema) {
@@ -192,11 +317,17 @@ class Model extends AbstractModel_1.AbstractModel {
192
317
  }
193
318
  /**
194
319
  * Assign hook function when execute returned results to callback function
195
- * @param {Function} arrayFunction function for callback result
320
+ * @param {Array<Function>} arrayFunctions functions for callback result
321
+ * @example
322
+ * class User extends Model {
323
+ * constructor() {
324
+ * this.useHook([(results) => console.log(results)])
325
+ * }
326
+ * }
196
327
  * @return {this}
197
328
  */
198
- useHook(functions) {
199
- for (const func of functions) {
329
+ useHook(arrayFunctions) {
330
+ for (const func of arrayFunctions) {
200
331
  if (typeof func !== "function")
201
332
  throw new Error(`this '${func}' is not a function`);
202
333
  this.$state.set('HOOK', [...this.$state.get('HOOK'), func]);
@@ -211,7 +342,7 @@ class Model extends AbstractModel_1.AbstractModel {
211
342
  return __awaiter(this, void 0, void 0, function* () {
212
343
  if (this.$state.get('SCHEMA')) {
213
344
  const columns = Object.keys(this.$state.get('SCHEMA'));
214
- const removeExcept = columns.filter((column) => !this.$state.get('EXCEPT').includes(column));
345
+ const removeExcept = columns.filter((column) => !String(this.$state.get('EXCEPT')).includes(column));
215
346
  return removeExcept;
216
347
  }
217
348
  const rawColumns = yield this.queryStatement([
@@ -221,7 +352,7 @@ class Model extends AbstractModel_1.AbstractModel {
221
352
  `${this.$state.get('TABLE_NAME')}`
222
353
  ].join(' '));
223
354
  const columns = rawColumns.map((column) => column.Field);
224
- const removeExcept = columns.filter((column) => !this.$state.get('EXCEPT').includes(column));
355
+ const removeExcept = columns.filter((column) => !String(this.$state.get('EXCEPT')).includes(column));
225
356
  return removeExcept;
226
357
  });
227
358
  }
@@ -268,6 +399,7 @@ class Model extends AbstractModel_1.AbstractModel {
268
399
  const copy = Object.fromEntries(instance.$state.get());
269
400
  const newInstance = new Model();
270
401
  newInstance.$state.clone(copy);
402
+ newInstance.$state.set('SAVE', '');
271
403
  if ((options === null || options === void 0 ? void 0 : options.insert) == null)
272
404
  newInstance.$state.set('INSERT', '');
273
405
  if ((options === null || options === void 0 ? void 0 : options.update) == null)
@@ -276,16 +408,39 @@ class Model extends AbstractModel_1.AbstractModel {
276
408
  newInstance.$state.set('DELETE', '');
277
409
  if ((options === null || options === void 0 ? void 0 : options.where) == null)
278
410
  newInstance.$state.set('WHERE', '');
411
+ if ((options === null || options === void 0 ? void 0 : options.limit) == null)
412
+ newInstance.$state.set('LIMIT', '');
413
+ if ((options === null || options === void 0 ? void 0 : options.offset) == null)
414
+ newInstance.$state.set('OFFSET', '');
279
415
  return newInstance;
280
416
  }
281
- /**
282
- * Assign ignore delete_at in model
283
- * @param {boolean} condition
284
- * @return {this} this
285
- */
286
- ignoreSoftDelete(condition = false) {
287
- this.$state.set('SOFT_DELETE', condition);
288
- return this;
417
+ queryStatement(sql) {
418
+ return __awaiter(this, void 0, void 0, function* () {
419
+ try {
420
+ if (this.$state.get('DEBUG'))
421
+ this.$utils.consoleDebug(sql);
422
+ this.$state.set('QUERIES', this.$state.get('QUERIES') + 1);
423
+ const result = yield this.$pool.query(sql);
424
+ return result;
425
+ }
426
+ catch (e) {
427
+ const createTable = this.$state.get('CREATE_TABLE');
428
+ const tableName = this.$state.get('TABLE_NAME');
429
+ if (createTable == null)
430
+ throw e;
431
+ if (this.$state.get('QUERIES') > 3)
432
+ throw e;
433
+ try {
434
+ yield new Schema_1.Schema()
435
+ .debug(this.$state.get('DEBUG'))
436
+ .createTable(tableName, createTable);
437
+ }
438
+ catch (e) {
439
+ throw e;
440
+ }
441
+ return yield this.queryStatement(sql);
442
+ }
443
+ });
289
444
  }
290
445
  /**
291
446
  * Assign table name
@@ -305,6 +460,15 @@ class Model extends AbstractModel_1.AbstractModel {
305
460
  this.$state.set('SOFT_DELETE', condition);
306
461
  return this;
307
462
  }
463
+ /**
464
+ * Assign ignore delete_at in model
465
+ * @param {boolean} condition
466
+ * @return {this} this
467
+ */
468
+ ignoreSoftDelete(condition = false) {
469
+ this.$state.set('SOFT_DELETE', condition);
470
+ return this;
471
+ }
308
472
  /**
309
473
  * Assign build in function to result of data
310
474
  * @param {object} func
@@ -318,6 +482,24 @@ class Model extends AbstractModel_1.AbstractModel {
318
482
  *
319
483
  * Use relations in registry of model return result of relation query
320
484
  * @param {...string} nameRelations ...name registry in models using (hasOne , hasMany , belongsTo , belongsToMany)
485
+ * @example
486
+ * import { Model } from 'tspace-mysql'
487
+ * class User extends Model {
488
+ * constructor(){
489
+ * super()
490
+ * this.hasMany({ name : 'posts' , model : Post })
491
+ * }
492
+ * }
493
+ *
494
+ * class Post extends Model {
495
+ * constructor(){
496
+ * super()
497
+ * this.hasMany({ name : 'comments' , model : Comment })
498
+ * this.belongsTo({ name : 'user' , model : User })
499
+ * }
500
+ * }
501
+ * // use with for results of relationship
502
+ * await new User().with('posts').findMany()
321
503
  * @return {this} this
322
504
  */
323
505
  with(...nameRelations) {
@@ -359,6 +541,24 @@ class Model extends AbstractModel_1.AbstractModel {
359
541
  *
360
542
  * Use relations in registry of model return only exists result of relation query
361
543
  * @param {...string} nameRelations if data exists return blank
544
+ * @example
545
+ * import { Model } from 'tspace-mysql'
546
+ * class User extends Model {
547
+ * constructor(){
548
+ * super()
549
+ * this.hasMany({ name : 'posts' , model : Post })
550
+ * }
551
+ * }
552
+ *
553
+ * class Post extends Model {
554
+ * constructor(){
555
+ * super()
556
+ * this.hasMany({ name : 'comments' , model : Comment })
557
+ * this.belongsTo({ name : 'user' , model : User })
558
+ * }
559
+ * }
560
+ * // use with for results of relationship if relations is exists
561
+ * await new User().withExists('posts').findMany()
362
562
  * @return {this} this
363
563
  */
364
564
  withExists(...nameRelations) {
@@ -381,6 +581,24 @@ class Model extends AbstractModel_1.AbstractModel {
381
581
  *
382
582
  * Use relations in registry of model return only exists result of relation query
383
583
  * @param {...string} nameRelations if data exists return blank
584
+ * @example
585
+ * import { Model } from 'tspace-mysql'
586
+ * class User extends Model {
587
+ * constructor(){
588
+ * super()
589
+ * this.hasMany({ name : 'posts' , model : Post })
590
+ * }
591
+ * }
592
+ *
593
+ * class Post extends Model {
594
+ * constructor(){
595
+ * super()
596
+ * this.hasMany({ name : 'comments' , model : Comment })
597
+ * this.belongsTo({ name : 'user' , model : User })
598
+ * }
599
+ * }
600
+ * // use with for results of relationship if relations is exists
601
+ * await new User().has('posts').findMany()
384
602
  * @return {this} this
385
603
  */
386
604
  has(...nameRelations) {
@@ -391,6 +609,45 @@ class Model extends AbstractModel_1.AbstractModel {
391
609
  * Use relation '${name}' registry of model return callback this query model
392
610
  * @param {string} nameRelation name relation in registry in your model
393
611
  * @param {function} callback query callback
612
+ * @example
613
+ * import { Model } from 'tspace-mysql'
614
+ * class User extends Model {
615
+ * constructor(){
616
+ * super()
617
+ * this.hasMany({ name : 'posts' , model : Post })
618
+ * }
619
+ * }
620
+ *
621
+ * class Post extends Model {
622
+ * constructor(){
623
+ * super()
624
+ * this.hasMany({ name : 'comments' , model : Comment })
625
+ * this.belongsTo({ name : 'user' , model : User })
626
+ * }
627
+ * }
628
+ *
629
+ * class Comment extends Model {
630
+ * constructor(){
631
+ * super()
632
+ * this.hasMany({ name : 'users' , model : User })
633
+ * this.belongsTo({ name : 'post' , model : Post })
634
+ * }
635
+ * }
636
+ *
637
+ * await new User().with('posts')
638
+ * .withQuery('posts', (query : Post) => {
639
+ * return query.with('comments','user')
640
+ * .withQuery('comments', (query : Comment) => {
641
+ * return query.with('user','post')
642
+ * })
643
+ * .withQuery('user', (query : User) => {
644
+ * return query.with('posts').withQuery('posts',(query : Post)=> {
645
+ * return query.with('comments','user')
646
+ * // relation n, n, ...n
647
+ * })
648
+ * })
649
+ * })
650
+ * .findMany()
394
651
  * @return {this} this
395
652
  */
396
653
  withQuery(nameRelation, callback) {
@@ -404,8 +661,26 @@ class Model extends AbstractModel_1.AbstractModel {
404
661
  }
405
662
  /**
406
663
  *
407
- * Use relations in registry of model retrun result of relation query
664
+ * Use relations in registry of model return result of relation query
408
665
  * @param {...string} nameRelations ...name registry in models using (hasOne , hasMany , belongsTo , belongsToMany)
666
+ * @example
667
+ * import { Model } from 'tspace-mysql'
668
+ * class User extends Model {
669
+ * constructor(){
670
+ * super()
671
+ * this.hasMany({ name : 'posts' , model : Post })
672
+ * }
673
+ * }
674
+ *
675
+ * class Post extends Model {
676
+ * constructor(){
677
+ * super()
678
+ * this.hasMany({ name : 'comments' , model : Comment })
679
+ * this.belongsTo({ name : 'user' , model : User })
680
+ * }
681
+ * }
682
+ * // use with for results of relationship
683
+ * await new User().relations('posts').findMany()
409
684
  * @return {this} this
410
685
  */
411
686
  relations(...nameRelations) {
@@ -415,7 +690,25 @@ class Model extends AbstractModel_1.AbstractModel {
415
690
  *
416
691
  * Use relations in registry of model return only exists result of relation query
417
692
  * @param {...string} nameRelations if data exists return blank
418
- * @return {this}
693
+ * @example
694
+ * import { Model } from 'tspace-mysql'
695
+ * class User extends Model {
696
+ * constructor(){
697
+ * super()
698
+ * this.hasMany({ name : 'posts' , model : Post })
699
+ * }
700
+ * }
701
+ *
702
+ * class Post extends Model {
703
+ * constructor(){
704
+ * super()
705
+ * this.hasMany({ name : 'comments' , model : Comment })
706
+ * this.belongsTo({ name : 'user' , model : User })
707
+ * }
708
+ * }
709
+ * // use with for results of relationship if relations is exists
710
+ * await new User().relationsExists('posts').findMany()
711
+ * @return {this} this
419
712
  */
420
713
  relationsExists(...nameRelations) {
421
714
  return this.withExists(...nameRelations);
@@ -425,6 +718,45 @@ class Model extends AbstractModel_1.AbstractModel {
425
718
  * Use relation '${name}' registry of model return callback this query model
426
719
  * @param {string} nameRelation name relation in registry in your model
427
720
  * @param {function} callback query callback
721
+ * @example
722
+ * import { Model } from 'tspace-mysql'
723
+ * class User extends Model {
724
+ * constructor(){
725
+ * super()
726
+ * this.hasMany({ name : 'posts' , model : Post })
727
+ * }
728
+ * }
729
+ *
730
+ * class Post extends Model {
731
+ * constructor(){
732
+ * super()
733
+ * this.hasMany({ name : 'comments' , model : Comment })
734
+ * this.belongsTo({ name : 'user' , model : User })
735
+ * }
736
+ * }
737
+ *
738
+ * class Comment extends Model {
739
+ * constructor(){
740
+ * super()
741
+ * this.hasMany({ name : 'users' , model : User })
742
+ * this.belongsTo({ name : 'post' , model : Post })
743
+ * }
744
+ * }
745
+ *
746
+ * await new User().with('posts')
747
+ * .relationQuery('posts', (query : Post) => {
748
+ * return query.with('comments','user')
749
+ * .relationQuery('comments', (query : Comment) => {
750
+ * return query.with('user','post')
751
+ * })
752
+ * .relationQuery('user', (query : User) => {
753
+ * return query.with('posts').relationQuery('posts',(query : Post)=> {
754
+ * return query.with('comments','user')
755
+ * // relation n, n, ...n
756
+ * })
757
+ * })
758
+ * })
759
+ * .findMany()
428
760
  * @return {this} this
429
761
  */
430
762
  relationQuery(nameRelation, callback) {
@@ -792,7 +1124,7 @@ class Model extends AbstractModel_1.AbstractModel {
792
1124
  this.selectRaw(`${this.$constants('AVG')}(${column}) ${this.$constants('AS')} avg`);
793
1125
  const sql = this._buildQueryModel();
794
1126
  const result = yield this.queryStatement(sql);
795
- return ((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.avg) || 0;
1127
+ return Number(this.resultHandler(((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.avg) || 0));
796
1128
  });
797
1129
  }
798
1130
  /**
@@ -807,7 +1139,7 @@ class Model extends AbstractModel_1.AbstractModel {
807
1139
  this.selectRaw(`${this.$constants('SUM')}(${column}) ${this.$constants('AS')} sum`);
808
1140
  const sql = this._buildQueryModel();
809
1141
  const result = yield this.queryStatement(sql);
810
- return ((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.sum) || 0;
1142
+ return Number(this.resultHandler(((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.sum) || 0));
811
1143
  });
812
1144
  }
813
1145
  /**
@@ -822,7 +1154,7 @@ class Model extends AbstractModel_1.AbstractModel {
822
1154
  this.selectRaw(`${this.$constants('MAX')}(${column}) ${this.$constants('AS')} max`);
823
1155
  const sql = this._buildQueryModel();
824
1156
  const result = yield this.queryStatement(sql);
825
- return ((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.max) || 0;
1157
+ return Number(this.resultHandler(((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.max) || 0));
826
1158
  });
827
1159
  }
828
1160
  /**
@@ -837,7 +1169,7 @@ class Model extends AbstractModel_1.AbstractModel {
837
1169
  this.selectRaw(`${this.$constants('MIN')}(${column}) ${this.$constants('AS')} min`);
838
1170
  const sql = this._buildQueryModel();
839
1171
  const result = yield this.queryStatement(sql);
840
- return ((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.min) || 0;
1172
+ return Number(this.resultHandler(((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.min) || 0));
841
1173
  });
842
1174
  }
843
1175
  /**
@@ -852,7 +1184,7 @@ class Model extends AbstractModel_1.AbstractModel {
852
1184
  this.selectRaw(`${this.$constants('COUNT')}(${column}) ${this.$constants('AS')} total`);
853
1185
  const sql = this._buildQueryModel();
854
1186
  const result = yield this.queryStatement(sql);
855
- return ((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.total) || 0;
1187
+ return Number(this.resultHandler(((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.total) || 0));
856
1188
  });
857
1189
  }
858
1190
  /**
@@ -871,7 +1203,7 @@ class Model extends AbstractModel_1.AbstractModel {
871
1203
  `(${sql})`,
872
1204
  `${this.$constants('AS')} 'exists'`
873
1205
  ].join(' '));
874
- return !!((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.exists) || false;
1206
+ return Boolean(this.resultHandler(!!((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.exists) || false));
875
1207
  });
876
1208
  }
877
1209
  /**
@@ -899,7 +1231,7 @@ class Model extends AbstractModel_1.AbstractModel {
899
1231
  }
900
1232
  this.$state.set('UPDATE', `${sql} ${this.$state.get('WHERE')}`);
901
1233
  const result = yield this.actionStatement({ sql: this.$state.get('UPDATE') });
902
- return (_a = !!result) !== null && _a !== void 0 ? _a : false;
1234
+ return Boolean(this.resultHandler((_a = !!result) !== null && _a !== void 0 ? _a : false));
903
1235
  }
904
1236
  this.$state.set('DELETE', [
905
1237
  `${this.$constants('DELETE')}`,
@@ -908,25 +1240,7 @@ class Model extends AbstractModel_1.AbstractModel {
908
1240
  `${this.$state.get('WHERE')}`
909
1241
  ].join(' '));
910
1242
  const result = yield this.actionStatement({ sql: this.$state.get('DELETE') });
911
- return (_b = !!result) !== null && _b !== void 0 ? _b : false;
912
- });
913
- }
914
- /**
915
- *
916
- * force delete data from the database
917
- * @return {promise<boolean>}
918
- */
919
- forceDelete() {
920
- var _a;
921
- return __awaiter(this, void 0, void 0, function* () {
922
- const sql = [
923
- `${this.$constants('DELETE')}`,
924
- `${this.$state.get('FROM')}`,
925
- `${this.$state.get('TABLE_NAME')}`,
926
- `${this.$state.get('WHERE')}`
927
- ].join(' ');
928
- const result = yield this.actionStatement({ sql });
929
- return (_a = !!result) !== null && _a !== void 0 ? _a : false;
1243
+ return Boolean(this.resultHandler((_b = !!result) !== null && _b !== void 0 ? _b : false));
930
1244
  });
931
1245
  }
932
1246
  /**
@@ -939,14 +1253,20 @@ class Model extends AbstractModel_1.AbstractModel {
939
1253
  return __awaiter(this, void 0, void 0, function* () {
940
1254
  this._validateMethod('first');
941
1255
  if (this.$state.get('VOID'))
942
- return null;
1256
+ return this.resultHandler(null);
943
1257
  if ((_a = this.$state.get('EXCEPT')) === null || _a === void 0 ? void 0 : _a.length)
944
1258
  this.select(...yield this.exceptColumns());
945
1259
  this.limit(1);
946
1260
  if (this.$state.get('RELATIONS_EXISTS')) {
947
- return yield this._execute({ sql: this._queryRelationsExists(), type: 'FIRST' });
1261
+ return yield this._execute({
1262
+ sql: this._queryRelationsExists(),
1263
+ type: 'FIRST'
1264
+ });
948
1265
  }
949
- return yield this._execute({ sql: this._buildQueryModel(), type: 'FIRST' });
1266
+ return yield this._execute({
1267
+ sql: this._buildQueryModel(),
1268
+ type: 'FIRST'
1269
+ });
950
1270
  });
951
1271
  }
952
1272
  /**
@@ -972,9 +1292,17 @@ class Model extends AbstractModel_1.AbstractModel {
972
1292
  this.select(...yield this.exceptColumns());
973
1293
  this.limit(1);
974
1294
  if (this.$state.get('RELATIONS_EXISTS')) {
975
- return yield this._execute({ sql: this._queryRelationsExists(), type: 'FIRST_OR_ERROR', message, options });
1295
+ return yield this._execute({
1296
+ sql: this._queryRelationsExists(),
1297
+ type: 'FIRST_OR_ERROR', message, options
1298
+ });
976
1299
  }
977
- return yield this._execute({ sql: this._buildQueryModel(), type: 'FIRST_OR_ERROR', message, options });
1300
+ return yield this._execute({
1301
+ sql: this._buildQueryModel(),
1302
+ type: 'FIRST_OR_ERROR',
1303
+ message,
1304
+ options
1305
+ });
978
1306
  });
979
1307
  }
980
1308
  /**
@@ -992,43 +1320,6 @@ class Model extends AbstractModel_1.AbstractModel {
992
1320
  * @override Method
993
1321
  * @return {promise<array>}
994
1322
  */
995
- all() {
996
- return __awaiter(this, void 0, void 0, function* () {
997
- const sql = [
998
- `${this.$constants('SELECT')}`,
999
- `*`,
1000
- `${this.$constants('FROM')}`,
1001
- `${this.$state.get('TABLE_NAME')}`
1002
- ].join(' ');
1003
- const result = yield this.queryStatement(sql);
1004
- return result;
1005
- });
1006
- }
1007
- /**
1008
- *
1009
- * @override Method
1010
- * @return {promise<object | null>}
1011
- */
1012
- find(id) {
1013
- return __awaiter(this, void 0, void 0, function* () {
1014
- this._validateMethod('find');
1015
- this._handleSoftDelete();
1016
- const result = yield this.queryStatement([
1017
- `${this.$constants('SELECT')}`,
1018
- `*`,
1019
- `${this.$constants('FROM')}`,
1020
- `${this.$state.get('TABLE_NAME')}`,
1021
- `${this.$constants('WHERE')}`,
1022
- `${this.$state.get('PRIMARY_KEY')} = ${id}`
1023
- ].join(' '));
1024
- return (result === null || result === void 0 ? void 0 : result.shift()) || null;
1025
- });
1026
- }
1027
- /**
1028
- *
1029
- * @override Method
1030
- * @return {promise<array>}
1031
- */
1032
1323
  get() {
1033
1324
  var _a;
1034
1325
  return __awaiter(this, void 0, void 0, function* () {
@@ -1040,7 +1331,10 @@ class Model extends AbstractModel_1.AbstractModel {
1040
1331
  let sql = this._buildQueryModel();
1041
1332
  if (this.$state.get('RELATIONS_EXISTS'))
1042
1333
  sql = this._queryRelationsExists();
1043
- return yield this._execute({ sql, type: 'GET' });
1334
+ return yield this._execute({
1335
+ sql,
1336
+ type: 'GET'
1337
+ });
1044
1338
  });
1045
1339
  }
1046
1340
  /**
@@ -1081,7 +1375,10 @@ class Model extends AbstractModel_1.AbstractModel {
1081
1375
  let sql = this._buildQueryModel();
1082
1376
  if (this.$state.get('RELATIONS_EXISTS'))
1083
1377
  sql = this._queryRelationsExists();
1084
- return yield this._execute({ sql, type: 'PAGINATION' });
1378
+ return yield this._execute({
1379
+ sql,
1380
+ type: 'PAGINATION'
1381
+ });
1085
1382
  });
1086
1383
  }
1087
1384
  /**
@@ -1141,7 +1438,7 @@ class Model extends AbstractModel_1.AbstractModel {
1141
1438
  data: newData
1142
1439
  });
1143
1440
  });
1144
- return resultData;
1441
+ return this.resultHandler(resultData);
1145
1442
  });
1146
1443
  }
1147
1444
  /**
@@ -1322,7 +1619,7 @@ class Model extends AbstractModel_1.AbstractModel {
1322
1619
  }
1323
1620
  /**
1324
1621
  *
1325
- * get schema of table
1622
+ * get schema from table
1326
1623
  * @return {this} this this
1327
1624
  */
1328
1625
  getSchema() {
@@ -1404,7 +1701,7 @@ class Model extends AbstractModel_1.AbstractModel {
1404
1701
  break;
1405
1702
  }
1406
1703
  }
1407
- switch (this.$state.get('SAVE')) {
1704
+ switch (String(this.$state.get('SAVE'))) {
1408
1705
  case 'INSERT_MULTIPLE': return yield this._createMultipleModel();
1409
1706
  case 'INSERT': return yield this._insertModel();
1410
1707
  case 'UPDATE': return yield this._updateModel();
@@ -1432,7 +1729,7 @@ class Model extends AbstractModel_1.AbstractModel {
1432
1729
  ].join(' ');
1433
1730
  const fields = yield this.queryStatement(sql);
1434
1731
  for (let row = 0; row < rows; row++) {
1435
- this._assertError(this.$state.get('TABLE_NAME') === '' || this.$state.get('TABLE_NAME') == null, "unknow this table");
1732
+ this._assertError(this.$state.get('TABLE_NAME') === '' || this.$state.get('TABLE_NAME') == null, "Unknow this table");
1436
1733
  let columnAndValue = {};
1437
1734
  for (const { Field: field, Type: type } of fields) {
1438
1735
  const passed = ['id', '_id', 'uuid', 'deleted_at', 'deletedAt'].some(p => field.toLowerCase() === p);
@@ -1471,8 +1768,8 @@ class Model extends AbstractModel_1.AbstractModel {
1471
1768
  className = this.constructor.name;
1472
1769
  const tb = className.replace(/([A-Z])/g, (str) => '_' + str.toLowerCase()).slice(1);
1473
1770
  if (singular)
1474
- return tb;
1475
- return pluralize_1.default.plural(tb);
1771
+ return this._valuePattern(tb);
1772
+ return pluralize_1.default.plural(this._valuePattern(tb));
1476
1773
  }
1477
1774
  _makeTableName() {
1478
1775
  const tb = this._classToTableName();
@@ -1536,7 +1833,17 @@ class Model extends AbstractModel_1.AbstractModel {
1536
1833
  pluralize_1.default.singular((_d = relationModel.query) === null || _d === void 0 ? void 0 : _d._tableName())
1537
1834
  ].sort().join('_'));
1538
1835
  }
1539
- return { name, as, relation, table, localKey, foreignKey, model, pivot, oldVersion };
1836
+ return {
1837
+ name,
1838
+ as,
1839
+ relation,
1840
+ table,
1841
+ localKey,
1842
+ foreignKey,
1843
+ model,
1844
+ pivot,
1845
+ oldVersion
1846
+ };
1540
1847
  }
1541
1848
  _handleSoftDelete() {
1542
1849
  if (this.$state.get('SOFT_DELETE')) {
@@ -1558,7 +1865,8 @@ class Model extends AbstractModel_1.AbstractModel {
1558
1865
  if (this.$state.get('UPDATE')) {
1559
1866
  sql = [
1560
1867
  this.$state.get('UPDATE'),
1561
- this.$state.get('WHERE')
1868
+ this.$state.get('WHERE'),
1869
+ this.$state.get('LIMIT'),
1562
1870
  ];
1563
1871
  break;
1564
1872
  }
@@ -1635,7 +1943,7 @@ class Model extends AbstractModel_1.AbstractModel {
1635
1943
  continue;
1636
1944
  this._assertError(`This column [ ${column} ] is invalid schema field type`);
1637
1945
  }
1638
- if (result[column] === null)
1946
+ if (result[column] == null)
1639
1947
  continue;
1640
1948
  if (typeOf(result[column]) === typeOf(new s()))
1641
1949
  continue;
@@ -1890,24 +2198,17 @@ class Model extends AbstractModel_1.AbstractModel {
1890
2198
  });
1891
2199
  }
1892
2200
  _pagination(data) {
1893
- var _a, _b;
2201
+ var _a;
1894
2202
  return __awaiter(this, void 0, void 0, function* () {
1895
2203
  const currentPage = +(this.$state.get('PAGE'));
1896
- this.selectRaw([
1897
- `${this.$constants('COUNT')}(${this.$state.get('PRIMARY_KEY')})`,
1898
- `${this.$constants('AS')}`,
1899
- `total`
1900
- ].join(' '));
1901
2204
  const limit = Number(this.$state.get('PER_PAGE'));
1902
2205
  this._assertError(limit < 1, "minimun less 1 of limit");
1903
- const sql = this._buildQueryModel();
1904
- const res = yield this.queryStatement(sql);
1905
- const total = (_a = res.shift().total) !== null && _a !== void 0 ? _a : 0;
2206
+ const total = yield new Model().copyModel(this, { where: true }).count('*');
1906
2207
  let lastPage = Math.ceil(total / limit) || 0;
1907
2208
  lastPage = lastPage > 1 ? lastPage : 1;
1908
2209
  const nextPage = currentPage + 1;
1909
2210
  const prevPage = currentPage - 1 === 0 ? 1 : currentPage - 1;
1910
- const totalPage = (_b = data === null || data === void 0 ? void 0 : data.length) !== null && _b !== void 0 ? _b : 0;
2211
+ const totalPage = (_a = data === null || data === void 0 ? void 0 : data.length) !== null && _a !== void 0 ? _a : 0;
1911
2212
  const meta = {
1912
2213
  total,
1913
2214
  limit,
@@ -1918,21 +2219,17 @@ class Model extends AbstractModel_1.AbstractModel {
1918
2219
  prevPage,
1919
2220
  };
1920
2221
  if (this._isPatternSnakeCase()) {
1921
- return this.$utils.snakeCase(this._result({
2222
+ return this.$utils.snakeCase(this.resultHandler({
1922
2223
  meta,
1923
2224
  data
1924
2225
  }));
1925
2226
  }
1926
- return this._result({
2227
+ return this.resultHandler({
1927
2228
  meta,
1928
2229
  data
1929
2230
  });
1930
2231
  });
1931
2232
  }
1932
- _result(data) {
1933
- this.$state.get('RESULT', data);
1934
- return data;
1935
- }
1936
2233
  _returnEmpty(type, result, message, options) {
1937
2234
  return __awaiter(this, void 0, void 0, function* () {
1938
2235
  let emptyData = null;
@@ -1978,13 +2275,13 @@ class Model extends AbstractModel_1.AbstractModel {
1978
2275
  }
1979
2276
  }
1980
2277
  if (this._isPatternSnakeCase()) {
1981
- const empty = this.$utils.snakeCase(this._result(emptyData));
2278
+ const empty = this.$utils.snakeCase(this.resultHandler(emptyData));
1982
2279
  const hook = this.$state.get('HOOK');
1983
2280
  for (let i in hook)
1984
2281
  yield hook[i](empty);
1985
2282
  return empty;
1986
2283
  }
1987
- const empty = this._result(emptyData);
2284
+ const empty = this.resultHandler(emptyData);
1988
2285
  const hook = this.$state.get('HOOK');
1989
2286
  for (let i in hook)
1990
2287
  yield hook[i](empty);
@@ -2031,10 +2328,10 @@ class Model extends AbstractModel_1.AbstractModel {
2031
2328
  const newData = data.shift();
2032
2329
  const checkProperty = newData.hasOwnProperty(pluck);
2033
2330
  this._assertError(!checkProperty, `Can't find property '${pluck}' of result`);
2034
- result = this._result(newData[pluck]);
2331
+ result = this.resultHandler(newData[pluck]);
2035
2332
  break;
2036
2333
  }
2037
- result = this._result((_c = data.shift()) !== null && _c !== void 0 ? _c : null);
2334
+ result = this.resultHandler((_c = data.shift()) !== null && _c !== void 0 ? _c : null);
2038
2335
  break;
2039
2336
  }
2040
2337
  case 'FIRST_OR_ERROR': {
@@ -2043,10 +2340,10 @@ class Model extends AbstractModel_1.AbstractModel {
2043
2340
  const newData = data.shift();
2044
2341
  const checkProperty = newData.hasOwnProperty(pluck);
2045
2342
  this._assertError(!checkProperty, `Can't find property '${pluck}' of result`);
2046
- result = (_d = this._result(newData[pluck])) !== null && _d !== void 0 ? _d : null;
2343
+ result = (_d = this.resultHandler(newData[pluck])) !== null && _d !== void 0 ? _d : null;
2047
2344
  break;
2048
2345
  }
2049
- result = this._result((_e = data.shift()) !== null && _e !== void 0 ? _e : null);
2346
+ result = this.resultHandler((_e = data.shift()) !== null && _e !== void 0 ? _e : null);
2050
2347
  break;
2051
2348
  }
2052
2349
  case 'GET': {
@@ -2058,17 +2355,17 @@ class Model extends AbstractModel_1.AbstractModel {
2058
2355
  resultArray[chunkIndex].push(item);
2059
2356
  return resultArray;
2060
2357
  }, []);
2061
- result = this._result(r);
2358
+ result = this.resultHandler(r);
2062
2359
  break;
2063
2360
  }
2064
2361
  if (this.$state.get('PLUCK')) {
2065
2362
  const pluck = this.$state.get('PLUCK');
2066
2363
  const newData = data.map((d) => d[pluck]);
2067
2364
  this._assertError(newData.every((d) => d == null), `Can't find property '${pluck}' of result`);
2068
- result = this._result(newData);
2365
+ result = this.resultHandler(newData);
2069
2366
  break;
2070
2367
  }
2071
- result = this._result(data);
2368
+ result = this.resultHandler(data);
2072
2369
  break;
2073
2370
  }
2074
2371
  case 'PAGINATION': {
@@ -2184,11 +2481,11 @@ class Model extends AbstractModel_1.AbstractModel {
2184
2481
  return `${this.$constants('SET')} ${keyValue.join(', ')}`;
2185
2482
  }
2186
2483
  _queryInsertModel(objects) {
2187
- const hasTimestamp = this.$state.get('TIMESTAMP');
2484
+ const hasTimestamp = Boolean(this.$state.get('TIMESTAMP'));
2188
2485
  if (hasTimestamp) {
2189
2486
  const format = this.$state.get('TIMESTAMP_FORMAT');
2190
- const createdAt = this._valuePattern(format.CREATED_AT);
2191
- const updatedAt = this._valuePattern(format.UPDATED_AT);
2487
+ const createdAt = this._valuePattern(String(format === null || format === void 0 ? void 0 : format.CREATED_AT));
2488
+ const updatedAt = this._valuePattern(String(format === null || format === void 0 ? void 0 : format.UPDATED_AT));
2192
2489
  objects = Object.assign(Object.assign({}, objects), { [createdAt]: this.$utils.timestamp(), [updatedAt]: this.$utils.timestamp() });
2193
2490
  }
2194
2491
  const hasUUID = objects.hasOwnProperty(this.$state.get('UUID_FORMAT'));
@@ -2261,17 +2558,17 @@ class Model extends AbstractModel_1.AbstractModel {
2261
2558
  _insertNotExistsModel() {
2262
2559
  return __awaiter(this, void 0, void 0, function* () {
2263
2560
  this._assertError(!this.$state.get('WHERE'), "Can't insert [insertNotExists] without where condition");
2264
- const clone = new Model().bind(this.$pool.get()).copyModel(this, { where: true });
2561
+ const clone = new Model().copyModel(this, { where: true }).bind(this.$pool.get());
2265
2562
  const check = (yield clone.exists()) || false;
2266
2563
  if (check)
2267
- return null;
2564
+ return this.resultHandler(null);
2268
2565
  const [result, id] = yield this.actionStatement({
2269
2566
  sql: this.$state.get('INSERT'),
2270
2567
  returnId: true
2271
2568
  });
2272
2569
  if (!result)
2273
- return null;
2274
- return yield new Model().bind(this.$pool.get()).copyModel(this).where('id', id).first();
2570
+ return this.resultHandler(null);
2571
+ return yield new Model().copyModel(this).bind(this.$pool.get()).where('id', id).first();
2275
2572
  });
2276
2573
  }
2277
2574
  _insertModel() {
@@ -2281,9 +2578,9 @@ class Model extends AbstractModel_1.AbstractModel {
2281
2578
  returnId: true
2282
2579
  });
2283
2580
  if (this.$state.get('VOID'))
2284
- return null;
2581
+ return this.resultHandler(null);
2285
2582
  if (!result)
2286
- return null;
2583
+ return this.resultHandler(null);
2287
2584
  return yield new Model().copyModel(this)
2288
2585
  .where('id', id)
2289
2586
  .bind(this.$pool.get())
@@ -2297,20 +2594,19 @@ class Model extends AbstractModel_1.AbstractModel {
2297
2594
  returnId: true
2298
2595
  });
2299
2596
  if (this.$state.get('VOID'))
2300
- return null;
2597
+ return this.resultHandler(null);
2301
2598
  if (!result)
2302
- return null;
2599
+ return this.resultHandler(null);
2303
2600
  const arrayId = [...Array(result)].map((_, i) => i + id);
2304
2601
  const data = new Model().copyModel(this).bind(this.$pool.get()).whereIn('id', arrayId).get();
2305
2602
  const resultData = data || [];
2306
- this.$state.set('RESULT', resultData);
2307
- return resultData;
2603
+ return this.resultHandler(resultData);
2308
2604
  });
2309
2605
  }
2310
2606
  _updateOrInsertModel() {
2311
2607
  return __awaiter(this, void 0, void 0, function* () {
2312
2608
  this._assertError(!this.$state.get('WHERE'), "Can not update or insert [updateOrInsert] without where condition");
2313
- const clone = new Model().bind(this.$pool.get()).copyModel(this, { where: true });
2609
+ const clone = new Model().copyModel(this, { where: true }).bind(this.$pool.get());
2314
2610
  const check = (yield clone.exists()) || false;
2315
2611
  switch (check) {
2316
2612
  case false: {
@@ -2318,95 +2614,79 @@ class Model extends AbstractModel_1.AbstractModel {
2318
2614
  sql: this.$state.get('INSERT'),
2319
2615
  returnId: true
2320
2616
  });
2321
- if (this.$state.get('VOID'))
2322
- return null;
2323
- if (!result)
2324
- return null;
2325
- const data = yield new Model().bind(this.$pool.get()).copyModel(this).where('id', id).first();
2617
+ if (this.$state.get('VOID') || !result)
2618
+ return this.resultHandler(null);
2619
+ const data = yield new Model().copyModel(this).bind(this.$pool.get()).where('id', id).first();
2326
2620
  const resultData = data == null
2327
2621
  ? null
2328
- : Object.assign(Object.assign({}, data), { action_status: 'insert' });
2329
- this.$state.set('RESULT', resultData);
2330
- return resultData;
2622
+ : Object.assign(Object.assign({}, data), { $action: 'insert' });
2623
+ return this.resultHandler(resultData);
2331
2624
  }
2332
2625
  case true: {
2333
2626
  const result = yield this.actionStatement({
2334
2627
  sql: new Model().copyModel(this, { update: true, where: true }).toString()
2335
2628
  });
2336
- if (this.$state.get('VOID'))
2337
- return null;
2338
- if (!result)
2339
- return null;
2340
- const data = yield new Model().bind(this.$pool.get()).copyModel(this, { where: true }).get();
2629
+ if (this.$state.get('VOID') || !result)
2630
+ return this.resultHandler(null);
2631
+ const data = yield new Model().copyModel(this, { where: true }).bind(this.$pool.get()).get();
2341
2632
  if ((data === null || data === void 0 ? void 0 : data.length) > 1) {
2342
2633
  for (const v of data)
2343
- v.action_status = 'update';
2344
- this.$state.set('RESULT', data);
2345
- return data || [];
2634
+ v.$action = 'update';
2635
+ return this.resultHandler(data || []);
2346
2636
  }
2347
- const resultData = Object.assign(Object.assign({}, data === null || data === void 0 ? void 0 : data.shift()), { action_status: 'update' }) || null;
2348
- this.$state.set('RESULT', resultData);
2349
- return resultData;
2637
+ const resultData = Object.assign(Object.assign({}, data === null || data === void 0 ? void 0 : data.shift()), { $action: 'update' }) || null;
2638
+ return this.resultHandler(resultData);
2350
2639
  }
2351
2640
  }
2352
2641
  });
2353
2642
  }
2354
2643
  _insertOrSelectModel() {
2355
2644
  return __awaiter(this, void 0, void 0, function* () {
2356
- this._assertError(!this.$state.get('WHERE'), "Can not update or insert [updateOrInsert] without where condition");
2357
- const clone = new Model().bind(this.$pool.get()).copyModel(this, { where: true });
2645
+ this._assertError(!this.$state.get('WHERE'), "Can not create or select [createOrSelect] without where condition");
2646
+ const clone = new Model().copyModel(this, { where: true }).bind(this.$pool.get());
2358
2647
  const check = (yield clone.exists()) || false;
2359
2648
  switch (check) {
2360
2649
  case false: {
2361
2650
  const [result, id] = yield this.actionStatement({
2362
- sql: this.$state.get('INSERT'),
2651
+ sql: String(this.$state.get('INSERT')),
2363
2652
  returnId: true
2364
2653
  });
2365
- if (this.$state.get('VOID'))
2366
- return null;
2367
- if (!result)
2368
- return null;
2369
- const data = yield new Model().bind(this.$pool.get()).copyModel(this).where('id', id).first();
2654
+ if (this.$state.get('VOID') || !result)
2655
+ return this.resultHandler(null);
2656
+ const data = yield new Model().copyModel(this).bind(this.$pool.get()).where('id', id).first();
2370
2657
  const resultData = data == null
2371
2658
  ? null
2372
- : Object.assign(Object.assign({}, data), { action_status: 'insert' });
2373
- this.$state.set('RESULT', resultData);
2374
- return resultData;
2659
+ : Object.assign(Object.assign({}, data), { $action: 'insert' });
2660
+ return this.resultHandler(resultData);
2375
2661
  }
2376
2662
  case true: {
2377
2663
  if (this.$state.get('VOID'))
2378
- return null;
2379
- const data = yield new Model().bind(this.$pool.get()).copyModel(this, { where: true }).get();
2664
+ return this.resultHandler(null);
2665
+ const data = yield new Model().copyModel(this, { where: true }).bind(this.$pool.get()).get();
2380
2666
  if ((data === null || data === void 0 ? void 0 : data.length) > 1) {
2381
2667
  for (const v of data)
2382
- v.action_status = 'select';
2383
- this.$state.set('RESULT', data);
2384
- return data || [];
2668
+ v.$action = 'select';
2669
+ return this.resultHandler(data || []);
2385
2670
  }
2386
- const resultData = Object.assign(Object.assign({}, data === null || data === void 0 ? void 0 : data.shift()), { action_status: 'select' }) || null;
2387
- this.$state.set('RESULT', resultData);
2388
- return resultData;
2671
+ const resultData = Object.assign(Object.assign({}, data === null || data === void 0 ? void 0 : data.shift()), { $action: 'select' }) || null;
2672
+ return this.resultHandler(resultData);
2389
2673
  }
2390
2674
  }
2391
2675
  });
2392
2676
  }
2393
2677
  _updateModel() {
2394
2678
  return __awaiter(this, void 0, void 0, function* () {
2395
- this._assertError(!this.$state.get('WHERE'), "can not update [ update ] without where condition");
2679
+ this._assertError(!String(this.$state.get('WHERE')), "can not update [ update ] without where condition");
2396
2680
  const sql = this._buildQueryModel();
2397
2681
  const result = yield this.actionStatement({ sql });
2398
- if (this.$state.get('VOID'))
2399
- return null;
2400
- if (result == null || !result)
2401
- return null;
2402
- const data = yield new Model().bind(this.$pool.get()).copyModel(this, { where: true }).get();
2682
+ if (this.$state.get('VOID') || !result || result == null)
2683
+ return this.resultHandler(null);
2684
+ const data = yield new Model().copyModel(this, { where: true }).bind(this.$pool.get()).get();
2403
2685
  if ((data === null || data === void 0 ? void 0 : data.length) > 1) {
2404
- this.$state.set('RESULT', data);
2405
- return data || [];
2686
+ return this.resultHandler(data || []);
2406
2687
  }
2407
2688
  const resultData = (data === null || data === void 0 ? void 0 : data.shift()) || null;
2408
- this.$state.set('RESULT', resultData);
2409
- return resultData;
2689
+ return this.resultHandler(resultData);
2410
2690
  });
2411
2691
  }
2412
2692
  _assertError(condition = true, message = 'error') {
@@ -2474,40 +2754,19 @@ class Model extends AbstractModel_1.AbstractModel {
2474
2754
  const methodCallings = this.$logger.get();
2475
2755
  const methodsNotAllowed = methodChangeStatements;
2476
2756
  const findMethodNotAllowed = methodCallings.find((methodCalling) => methodsNotAllowed.includes(methodCalling));
2477
- this._assertError(methodCallings.some((methodCalling) => methodsNotAllowed.includes(methodCalling)), `this method ${method} can't using method : [ ${findMethodNotAllowed} ]`);
2757
+ this._assertError(methodCallings.some((methodCalling) => methodsNotAllowed.includes(methodCalling)), `This method "${method}" can't using method : [ ${findMethodNotAllowed} ]`);
2478
2758
  break;
2479
2759
  }
2480
2760
  case 'save': {
2481
2761
  const methodCallings = this.$logger.get();
2482
2762
  const methodsSomeAllowed = methodChangeStatements;
2483
- this._assertError(!methodCallings.some((methodCalling) => methodsSomeAllowed.includes(methodCalling)), `this ${method} method need some : [ ${methodsSomeAllowed.join(', ')} ] methods`);
2763
+ this._assertError(!methodCallings.some((methodCalling) => methodsSomeAllowed.includes(methodCalling)), `This ${method} method need some : [ ${methodsSomeAllowed.join(', ')} ] methods`);
2484
2764
  break;
2485
2765
  }
2486
2766
  }
2487
2767
  }
2488
2768
  _initialModel() {
2489
- this.$state = (() => {
2490
- let db = new Map(Object.entries(Object.assign({}, this.$constants('MODEL'))));
2491
- let original = new Map(Object.entries(Object.assign({}, this.$constants('MODEL'))));
2492
- return {
2493
- original: () => original,
2494
- get: (key) => {
2495
- if (key == null)
2496
- return db;
2497
- this._assertError(!db.has(key), `can't get this [ ${key} `);
2498
- return db.get(key);
2499
- },
2500
- set: (key, value) => {
2501
- this._assertError(!db.has(key), `can't set this [ ${key} ]`);
2502
- db.set(key, value);
2503
- return;
2504
- },
2505
- clone: (data) => {
2506
- db = new Map(Object.entries(Object.assign({}, data)));
2507
- return;
2508
- }
2509
- };
2510
- })();
2769
+ this.$state = new StateHandler_1.StateHandler(this.$constants('MODEL'));
2511
2770
  this._makeTableName();
2512
2771
  return this;
2513
2772
  }