factory.go raw

   1  // Copyright 2022-2025 The sacloud/iaas-api-go Authors
   2  //
   3  // Licensed under the Apache License, Version 2.0 (the "License");
   4  // you may not use this file except in compliance with the License.
   5  // You may obtain a copy of the License at
   6  //
   7  //      http://www.apache.org/licenses/LICENSE-2.0
   8  //
   9  // Unless required by applicable law or agreed to in writing, software
  10  // distributed under the License is distributed on an "AS IS" BASIS,
  11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12  // See the License for the specific language governing permissions and
  13  // limitations under the License.
  14  
  15  package iaas
  16  
  17  var clientFactory = make(map[string]func(APICaller) interface{})
  18  
  19  // SetClientFactoryFunc リソースごとのクライアントファクトリーを登録する
  20  func SetClientFactoryFunc(resourceName string, factoryFunc func(caller APICaller) interface{}) {
  21  	clientFactory[resourceName] = factoryFunc
  22  }
  23  
  24  var clientFactoryHooks = make(map[string][]func(interface{}) interface{})
  25  
  26  // AddClientFacotyHookFunc クライアントファクトリーのフックを登録する
  27  func AddClientFacotyHookFunc(resourceName string, hookFunc func(interface{}) interface{}) {
  28  	clientFactoryHooks[resourceName] = append(clientFactoryHooks[resourceName], hookFunc)
  29  }
  30  
  31  // GetClientFactoryFunc リソースごとのクライアントファクトリーを取得する
  32  //
  33  // resourceNameに対するファクトリーが登録されてない場合はpanicする
  34  func GetClientFactoryFunc(resourceName string) func(APICaller) interface{} {
  35  	f, ok := clientFactory[resourceName]
  36  	if !ok {
  37  		panic(resourceName + " is not found in clientFactory")
  38  	}
  39  	if hooks, ok := clientFactoryHooks[resourceName]; ok {
  40  		return func(caller APICaller) interface{} {
  41  			ret := f(caller)
  42  			for _, hook := range hooks {
  43  				ret = hook(ret)
  44  			}
  45  			return ret
  46  		}
  47  	}
  48  	return f
  49  }
  50