Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 03c783ba53 | |||
| ad04a920fd | |||
| 431f06b9f6 |
@@ -3,6 +3,7 @@
|
||||
Component identity propagation for layered Go libraries.
|
||||
|
||||
Source: https://git.wisehodl.dev/jay/go-mana-component
|
||||
|
||||
Mirror: https://github.com/wisehodl/go-mana-component
|
||||
|
||||
## What this library does
|
||||
@@ -75,12 +76,14 @@ At the connection layer, another `MustExtend` call extends the path to
|
||||
|
||||
### Usage Notes
|
||||
|
||||
**Error-Returning vs Panic Variants**:
|
||||
**Function Variants**:
|
||||
|
||||
- Use `New` and `Extend` when a missing or invalid component is a recoverable
|
||||
condition.
|
||||
- Use `MustNew` and `MustExtend` at library boundaries where a missing
|
||||
component is a programming error that should halt execution immediately.
|
||||
- Use `TryExtend` if you only want to extend a component if it exists,
|
||||
otherwise use the parent context as-is.
|
||||
|
||||
**Generic Output**:
|
||||
|
||||
|
||||
@@ -93,6 +93,21 @@ func Extend(ctx context.Context, name string) (context.Context, error) {
|
||||
return insert(ctx, c.Module(), name, c.Path()), nil
|
||||
}
|
||||
|
||||
// TryExtend returns ctx if no parent component is attached, otherwise
|
||||
// extends the existing component path.
|
||||
func TryExtend(ctx context.Context, name string) (context.Context, error) {
|
||||
if ctx == nil {
|
||||
return nil, fmt.Errorf("context is nil")
|
||||
}
|
||||
|
||||
c, ok := Get(ctx)
|
||||
if !ok || name == "" {
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
return insert(ctx, c.Module(), name, c.Path()), nil
|
||||
}
|
||||
|
||||
// MustNew is New but panics on error.
|
||||
func MustNew(ctx context.Context, module string, name string) context.Context {
|
||||
if ctx == nil {
|
||||
|
||||
@@ -80,6 +80,17 @@ func TestExtend(t *testing.T) {
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("try passes through", func(t *testing.T) {
|
||||
inCtx := context.Background()
|
||||
outCtx, err := TryExtend(inCtx, "subcomponent")
|
||||
if err != nil {
|
||||
t.Fatal("unexpected error:", err)
|
||||
}
|
||||
if outCtx != inCtx {
|
||||
t.Errorf("expected context to pass through")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("must variant should panic", func(t *testing.T) {
|
||||
assertPanics(t, func() {
|
||||
MustExtend(context.Background(), "subcomponent")
|
||||
|
||||
Reference in New Issue
Block a user