gitlab.com/picnic-app/backend/role-api@v0.0.0-20230614140944-06a76ff3696d/internal/repo/spanner/repo.go (about)

     1  package spanner
     2  
     3  import (
     4  	"context"
     5  
     6  	"cloud.google.com/go/spanner"
     7  	"google.golang.org/api/option"
     8  
     9  	"gitlab.com/picnic-app/backend/libs/golang/config"
    10  )
    11  
    12  func NewRepo(ctx context.Context, cfg config.Spanner) (Repo, error) {
    13  	cli, err := NewSpannerClient(ctx, cfg.DSN, cfg.ADCPath)
    14  	if err != nil {
    15  		return Repo{}, fromError(err)
    16  	}
    17  
    18  	return Repo{
    19  		cli: cli,
    20  	}, nil
    21  }
    22  
    23  func NewRepoWithClient(cli *spanner.Client) Repo { return Repo{cli: cli} }
    24  
    25  type Repo struct{ cli *spanner.Client }
    26  
    27  func (r Repo) Close() { r.cli.Close() }
    28  
    29  func NewSpannerClient(ctx context.Context, dsn, adcCredPath string) (*spanner.Client, error) {
    30  	var opts []option.ClientOption
    31  	if adcCredPath != "" {
    32  		opts = append(opts, option.WithCredentialsFile(adcCredPath))
    33  	}
    34  
    35  	client, err := spanner.NewClient(ctx, dsn, opts...)
    36  	if err != nil {
    37  		return nil, fromError(err)
    38  	}
    39  
    40  	return client, nil
    41  }