• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements.  See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership.  The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License.  You may obtain a copy of the License at
9 *
10 *   http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied.  See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19/*
20 * 2021.01.08 - Rewrite the function 'register' and make it simpler.
21 * Copyright (c) 2021 Huawei Device Co., Ltd.
22 */
23
24import { Log } from '../utils/utils';
25
26export interface OptionsInterface {
27  create: (id: string) => any
28  destroy: (id: string) => void
29  refresh?: (id:string, data: object) => Error | void
30}
31
32export interface ServicesInterface {
33  name: string
34  options: OptionsInterface
35}
36
37export const services: ServicesInterface[] = [];
38
39/**
40 * Register a service.
41 * @param {string} name - Service name.
42 * @param {OptionsInterface} options - Could have { create, destroy, refresh } lifecycle methods.
43 */
44export function register(name: string, options: OptionsInterface): void {
45  const hasName = services.map(
46    service => service.name
47  ).indexOf(name) >= 0;
48
49  if (hasName) {
50    Log.warn(`Service '${name}' has been registered already!`);
51  } else {
52    options = Object.assign({}, options);
53    services.push({
54      name,
55      options
56    });
57  }
58}
59
60/**
61 * Unregister a service by name.
62 * @param {string} name - Service name.
63 */
64export function unregister(name: string): void {
65  services.some((service: ServicesInterface, index: number) => {
66    if (service.name === name) {
67      services.splice(index, 1);
68      return true;
69    }
70  });
71}
72
73export default {
74  register,
75  unregister
76};
77