diff --git a/initializer/initializer.go b/initializer/initializer.go new file mode 100644 index 0000000..cde8f34 --- /dev/null +++ b/initializer/initializer.go @@ -0,0 +1,31 @@ +package initializer + +import "context" + +type ( + _Initializer interface{ Init() } + _WithError interface{ Init() error } + _ByContext interface{ Init(context.Context) } + _ByContextWithError interface{ Init(context.Context) error } +) + +func InitByContext(ctx context.Context, initializer any) error { + switch v := initializer.(type) { + case _Initializer: + v.Init() + return nil + case _WithError: + return v.Init() + case _ByContext: + v.Init(ctx) + return nil + case _ByContextWithError: + return v.Init(ctx) + default: + return nil + } +} + +func Init(initializer any) error { + return InitByContext(context.Background(), initializer) +} diff --git a/initializer/initializer_test.go b/initializer/initializer_test.go new file mode 100644 index 0000000..dd65cd0 --- /dev/null +++ b/initializer/initializer_test.go @@ -0,0 +1,57 @@ +package initializer_test + +import ( + "context" + "testing" + + . "github.com/onsi/gomega" + "github.com/pkg/errors" + + "github.com/sincospro/datatypes/initializer" +) + +var ( + errInitializerWithError = errors.New("initialize with error") + errInitializerByContextWithError = errors.New("initialize by context with error") +) + +type Initializer struct{} + +func (i *Initializer) Init() {} + +type InitializerWithError struct{} + +func (i *InitializerWithError) Init() error { + return errInitializerWithError +} + +type InitializerByContext struct{} + +func (i *InitializerByContext) Init(_ context.Context) {} + +type InitializerByContextWithError struct{} + +func (i *InitializerByContextWithError) Init(_ context.Context) error { + return errInitializerByContextWithError +} + +func TestInit(t *testing.T) { + results := []error{ + nil, + errInitializerWithError, + nil, + errInitializerByContextWithError, + } + for i, v := range []any{ + &Initializer{}, + &InitializerWithError{}, + &InitializerByContext{}, + &InitializerByContextWithError{}, + } { + if results[i] == nil { + NewWithT(t).Expect(initializer.Init(v)).To(BeNil()) + } else { + NewWithT(t).Expect(initializer.Init(v)).To(Equal(results[i])) + } + } +} diff --git a/types.go b/types.go index 679fce1..4f50fb0 100644 --- a/types.go +++ b/types.go @@ -1,7 +1,6 @@ package datatypes import ( - "context" "database/sql" "database/sql/driver" "encoding" @@ -42,11 +41,8 @@ var ( // Interfaces type ( - DefaultSetter interface{ SetDefault() } - Initializer interface{ Init() } - InitializerWithError interface{ Init() error } - InitializeByContext interface{ Init(context.Context) error } - CanBeZero interface{ Zero() bool } - Stringer interface{ String() string } - SecurityStringer interface{ SecurityString() string } + DefaultSetter interface{ SetDefault() } + CanBeZero interface{ Zero() bool } + Stringer interface{ String() string } + SecurityStringer interface{ SecurityString() string } )