forked from louislam/redbean-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbean.ts
627 lines (490 loc) · 15.9 KB
/
bean.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
import {RedBeanNode} from "./redbean-node";
import {magicMethods} from "./magic-methods";
import {camelCaseToUnderscore, underscoreToCamelCase} from "./helper/string-helper";
import {LazyLoadArray} from "./lazy-load-array";
import {SharedList} from "./shared-list";
import {OwnList} from "./own-list";
import {LooseObject} from "./helper/helper";
import AwaitLock from 'await-lock';
import {Knex} from "knex";
import * as util from "util";
import RawBinding = Knex.RawBinding;
@magicMethods
export class Bean {
[key: string]: any;
public beanMeta = new BeanMeta();
constructor(type : string, R : RedBeanNode) {
this.beanMeta.R = R;
this.beanMeta.type = type;
this.devLog("Instantiate");
}
/**
* Magic Setter
* @param name
* @param value
*/
__set(name, value) {
this.devLog("Set Property:", name, "=", value);
if (name.startsWith("_")) {
throw "invalid property name: starts with underscore is not allowed";
}
let hasRelationField = (this[Bean.getInternalRelationFieldName(name)] !== undefined);
if (value instanceof Bean || hasRelationField) {
this.devLog("A bean set to property");
this.setRelationBean(name, value);
} else {
let key = Bean.internalName(name);
this.beanMeta.old[key] = this[key];
this[key] = value;
// If this is a relation field, sync the relation bean too!
if (Bean.isRelationField(key)) {
this.devLog("It is a relation field");
let type = Bean.getTypeFromRelationField(key);
delete this.beanMeta.typeBeanList[type];
}
}
}
/**
* Magic Getter
* @param name
*/
__get(name) {
this.devLog("__get:", name);
// starts with underscore and come in here = undefined
if (name.startsWith("_")) {
return undefined;
}
this.devLog("Get Property:", name);
// Check if relation field
// converting "product" to this["_productId"] for example
let relationFieldName = Bean.getInternalRelationFieldName(name);
this.devLog("Convert to relation field name, see is there any relation id:", relationFieldName)
if (this.beanMeta.isChainBean()) {
this.devLog("this.beanMeta.fetchAs:", this.beanMeta.fetchAs);
}
let id = this[relationFieldName];
// if it is null or number, it is a relation field!
// or there is a fetchAs
if (id !== undefined || this.beanMeta.fetchAs) {
this.devLog("Relation Bean Property detected");
let alias = name;
let type = name;
if (this.beanMeta.fetchAs) {
// Assign a true type for the query
type = this.beanMeta.fetchAs;
}
return this.getRelationBean(alias, type, this.beanMeta.noCache);
}
// If own(???)List, here
else if (Bean.isOwnListProperty(name)) {
this.devLog("ownList Property detected");
let alias = this.beanMeta.type;
let type = Bean.getTypeFromOwnListProperty(name);
this.devLog("type =", type);
if (this.beanMeta.alias) {
alias = this.beanMeta.alias;
}
return this.ownList(type, alias, this.beanMeta.noCache);
}
// If shared(???)List, here
else if (Bean.isSharedListProperty(name)) {
this.devLog("sharedList Property detected");
let type = Bean.getTypeFromSharedListProperty(name);
return this.sharedList(type, this.beanMeta.noCache);
}
else {
let key = Bean.internalName(name);
return this[key];
}
}
__isset(name) {
this.devLog("Check isset property of ", name);
return (this[Bean.internalName(name)]) ? true : false;
}
/**
* Many-to-one
* product.shop = shop;
* @param alias
* @param bean
*/
protected setRelationBean(alias : string, bean : Bean | null) {
if (bean) {
if (bean.id) {
// Not allow self reference?
if (this.getType() == bean.getType() && this.id === bean.id) {
throw "Error: self reference detected";
}
this[Bean.getInternalRelationFieldName(alias)] = bean.id;
} else {
this[Bean.getInternalRelationFieldName(alias)] = null;
}
this.beanMeta.typeBeanList[alias] = bean;
} else {
delete this.beanMeta.typeBeanList[alias];
this[Bean.getInternalRelationFieldName(alias)] = null;
}
}
/**
* Many-to-one
* let shop = product.shop
* @param alias
* @param type
* @param force
*/
protected async getRelationBean(alias : string, type? : string, force = false) : Promise<Bean | null> {
this.devLog("Getting relation bean:", alias, type, force);
if (! type) {
type = alias;
}
let fieldName = Bean.getInternalRelationFieldName(alias);
this.devLog("Relation Field Name:", fieldName);
if (! this.beanMeta.typeBeanList[type] || force) {
let id = this[fieldName];
if (! id) {
this.devLog("Return null, id = ", id);
return null;
}
this.beanMeta.typeBeanList[type] = await this.R.load(type, id);
}
return this.beanMeta.typeBeanList[type];
}
/**
* One-to-many
* @param alias
* @param type
* @param force
*/
protected ownList(type : string, alias : string, force = false) {
let key = type + "_" + alias;
if (! this.beanMeta.ownListList[key] || force) {
this.beanMeta.ownListList[key] = new OwnList(this, type, alias);
if (this.beanMeta.withCondition) {
this.beanMeta.ownListList[key].withCondition = this.beanMeta.withCondition;
this.beanMeta.ownListList[key].withConditionData = this.beanMeta.withConditionData;
}
}
return this.beanMeta.ownListList[key];
}
protected sharedList(type : string, force = false) {
let via;
if (this.beanMeta.via) {
via = this.beanMeta.via;
} else {
let typeList = [this.beanMeta.type, type].sort(function (a, b) {
return ('' + a).localeCompare(b);
});
via = typeList[0] + "_" + typeList[1];
}
if (! this.beanMeta.sharedListList[via]) {
this.beanMeta.sharedListList[via] = new SharedList(this, type, via);
if (this.beanMeta.withCondition) {
this.beanMeta.sharedListList[via].withCondition = this.beanMeta.withCondition;
this.beanMeta.sharedListList[via].withConditionData = this.beanMeta.withConditionData;
}
}
return this.beanMeta.sharedListList[via];
}
/**
* Store all relation beans
* All beans without id will be stored.
*/
async storeTypeBeanList() {
this.devLog("storeTypeBeanList");
// Own List
for (let type in this.beanMeta.typeBeanList) {
let bean = this.beanMeta.typeBeanList[type];
if (! bean.id) {
await this.R.store(bean);
}
this.devLog("Is proxy: " + util.types.isProxy(this))
this[Bean.getRelationFieldName(type)] = bean.id;
}
}
/**
* Store all shared list
* All beans without id will be stored.
*/
async storeSharedList() {
let promiseList : Promise<any>[] = [];
// Shared List
for (let key in this.beanMeta.sharedListList) {
let sharedList = this.beanMeta.sharedListList[key];
if (sharedList instanceof SharedList) {
promiseList.push(sharedList.store());
}
}
await this.R.concurrent(promiseList);
}
/**
* Store all own list
* All beans without id will be stored.
*/
async storeOwnList() {
let promiseList : Promise<any>[] = [];
for (let key in this.beanMeta.ownListList) {
let ownList = this.beanMeta.ownListList[key];
if (ownList instanceof OwnList) {
promiseList.push(ownList.store());
}
}
await this.R.concurrent(promiseList);
}
async refresh() {
let updatedBean = await this.R.load(this.beanMeta.type, this.id);
if (updatedBean != null) {
this.import(updatedBean.export());
this.beanMeta.refresh();
} else {
// Deleted in database?!
// Do Nothing for now
// TODO: Maybe remove all property?
}
}
import(obj : any) {
this.devLog("Import");
for (let key in obj) {
if (key !== "beanMeta") {
// Date Object to string
if (obj[key] instanceof Date) {
if (obj[key].getHours() == 0 && obj[key].getMinutes() == 0 && obj[key].getSeconds() == 0) {
obj[key] = this.R.isoDate(obj[key]);
} else {
obj[key] = this.R.isoDateTime(obj[key]);
}
}
this[key] = obj[key];
}
}
}
export(camelCase = true) {
let obj : any = {};
for (let key in this) {
if (key !== "beanMeta") {
if (camelCase) {
obj[Bean.removePrefixUnderscore(key)] = this[key];
} else {
obj[Bean.dbFieldName(key)] = this[key];
}
}
}
return obj;
}
/**
* The chain bean can get relation bean only
* All property cannot be accessed.
* @param type
*/
fetchAs(type : string) : Bean {
this.devLog("fetchAs:", type)
let chainBean = this.createChainBean();
chainBean.beanMeta.fetchAs = type;
return chainBean;
}
alias(alias : string) : Bean {
this.devLog("alias:", alias)
let chainBean = this.createChainBean();
chainBean.beanMeta.alias = alias;
return chainBean;
}
via(via : string) : Bean {
let chainBean = this.createChainBean();
chainBean.beanMeta.via = via;
return chainBean;
}
withCondition(condition : string, data : RawBinding[] = []) : Bean {
let chainBean = this.createChainBean();
chainBean.beanMeta.withCondition = condition;
chainBean.beanMeta.withConditionData = data;
return chainBean;
}
with(value : string, data : RawBinding[] = []) {
return this.withCondition(" 1=1 " + value, data);
}
/**
* If it is a chain bean already, it will return this. Otherwise it will return a new chain bean.
* @private
*/
private createChainBean() : Bean {
if (this.beanMeta.isChainBean()) {
this.devLog("I am a chain bean");
return this;
} else {
this.devLog("Create a chain bean");
let chainBean = this.R.duplicate(this, false);
chainBean.id = this.id;
chainBean.beanMeta.chainParentBean = this;
chainBean.beanMeta.noCache = true;
return chainBean;
}
}
getType() {
return this.beanMeta.type;
}
get R() {
return this.beanMeta.R;
}
static isOwnListProperty(name : string) {
return name.startsWith("own") && name.endsWith("List");
}
static getTypeFromOwnListProperty(name : string) {
if (this.isOwnListProperty(name)) {
// slice 3(own) and 4(List)
return name.slice(3, name.length - 4).toLowerCase();
} else {
throw name + " is not an own list property!";
}
}
static isSharedListProperty(name : string) {
return name.startsWith("shared") && name.endsWith("List");
}
static getTypeFromSharedListProperty(name : string) {
if (this.isSharedListProperty(name)) {
// slice 6(shared) and 4(List)
return name.slice(6, name.length - 4).toLowerCase();
} else {
throw name + " is not an shared list property!";
}
}
static isRelationField(name : string) {
return name.endsWith("Id");
}
protected static getInternalRelationFieldName(type : string) {
return Bean.prefixUnderscore(Bean.getRelationFieldName(type));
}
public static getRelationFieldName(type : string) {
return type + "Id";
}
static prefixUnderscore(name : string) {
return "_" + name;
}
static getTypeFromRelationField(name : string) {
let s = name;
if (s.endsWith("Id")) {
s = s.slice(0, s.length - 2);
}
return Bean.removePrefixUnderscore(s);
}
static removePrefixUnderscore(name : string) {
if (name.startsWith("_")) {
return name.slice(1);
} else {
return name;
}
}
static dbFieldName(name : string) {
return Bean.removePrefixUnderscore(camelCaseToUnderscore(name));
}
static internalName(name : string) {
return Bean.prefixUnderscore(underscoreToCamelCase(name));
}
protected devLog(...params : any[]) {
if (this.R.devDebug) {
console.log("[" + this.beanMeta.type, this._id + "]", ...params);
}
}
isTainted() {
return Object.keys(this.beanMeta.old).length > 0;
}
}
/**
* All true private variables are here, haha
*/
class BeanMeta {
#_R! : RedBeanNode;
#_type! : string;
#_lock : AwaitLock = new AwaitLock();
/**
* For chain operation
*/
#_chainParentBean! : Bean;
/**
* ownList / shareList etc will be cache by default
*/
noCache = false;
/* Variables for Chaining function */
/**
* For chain fetchAs() / fetchAs()
*/
fetchAs = "";
alias = "";
via = "";
withCondition = "";
withConditionData : RawBinding[] = [];
/*
* These variables are for cache
* Should be cleared if refresh() is called.
*/
/**
*
* @private
*/
#_typeBeanList : LooseObject<Bean> = {};
/**
* Contains a list of own list
* @private
*/
#_ownListList : LooseObject<OwnList> = {};
/**
* Key is via table name
* @private
*/
#_sharedListList : LooseObject<SharedList> = {};
#_old : LooseObject = {};
get R(): RedBeanNode {
return this.#_R;
}
set R(value: RedBeanNode) {
this.#_R = value;
}
get typeBeanList(): any {
return this.#_typeBeanList;
}
get type(): string {
return this.#_type;
}
set type(value: string) {
// Limit english, number, _ and - only
// Because Unicode table name is not tested and should be hard to test
if (value.match(/^[a-zA-Z0-9_-]+$/) == null) {
throw `type name '${value}' is not allowed`
}
this.#_type = value;
}
get ownListList() {
return this.#_ownListList;
}
get sharedListList() {
return this.#_sharedListList;
}
set chainParentBean(value: Bean) {
this.#_chainParentBean = value;
}
/**
* Has a Parent bean = it is a chain bean
* No parent bean = not a chain bean
*/
isChainBean() {
return (this.#_chainParentBean) ? true : false;
}
get old(): LooseObject {
return this.#_old;
}
set old(value: LooseObject) {
this.#_old = value;
}
clearCache() {
this.#_typeBeanList = {};
this.#_ownListList = {};
this.#_sharedListList = {};
}
clearHistory() {
this.#_old = {};
}
refresh() {
this.clearCache();
this.clearHistory();
}
get lock(): AwaitLock {
return this.#_lock;
}
}