github.com/hellofresh/janus@v0.0.0-20230925145208-ce8de8183c67/pkg/api/repository.go (about)

     1  package api
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"fmt"
     7  	"io"
     8  	"net/url"
     9  	"time"
    10  
    11  	log "github.com/sirupsen/logrus"
    12  )
    13  
    14  const (
    15  	mongodb = "mongodb"
    16  	cassandra = "cassandra"
    17  	file    = "file"
    18  )
    19  
    20  // Repository defines the behavior of a proxy specs repository
    21  type Repository interface {
    22  	io.Closer
    23  	FindAll() ([]*Definition, error)
    24  }
    25  
    26  // Watcher defines how a provider should watch for changes on configurations
    27  type Watcher interface {
    28  	Watch(ctx context.Context, cfgChan chan<- ConfigurationChanged)
    29  }
    30  
    31  // Listener defines how a provider should listen for changes on configurations
    32  type Listener interface {
    33  	Listen(ctx context.Context, cfgChan <-chan ConfigurationMessage)
    34  }
    35  
    36  // BuildRepository creates a repository instance that will depend on your given DSN
    37  func BuildRepository(dsn string, refreshTime time.Duration) (Repository, error) {
    38  	dsnURL, err := url.Parse(dsn)
    39  	if err != nil {
    40  		return nil, fmt.Errorf("error parsing the DSN: %w", err)
    41  	}
    42  
    43  	switch dsnURL.Scheme {
    44  	case mongodb:
    45  		log.Debug("MongoDB configuration chosen")
    46  		return NewMongoAppRepository(dsn, refreshTime)
    47  	case cassandra:
    48  		log.Debugf("Casssandra configuration chosen: dsn is %s, dsnURL is %s", dsnURL.Path, dsnURL)
    49  		return NewCassandraRepository(dsnURL.Path, refreshTime)
    50  	case file:
    51  		log.Debug("File system based configuration chosen")
    52  		apiPath := fmt.Sprintf("%s/apis", dsnURL.Path)
    53  
    54  		log.WithField("path", apiPath).Debug("Trying to load API configuration files")
    55  		repo, err := NewFileSystemRepository(apiPath)
    56  		if err != nil {
    57  			return nil, fmt.Errorf("could not create a file system repository: %w", err)
    58  		}
    59  		return repo, nil
    60  	default:
    61  		return nil, errors.New("selected scheme is not supported to load API definitions")
    62  	}
    63  }