Use a shared in-memory code store across mock, Tencent, and Aliyun SMS services so send and verify follow the same contract. Also surface batch flush failures through FlushNow and explicit error tracking hooks for audit buffering.
62 lines
1.6 KiB
Go
62 lines
1.6 KiB
Go
package sms
|
|
|
|
import (
|
|
"fmt"
|
|
)
|
|
|
|
// NewSMSService creates an SMS service based on the configuration.
|
|
func NewSMSService(config *Config) (SMSService, error) {
|
|
if config == nil {
|
|
config = DefaultConfig()
|
|
}
|
|
|
|
if !config.Enabled {
|
|
return NewMockSMSService(config), nil
|
|
}
|
|
|
|
switch config.Provider {
|
|
case ProviderTencent:
|
|
return NewTencentSMSServiceWithCodeStore(config, NewInMemoryCodeStore()), nil
|
|
case ProviderAliyun:
|
|
svc, err := NewAliyunSMSServiceWithCodeStore(config, NewInMemoryCodeStore())
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to create Aliyun SMS service: %w", err)
|
|
}
|
|
return svc, nil
|
|
default:
|
|
return nil, fmt.Errorf("unsupported SMS provider: %s", config.Provider)
|
|
}
|
|
}
|
|
|
|
// NewSMSServiceWithCodeStore creates an SMS service with a shared code store.
|
|
// This is useful when you want to send and verify codes through different channels.
|
|
func NewSMSServiceWithCodeStore(config *Config, store *InMemoryCodeStore) (SMSService, *InMemoryCodeStore, error) {
|
|
if config == nil {
|
|
config = DefaultConfig()
|
|
}
|
|
if store == nil {
|
|
store = NewInMemoryCodeStore()
|
|
}
|
|
|
|
if !config.Enabled {
|
|
mockSvc := &MockSMSService{
|
|
store: store,
|
|
config: config,
|
|
}
|
|
return mockSvc, store, nil
|
|
}
|
|
|
|
switch config.Provider {
|
|
case ProviderTencent:
|
|
return NewTencentSMSServiceWithCodeStore(config, store), store, nil
|
|
case ProviderAliyun:
|
|
svc, err := NewAliyunSMSServiceWithCodeStore(config, store)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("failed to create Aliyun SMS service: %w", err)
|
|
}
|
|
return svc, store, nil
|
|
default:
|
|
return nil, nil, fmt.Errorf("unsupported SMS provider: %s", config.Provider)
|
|
}
|
|
}
|