Files
probo/pkg/connector/registry.go
Bryan Frimin 59aa332ab5 Move to vanity import url
Signed-off-by: Bryan Frimin <bryan@getprobo.com>
2025-10-31 17:01:52 +01:00

76 lines
2.2 KiB
Go

// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package connector
import (
"context"
"fmt"
"net/http"
"sync"
"go.probo.inc/probo/pkg/gid"
)
type (
ConnectorRegistry struct {
sync.RWMutex
connectors map[string]Connector
}
)
func NewConnectorRegistry() *ConnectorRegistry {
return &ConnectorRegistry{
connectors: make(map[string]Connector),
}
}
func (cr *ConnectorRegistry) Register(provider string, connector Connector) error {
cr.Lock()
defer cr.Unlock()
if _, ok := cr.connectors[provider]; ok {
return fmt.Errorf("connector %q already registered", provider)
}
cr.connectors[provider] = connector
return nil
}
func (cr *ConnectorRegistry) Get(provider string) (Connector, error) {
cr.RLock()
defer cr.RUnlock()
connector, ok := cr.connectors[provider]
if !ok {
return nil, fmt.Errorf("connector %q not found", provider)
}
return connector, nil
}
func (cr *ConnectorRegistry) Initiate(ctx context.Context, provider string, organizationID gid.GID, r *http.Request) (string, error) {
connector, err := cr.Get(provider)
if err != nil {
return "", fmt.Errorf("cannot initiate connector: %w", err)
}
return connector.Initiate(ctx, provider, organizationID, r)
}
func (cr *ConnectorRegistry) Complete(ctx context.Context, provider string, r *http.Request) (Connection, *gid.GID, error) {
connector, err := cr.Get(provider)
if err != nil {
return nil, nil, fmt.Errorf("cannot complete connector: %w", err)
}
return connector.Complete(ctx, r)
}