Skip to content

Commit

Permalink
NewMappers now can have a parent
Browse files Browse the repository at this point in the history
  • Loading branch information
yuin committed Apr 17, 2024
1 parent 382a4d1 commit d88ced0
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 23 deletions.
24 changes: 2 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -306,30 +306,10 @@ Large applications often consist of multiple go modules.
You can hierarchize mappers by a delegation like the following:
```go
type delegatingMappers struct {
Mappers
parent Mappers
}

func (d *delegatingMappers) Get(name string) (any, error) {
v, err := d.Mappers.Get(name)
var merr interface {
NotFound() bool
}
if errors.As(err, &merr) && merr.NotFound() {
return d.parent.Get(name)
}
return v, err
}

func NewDefaultMappers(parent Mappers) Mappers {
m := NewMappers()
dm := &delegatingMappers{
Mappers: m,
parent: parent,
}
m := NewMappers(parent)
// Add gRPC specific mappers and helpers
return dm
return m
}

// mappers := grpc_mappers.NewDefaultMappers(lib_mappers.NewMappers())
Expand Down
13 changes: 12 additions & 1 deletion mappers.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,14 +81,18 @@ type Mappers interface {
type mappers struct {
dependencies sync.Map // [string, any]
factories sync.Map // [string, func(*mappers) (any, error)]
parent Mappers
}
// NewMappers return a new [Mappers] .
func NewMappers() Mappers {
func NewMappers(parent ...Mappers) Mappers {
mappers := &mappers{
dependencies: sync.Map{},
factories: sync.Map{},
}
if len(parent) != 0 {
mappers.parent = parent[0]
}
{{MAPPERS}}
return mappers
}
Expand Down Expand Up @@ -162,6 +166,13 @@ func (d *mappers) Get(name string) (any, error) {
}
d.dependencies.Store(name, obj)
} else {
if d.parent != nil {
obj, err := d.parent.Get(name)
if err != nil {
return nil, err
}
return obj, nil
}
merr := &merror {
error: fmt.Errorf("Object %%s not found", name),
notFound: true,
Expand Down

0 comments on commit d88ced0

Please sign in to comment.