/
application.ts
1262 lines (1182 loc) · 30.3 KB
/
application.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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { WorkerLogLevel, WorkerOutput } from "@webda/workout";
import * as fs from "fs";
import { JSONSchema7 } from "json-schema";
import { OpenAPIV3 } from "openapi-types";
import * as path from "path";
import { Constructor, Core, CoreModel, CoreModelDefinition, Service, WebdaError } from "./index";
import { getCommonJS } from "./utils/esm";
import { FileUtils } from "./utils/serializers";
const { __dirname } = getCommonJS(import.meta.url);
export type PackageDescriptorAuthor =
| string
| {
name?: string;
email?: string;
url?: string;
};
export type Modda = ServiceConstructor<Service>;
/**
* Defined relationship for one model
*/
export type ModelGraph = {
parent?: Omit<ModelRelation, "type">;
links?: ModelRelation[];
queries?: {
attribute: string;
model: string;
targetAttribute: string;
}[];
maps?: {
attribute: string;
model: string;
targetAttributes: string[];
targetLink: string;
cascadeDelete: boolean;
}[];
children?: string[];
binaries?: {
attribute: string;
cardinality: "ONE" | "MANY";
metadata?: string;
}[];
};
/**
* Defined relationship for all models
*/
export type ModelsGraph = {
// key is shared with models
[key: string]: ModelGraph;
};
/**
* Some package exists but seems pretty big for this
* https://classic.yarnpkg.com/en/docs/package-json
*/
export interface PackageDescriptor {
name?: string;
version?: string;
description?: string;
keywords?: string[];
license?: string | { name: string };
homepage?: string;
bugs?: string;
repository?: string;
author?: PackageDescriptorAuthor;
contributors?: string[] | PackageDescriptorAuthor[];
files?: string[];
main?: string;
bin?:
| string
| {
[key: string]: string;
};
man?: string | string[];
directories?: { [key: string]: string };
scripts?: { [key: string]: string };
config?: any;
dependencies?: { [key: string]: string };
devDependencies?: { [key: string]: string };
peerDependencies?: { [key: string]: string };
peerDependenciesMeta?: {
[key: string]: {
optional: boolean;
};
};
optionalDependencies?: { [key: string]: string };
bundledDependencies?: string[];
flat?: boolean;
resolutions?: { [key: string]: string };
engines?: { [key: string]: string };
os?: string[];
cpu?: string[];
private?: boolean;
publishConfig?: any;
webda?: Partial<WebdaPackageDescriptor>;
termsOfService?: string;
title?: string;
}
export type ModelRelation = {
attribute: string;
model: string;
type: "LINK" | "LINKS_MAP" | "LINKS_ARRAY" | "LINKS_SIMPLE_ARRAY";
};
/**
* Define the model hierarchy
*/
export type ModelsTree = {
[key: string]: ModelsTree;
};
/**
* A Webda module is a NPM package
*
* It contains one or more Modda to provide features
*/
export interface Module {
/**
* Services provided by the module
*/
moddas?: { [key: string]: string };
/**
* Models provided by the module
*/
models: {
/**
* Models provided by the module
*/
list: { [key: string]: string };
/**
* Models hierarchy tree
*
* Models Graph establish the relationship between models
* Models Tree establish the hierarchy between models classes
*/
tree: ModelsTree;
/**
* Models graph
*
* Typescript does not have reflection, we therefore deduct the
* relations on compilation time and inject in the module
*
* The parent is define by a ModelParent type on the model
* The links are attribute of types ModelLink
*/
graph: ModelsGraph;
/**
* Specific plurals for a model
*/
plurals: { [key: string]: string };
/**
* Contains the shortcut id for the models
*/
shortIds: { [key: string]: string };
/**
* Store the model attributes types
*/
reflections: { [key: string]: { [key: string]: string } };
};
/**
* Deployers provided by the module
*
* @link Deployer
*/
deployers?: { [key: string]: string };
/**
* Schemas for services, deployers and coremodel
*/
schemas?: { [key: string]: JSONSchema7 };
/**
* Application beans
*/
beans?: { [key: string]: string };
}
/**
* Cached module is all modules discover plus local package including the sources list
*/
export interface CachedModule extends Module {
/**
* Contained dynamic information on the project
* Statically capture on deployment
*/
project: ProjectInformation;
}
export type StaticWebsite = {
url: string;
path?: string;
index?: string;
catchAll?: boolean;
};
export type UnpackedConfiguration = {
version: 3;
/**
* Services configuration
*/
services?: any;
/**
* Global parameters
*/
parameters?: {
/**
* Trust this reverse proxies
*/
trustedProxies?: string | string[];
/**
* Allowed origin for referer that match
* any of this regexp
*
* {@link OriginFilter}
*/
csrfOrigins?: string[];
/**
* Allow you to authorize one or several websites
* If you use "*" then the API is open to direct call and any origins
* You can also serve one static website by having a
*
* {@link WebsiteOriginFilter}
*/
website?: string | string[];
/**
* Serve statically a website
*/
static?: StaticWebsite;
/**
* Read from the configuration service before init
*/
configurationService?: string;
/**
* Define the api url
*/
apiUrl?: string;
/**
* Will not try to parse request bigger than this
*
* This parameter can be overriden by a direct call to
* getHttpContext().getRawBody(xxx)
*
* @default 10Mb
*/
requestLimit?: number;
/**
* Will not take more than this to read a request (unit: milliseconds)
*
* This parameter can be overriden by a direct call to
* getHttpContext().getRawBody(undefined, xxx)
*
* @default 60000
*/
requestTimeout?: number;
/**
* Define the default store
*/
defaultStore?: string;
/**
* Define metrics
*/
metrics?:
| false
| {
labels?: { [key: string]: string };
config?: { [key: string]: any };
prefix?: string;
};
/**
* Allow any other type of parameters
*/
[key: string]: any;
};
/**
* OpenAPI override
*/
openapi?: Partial<OpenAPIV3.Document>;
/**
* Include other configuration.json
*
* This allow you so share Store definition or parameters between different components
* The configuration is merged with `deepmerge(...imports, local)`
*/
imports?: string[];
};
export type Configuration = UnpackedConfiguration & {
/**
* Cached modules to avoid scanning node_modules
* This is used by packagers
*/
cachedModules?: CachedModule;
};
export type StoredConfiguration = Configuration;
/**
* Return the gather information from the repository
* @mermaid Make TypeDoc easy to use with mermaid.js
* graph TB
* mermaid.js --> TypeDoc;
*/
export interface GitInformation {
/**
* Current commit reference
*
* `git rev-parse HEAD`
*/
commit: string;
/**
* Current branch
*
* `git symbolic-ref --short HEAD`
*/
branch: string;
/**
* Current commit short reference
*
* `git rev-parse --short HEAD`
*/
short: string;
/**
* Current tag name that match the package version
*/
tag: string;
/**
* Return all tags that point to the current HEAD
*
* `git tag --points-at HEAD`
*/
tags: string[];
/**
* Current version as return by package.json with auto snapshot
*
* If the version return by package is not in the current `tags`, the version is
* incremented to the next patch version with a +{date}
*
* Example:
*
* with package.json version = "1.1.0" name = "mypackage"
* if a tag "v1.1.0" or "mypackage@1.1.0" then version = "1.1.0"
* else version = "1.1.1+20201110163014178"
*/
version: string;
}
/**
* Helper to define a ServiceContrustor
*/
export interface ServiceConstructor<T extends Service> {
new (webda: Core, name: string, params: any): T;
}
export enum SectionEnum {
Moddas = "moddas",
Deployers = "deployers",
Beans = "beans"
}
/**
* Webda specific metadata for the project
*/
export interface WebdaPackageDescriptor {
/**
* Webda namespace
*/
namespace?: string;
/**
* Logo to display within the shell tty
*/
logo?: string;
/**
* Service to replace default launcher
*/
launcher?: {
/**
* Service to use for launch
*/
service: string;
/**
* Method to use
*/
method: string;
};
/**
* Information on the workspace
*/
workspaces?: {
packages: string[];
parent: PackageDescriptor;
path: string;
};
[key: string]: any;
}
/**
* Information on the whole project
*/
export interface ProjectInformation {
/**
* package.json information
*/
package: PackageDescriptor;
/**
* Webda project information
*
* It is the aggregation of webda information contained in package
* and its workspace meta
*/
webda: WebdaPackageDescriptor;
/**
* Git information gathered
*/
git: GitInformation;
/**
* Deployment information
*/
deployment: {
name: string;
[key: string]: any;
};
}
/**
* Type of Section
*/
export type Section = "moddas" | "deployers" | "models" | "beans";
/**
* Map a Webda Application
*
* It allows to:
* - Analyse imported modules
* - Scan code for Modda and generate the webda.config.json
* - Compile and Watch
* - Migrate from old configuration
* - List deployments
*
*
* @category CoreFeatures
*/
export class Application {
/**
* Get Application root path
*/
readonly appPath: string;
/**
* Base configuration loaded from webda.config.json
*/
protected baseConfiguration: Configuration;
/**
* Current deployment
*/
protected currentDeployment: string;
/**
* Contains definitions of current application
*/
protected appModule: Module = {
moddas: {},
models: {
list: {},
graph: {},
tree: {},
plurals: {},
shortIds: {},
reflections: {}
},
deployers: {}
};
/**
* Contains already loaded modules
*/
protected _loaded: string[] = [];
/**
* Deployers type registry
*/
protected deployers: { [key: string]: any } = {};
/**
* Moddas registry
*/
protected moddas: { [key: string]: Modda } = {};
/**
* Models type registry
*/
protected models: { [key: string /* LongId */]: CoreModelDefinition } = {};
/**
* Models graph
*/
protected graph: ModelsGraph = {};
/**
* Models specific plurals
*/
protected plurals: { [key: string]: string } = {};
/**
* Class Logger
*/
protected logger: WorkerOutput;
/**
* Detect if running as workspace
*/
protected workspacesPath: string = "";
/**
* When the application got initiated
*/
protected initTime: number;
/**
* Direct parent of a model
*/
protected flatHierarchy: { [key: string]: string } = {};
/**
* Configuration file
*/
readonly configurationFile: string;
/**
* Current deployment file
*/
deploymentFile: string;
/**
* Current application
*/
protected static active: Application;
/**
*
* @param {string} fileOrFolder to load Webda Application from
* @param {Logger} logger
*/
constructor(file: string, logger: WorkerOutput = undefined) {
this.logger = logger || new WorkerOutput();
this.initTime = Date.now();
if (!fs.existsSync(file)) {
throw new WebdaError.CodeError(
"NO_WEBDA_FOLDER",
`Not a webda application folder or webda.config.jsonc or webda.config.json file: unexisting ${file}`
);
}
if (fs.lstatSync(file).isDirectory()) {
file = path.join(file, "webda.config.jsonc");
if (!fs.existsSync(file)) {
file = file.substring(0, file.length - 1);
}
}
this.configurationFile = file;
this.appPath = path.resolve(path.dirname(file));
}
/**
* Import all required modules
*/
async load(): Promise<this> {
this.loadConfiguration(this.configurationFile);
await this.loadModule(this.baseConfiguration.cachedModules);
// Flat the model tree
const addParent = (parent: string, tree: ModelGraph) => {
for (let key in tree) {
this.flatHierarchy[key] = parent;
addParent(key, tree[key]);
}
};
addParent("Webda/CoreModel", this.baseConfiguration.cachedModules.models.tree);
return this;
}
/**
* Allow subclass to implement migration
*
* @param file
* @returns
*/
loadConfiguration(file: string): void {
// Check if file is a file or folder
if (!fs.existsSync(file)) {
throw new WebdaError.CodeError(
"NO_WEBDA_FOLDER",
`Not a webda application folder or webda.config.jsonc or webda.config.json file: ${file}`
);
}
try {
this.baseConfiguration = FileUtils.load(file);
this.baseConfiguration.parameters ??= {};
this.baseConfiguration.parameters.defaultStore ??= "Registry";
if (this.baseConfiguration.version !== 3) {
this.log("ERROR", "Your configuration file should use version 3, see https://docs.webda.io/");
}
} catch (err) {
throw new WebdaError.CodeError("INVALID_WEBDA_CONFIG", `Cannot parse JSON of: ${file}`);
}
}
/**
*
* @param proto Prototype to send
*/
getFullNameFromPrototype(proto): string {
for (let section in SectionEnum) {
for (let i in this[SectionEnum[section]]) {
if (this[SectionEnum[section]][i] && this[SectionEnum[section]][i].prototype === proto) {
return i;
}
}
}
// Manage CoreModel too
for (let i in this.models) {
if (this.models[i].prototype === proto) {
return i;
}
}
}
/**
* Get a schema from a type
*
* Schema should be precomputed in the default app
* @param type
* @returns
*/
getSchema(type: string): JSONSchema7 {
return this.baseConfiguration.cachedModules.schemas[type];
}
/**
* Get schemas
* @returns
*/
getSchemas(): { [key: string]: JSONSchema7 } {
return this.baseConfiguration.cachedModules.schemas;
}
/**
* Check if a schema exists
* @param type
* @returns schema name if it exists
*/
hasSchema(type: string): boolean {
return this.baseConfiguration.cachedModules.schemas[type] !== undefined;
}
/**
* Get model graph
*/
getRelations(model: string | Constructor<CoreModel> | CoreModel) {
const name = typeof model === "string" ? this.completeNamespace(model) : this.getModelName(model);
// Get relations should not be case-sensitive until v4
const key = Object.keys(this.graph).find(k => k?.toLowerCase() === name?.toLowerCase());
return this.getGraph()[key] || {};
}
/**
* Get the all graph
* @returns
*/
getGraph() {
return this.graph;
}
/**
* Check if application has cached modules
*
* When deployed the application contains cachedModules in the `webda.config.json`
* It allows to avoid the search for `webda.module.json` inside node_modules and
* take the schema from the cached modules also
*/
isCached(): boolean {
return true;
}
/**
* Retrieve specific webda conf from package.json
*
* In case of workspaces the object is combined
*/
getPackageWebda(): WebdaPackageDescriptor {
return (
this.baseConfiguration.cachedModules.project?.webda || {
namespace: "Webda"
}
);
}
/**
* Retrieve content of package.json
*/
getPackageDescription(): PackageDescriptor {
return this.baseConfiguration.cachedModules?.project?.package || {};
}
/**
* Log information
*
* @param level to log for
* @param args anything to display same as console.log
*/
log(level: WorkerLogLevel, ...args) {
if (this.logger) {
this.logger.log(level, ...args);
}
}
/**
* Get current logger
*/
getWorkerOutput() {
return this.logger;
}
/**
* Return the current app path
*
* @param subpath to append to
*/
getAppPath(subpath: string = undefined): string {
if (subpath && subpath !== "") {
if (path.isAbsolute(subpath)) {
return subpath;
}
return path.join(this.appPath, subpath);
}
return this.appPath;
}
/**
* Add a new service
*
* @param name
* @param service
*/
addService(name: string, service: Modda): this {
this.log("TRACE", "Registering service", name);
this.moddas[name] = service;
return this;
}
/**
* Register a new schema in the application
* @param name
* @param schema
*/
registerSchema(name: string, schema: JSONSchema7): void {
if (this.hasSchema(name)) {
throw new Error(`Schema ${name} already registered`);
}
this.baseConfiguration.cachedModules.schemas[name] = schema;
}
/**
* Get plural of an Id
* @param name
* @returns
*/
getModelPlural(name: string): string {
let value = this.plurals[name] || name.split("/").pop();
return value.endsWith("s") ? value : value + "s";
}
/**
*
* @param section
* @param name
* @param caseSensitive
*/
hasWebdaObject(section: Section, name: string, caseSensitive: boolean = false): boolean {
let objectName = this.completeNamespace(name);
this.log("TRACE", `Search for ${section} ${objectName}`);
if (!this[section][objectName] && name.indexOf("/") === -1) {
objectName = `Webda/${name}`;
}
if (!this[section][objectName]) {
const caseInsensitive = Object.keys(this[section]).find(k => k.toLowerCase() === name.toLowerCase());
if (this[section][caseInsensitive] && !caseSensitive) {
// We found a case insensitive match
return true;
}
return false;
}
return true;
}
/**
*
* @param section
* @param name
* @returns
*/
getWebdaObject(section: Section, name: string, caseSensitive: boolean = false) {
let objectName = this.completeNamespace(name);
this.log("TRACE", `Search for ${section} ${objectName}`);
if (!this[section][objectName] && name.indexOf("/") === -1) {
objectName = `Webda/${name}`;
}
if (!this[section][objectName]) {
const caseInsensitive = Object.keys(this[section]).find(k => k.toLowerCase() === name.toLowerCase());
if (this[section][caseInsensitive] && !caseSensitive) {
// We found a case insensitive match
this.log("DEBUG", `Found ${caseInsensitive} instead of ${name}, will be removed in 4.0`);
return this[section][caseInsensitive];
}
objectName = name !== objectName ? ` or ${objectName}` : "";
throw Error(
`Undefined ${section.substring(0, section.length - 1)} ${name}${objectName} (${Object.keys(this[section]).join(
", "
)})`
);
}
return this[section][objectName];
}
/**
* Get a service based on name
*
* @param name
*/
getModda(name): Modda {
return this.getWebdaObject("moddas", name);
}
/**
* Return all services of the application
*/
getModdas(): { [key: string]: Modda } {
return this.moddas;
}
/**
* Return all beans of the application
*/
getBeans(): { [key: string]: string } {
return this.baseConfiguration.cachedModules.beans;
}
/**
* Retrieve the model implementation
*
* @param name model to retrieve
*/
getModel<T extends CoreModel = CoreModel>(name: string): CoreModelDefinition<T> {
return this.getWebdaObject("models", this.completeNamespace(name));
}
/**
* Get all models definitions
*/
getModels(): {
[key: string]: CoreModelDefinition;
} {
return this.models;
}
/**
* Return models that do not have parents
* @returns
*/
getRootModels(): string[] {
return Object.keys(this.graph).filter(key => !this.graph[key].parent && this.models[key]?.Expose);
}
/**
* Return models that do not have parents and are exposed
* Or specifically set as root via the Expose.root parameter
* @returns
*/
getRootExposedModels(): string[] {
const results = new Set<string>(this.getRootModels().filter(k => this.getModel(k).Expose));
for (let model in this.models) {
if (this.models[model].Expose?.root) {
results.add(model);
}
}
return [...results];
}
/**
* Return the model name for a object
* @param object
*/
getModelFromInstance(object: CoreModel): string | undefined {
return Object.keys(this.models).find(k => this.models[k] === object.constructor);
}
/**
* Return the model name for a object
* @param object
*/
getModelFromConstructor(model: Constructor<CoreModel>): string | undefined {
return Object.keys(this.models).find(k => this.models[k] === model);
}
/**
* Get the model name from a model or a constructor
*
* @param model
* @returns longId for a model
*/
getModelName(model: CoreModel | Constructor<CoreModel>): string | undefined {
// If __type is defined, use it
if ((<any>model).__type) {
return this.completeNamespace((<any>model).__type);
}
if (model instanceof CoreModel) {
return this.getModelFromInstance(model);
}
return this.getModelFromConstructor(model);
}
/**
* Get the model hierarchy
* @param model
*/
getModelHierarchy(model: CoreModel | Constructor<CoreModel> | string): { ancestors: string[]; children: ModelsTree } {
if (typeof model !== "string") {
model = this.getModelName(model);
} else {
model = this.completeNamespace(model);
}
if (model === "Webda/CoreModel") {
return { ancestors: [], children: this.baseConfiguration?.cachedModules?.models?.tree };
}
let ancestors: string[] = [];
let modelInfo = model;
while ((this.flatHierarchy[modelInfo] || "Webda/CoreModel") !== "Webda/CoreModel") {
modelInfo = this.flatHierarchy[modelInfo];
ancestors.unshift(modelInfo);
}
let tree = this.baseConfiguration?.cachedModules?.models?.tree || {};
ancestors.forEach(ancestor => {
tree = tree[ancestor] || {};
});
ancestors.unshift(this.getShortId("Webda/CoreModel"));
ancestors.reverse();
return { ancestors: ancestors.map(i => this.getShortId(i)), children: tree[model] || {} };
}
/**
* Get all model types with the hierarchy
* @param model
* @returns
*/
getModelTypes(model: CoreModel) {
const hierarchy = this.getModelHierarchy(model);
const coreModel = this.getShortId("Webda/CoreModel");
return [model.__type, ...hierarchy.ancestors]
.map(i => (i.includes("/") ? this.getShortId(i) : i))
.filter(i => i !== coreModel);
}
/**
* Return all deployers
*/
getDeployers(): { [key: string]: Modda } {
return this.deployers;
}
/**
* Add a new model
*
* @param name
* @param model
*/
addModel(name: string, model: any, dynamic: boolean = true): this {
this.log("TRACE", "Registering model", name);
this.models[name] = model;
if (dynamic && model) {
const superClass = Object.getPrototypeOf(model);
Object.values(this.getModels())
.filter(m => m === superClass)
.forEach(m => {
this.flatHierarchy[name] = this.getModelName(m);
this.getModelHierarchy(this.flatHierarchy[name]).children[name] = {};
});
}
return this;
}
/**
* Add a new deployer
*
* @param name
* @param model
*/
addDeployer(name: string, model: any): this {
this.log("TRACE", "Registering deployer", name);
this.deployers[name] = model;
return this;
}
/**
* Return webda current version
*
* @returns package version
* @since 0.4.0