UNPKG

2.73 kBPlain TextView Raw
1import { ConsoleLogger as LoggerClass } from './Logger';
2
3const logger = new LoggerClass('Amplify');
4
5export class AmplifyClass {
6 // Everything that is `register`ed is tracked here
7 private _components = [];
8 private _config = {};
9
10 // All modules (with `getModuleName()`) are stored here for dependency injection
11 private _modules = {};
12
13 // for backward compatibility to avoid breaking change
14 // if someone is using like Amplify.Auth
15 Auth = null;
16 Analytics = null;
17 API = null;
18 Credentials = null;
19 Storage = null;
20 I18n = null;
21 Cache = null;
22 PubSub = null;
23 Interactions = null;
24 Pushnotification = null;
25 UI = null;
26 XR = null;
27 Predictions = null;
28 DataStore = null;
29 Geo = null;
30
31 Logger = LoggerClass;
32 ServiceWorker = null;
33
34 register(comp) {
35 logger.debug('component registered in amplify', comp);
36 this._components.push(comp);
37 if (typeof comp.getModuleName === 'function') {
38 this._modules[comp.getModuleName()] = comp;
39 this[comp.getModuleName()] = comp;
40 } else {
41 logger.debug('no getModuleName method for component', comp);
42 }
43
44 // Finally configure this new component(category) loaded
45 // With the new modularization changes in Amplify V3, all the Amplify
46 // component are not loaded/registered right away but when they are
47 // imported (and hence instantiated) in the client's app. This ensures
48 // that all new components imported get correctly configured with the
49 // configuration that Amplify.configure() was called with.
50 comp.configure(this._config);
51 }
52
53 configure(config?) {
54 if (!config) return this._config;
55
56 this._config = Object.assign(this._config, config);
57 logger.debug('amplify config', this._config);
58
59 // Dependency Injection via property-setting.
60 // This avoids introducing a public method/interface/setter that's difficult to remove later.
61 // Plus, it reduces `if` statements within the `constructor` and `configure` of each module
62 Object.entries(this._modules).forEach(([Name, comp]) => {
63 // e.g. Auth.*
64 Object.keys(comp).forEach(property => {
65 // e.g. Auth["Credentials"] = this._modules["Credentials"] when set
66 if (this._modules[property]) {
67 comp[property] = this._modules[property];
68 }
69 });
70 });
71
72 this._components.map(comp => {
73 comp.configure(this._config);
74 });
75
76 return this._config;
77 }
78
79 addPluggable(pluggable) {
80 if (
81 pluggable &&
82 pluggable['getCategory'] &&
83 typeof pluggable['getCategory'] === 'function'
84 ) {
85 this._components.map(comp => {
86 if (
87 comp['addPluggable'] &&
88 typeof comp['addPluggable'] === 'function'
89 ) {
90 comp.addPluggable(pluggable);
91 }
92 });
93 }
94 }
95}
96
97export const Amplify = new AmplifyClass();
98
99/**
100 * @deprecated use named import
101 */
102export default Amplify;