-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathregistry.go
58 lines (47 loc) · 1.56 KB
/
registry.go
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
package fxworker
import (
"fmt"
"github.com/ankorstore/yokai/worker"
"go.uber.org/fx"
)
// WorkerRegistry is the registry collecting workers and their definitions.
type WorkerRegistry struct {
workers []worker.Worker
definitions []WorkerDefinition
}
// FxWorkerRegistryParam allows injection of the required dependencies in [NewFxWorkerRegistry].
type FxWorkerRegistryParam struct {
fx.In
Workers []worker.Worker `group:"workers"`
Definitions []WorkerDefinition `group:"workers-definitions"`
}
// NewFxWorkerRegistry returns as new [WorkerRegistry].
func NewFxWorkerRegistry(p FxWorkerRegistryParam) *WorkerRegistry {
return &WorkerRegistry{
workers: p.Workers,
definitions: p.Definitions,
}
}
// ResolveWorkersRegistrations resolves a list of [worker.WorkerRegistration] from their definitions.
func (r *WorkerRegistry) ResolveWorkersRegistrations() ([]*worker.WorkerRegistration, error) {
registrations := []*worker.WorkerRegistration{}
for _, definition := range r.definitions {
implementation, err := r.lookupRegisteredWorker(definition.ReturnType())
if err != nil {
return nil, err
}
registrations = append(
registrations,
worker.NewWorkerRegistration(implementation, definition.Options()...),
)
}
return registrations, nil
}
func (r *WorkerRegistry) lookupRegisteredWorker(returnType string) (worker.Worker, error) {
for _, implementation := range r.workers {
if GetType(implementation) == returnType {
return implementation, nil
}
}
return nil, fmt.Errorf("cannot find worker implementation for type %s", returnType)
}