|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright (C) 2020 The Android Open Source Project |
| 4 | + * |
| 5 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | + * you may not use this file except in compliance with the License. |
| 7 | + * You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | +import {appContext} from './app-context.js'; |
| 18 | +import {FlagsService} from './flags.js'; |
| 19 | + |
| 20 | +const initializedServices = new Map(); |
| 21 | + |
| 22 | +function getService(serviceName, serviceInit) { |
| 23 | + if (!initializedServices[serviceName]) { |
| 24 | + initializedServices[serviceName] = serviceInit(); |
| 25 | + } |
| 26 | + return initializedServices[serviceName]; |
| 27 | +} |
| 28 | + |
| 29 | +/** |
| 30 | + * The AppContext lazy initializator for all services |
| 31 | + */ |
| 32 | +export function initAppContext() { |
| 33 | + const registeredServices = {}; |
| 34 | + function addService(serviceName, serviceCreator) { |
| 35 | + if (registeredServices[serviceName]) { |
| 36 | + throw new Error(`Service ${serviceName} already registered.`); |
| 37 | + } |
| 38 | + registeredServices[serviceName] = { |
| 39 | + get() { |
| 40 | + return getService(serviceName, serviceCreator); |
| 41 | + }, |
| 42 | + }; |
| 43 | + } |
| 44 | + |
| 45 | + addService('flagsService', () => new FlagsService()); |
| 46 | + |
| 47 | + Object.defineProperties(appContext, registeredServices); |
| 48 | +} |
0 commit comments