-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadapter.go
More file actions
93 lines (79 loc) · 2.5 KB
/
adapter.go
File metadata and controls
93 lines (79 loc) · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package dynamic
import (
"context"
"github.com/GoCodeAlone/modular"
)
// ModuleAdapter wraps a DynamicComponent as a modular.Module so it can
// participate in the modular dependency system.
type ModuleAdapter struct {
component *DynamicComponent
moduleName string
provides []string
requires []string
}
// NewModuleAdapter creates a new ModuleAdapter wrapping the given component.
func NewModuleAdapter(component *DynamicComponent) *ModuleAdapter {
return &ModuleAdapter{
component: component,
moduleName: component.Name(),
}
}
// Name returns the component name.
func (a *ModuleAdapter) Name() string {
return a.moduleName
}
// Init initializes the adapter by collecting required services and passing
// them to the underlying component, then registering provided services.
func (a *ModuleAdapter) Init(app modular.Application) error {
services := make(map[string]any)
for _, svcName := range a.requires {
var svc any
if err := app.GetService(svcName, &svc); err == nil {
services[svcName] = svc
}
}
if err := a.component.Init(services); err != nil {
return err
}
for _, svcName := range a.provides {
if err := app.RegisterService(svcName, a.component); err != nil {
return err
}
}
return nil
}
// SetProvides sets the list of service names this adapter provides.
func (a *ModuleAdapter) SetProvides(services []string) {
a.provides = services
}
// SetRequires sets the list of service names this adapter requires.
func (a *ModuleAdapter) SetRequires(services []string) {
a.requires = services
}
// Execute delegates execution to the underlying component.
func (a *ModuleAdapter) Execute(ctx context.Context, params map[string]any) (map[string]any, error) {
return a.component.Execute(ctx, params)
}
// ProvidesServices returns the services provided by this adapter.
func (a *ModuleAdapter) ProvidesServices() []modular.ServiceProvider {
providers := make([]modular.ServiceProvider, 0, len(a.provides))
for _, svcName := range a.provides {
providers = append(providers, modular.ServiceProvider{
Name: svcName,
Description: "Dynamic component service: " + svcName,
Instance: a.component,
})
}
return providers
}
// RequiresServices returns the services required by this adapter.
func (a *ModuleAdapter) RequiresServices() []modular.ServiceDependency {
deps := make([]modular.ServiceDependency, 0, len(a.requires))
for _, svcName := range a.requires {
deps = append(deps, modular.ServiceDependency{
Name: svcName,
Required: false,
})
}
return deps
}