UNPKG

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