1
api-go/client.go

102 lines
2.9 KiB
Go
Raw Permalink Normal View History

2023-12-30 19:17:19 +00:00
// Copyright (C) 2023 The Licensing Authors
// SPDX-License-Identifier: MIT
package api
import (
"fmt"
"google.golang.org/grpc"
contributorsv1 "code.pitz.tech/licensing/api-go/contributors/v1"
licensesv1 "code.pitz.tech/licensing/api-go/licenses/v1"
packagesv1 "code.pitz.tech/licensing/api-go/packages/v1"
productsv1 "code.pitz.tech/licensing/api-go/products/v1"
tokensv1 "code.pitz.tech/licensing/api-go/tokens/v1"
usersv1 "code.pitz.tech/licensing/api-go/users/v1"
)
// ClientOption defines a base abstraction for configuring the client.
type ClientOption interface {
// Apply configures the provided ClientConfig when called.
Apply(*ClientConfig)
}
// ClientOptionFunc provides a functional abstraction for configuring the client.
type ClientOptionFunc func(*ClientConfig)
func (fn ClientOptionFunc) Apply(config *ClientConfig) {
if fn != nil {
fn(config)
}
}
// ClientConfig defines the bare requirements needed to establish a connection to the target server instance.
type ClientConfig struct {
ClientConn *grpc.ClientConn
}
// Apply merges this configuration with the destination configuration. This mechanism uses a last-write-wins approach.
func (c ClientConfig) Apply(dst *ClientConfig) {
if c.ClientConn != nil {
dst.ClientConn = c.ClientConn
}
}
// NewClient constructs an API client using the provided configuration or list of options.
func NewClient(opts ...ClientOption) (*Client, error) {
cfg := ClientConfig{}
for _, opt := range opts {
opt.Apply(&cfg)
}
if cfg.ClientConn == nil {
return nil, fmt.Errorf("client conn not provided")
}
client := &Client{
contributors: contributorsv1.NewContributorServiceClient(cfg.ClientConn),
licenses: licensesv1.NewLicenseServiceClient(cfg.ClientConn),
packages: packagesv1.NewPackageServiceClient(cfg.ClientConn),
products: productsv1.NewProductServiceClient(cfg.ClientConn),
tokens: tokensv1.NewTokenServiceClient(cfg.ClientConn),
users: usersv1.NewUserServiceClient(cfg.ClientConn),
}
return client, nil
}
// Client encapsulates all operations that can be performed against the service.
type Client struct {
contributors contributorsv1.ContributorServiceClient
licenses licensesv1.LicenseServiceClient
packages packagesv1.PackageServiceClient
products productsv1.ProductServiceClient
tokens tokensv1.TokenServiceClient
users usersv1.UserServiceClient
}
func (c *Client) Contributors() contributorsv1.ContributorServiceClient {
return c.contributors
}
func (c *Client) Licenses() licensesv1.LicenseServiceClient {
return c.licenses
}
func (c *Client) Packages() packagesv1.PackageServiceClient {
return c.packages
}
func (c *Client) Products() productsv1.ProductServiceClient {
return c.products
}
func (c *Client) Tokens() tokensv1.TokenServiceClient {
return c.tokens
}
func (c *Client) Users() usersv1.UserServiceClient {
return c.users
}