emissary/pkg/client/query_tenants.go

78 lines
1.7 KiB
Go

package client
import (
"context"
"fmt"
"net/url"
"forge.cadoles.com/Cadoles/emissary/internal/datastore"
"github.com/pkg/errors"
)
type QueryTenantsOptionFunc func(*QueryTenantsOptions)
type QueryTenantsOptions struct {
Options []OptionFunc
Limit *int
Offset *int
IDs []TenantID
}
func WithQueryTenantsOptions(funcs ...OptionFunc) QueryTenantsOptionFunc {
return func(opts *QueryTenantsOptions) {
opts.Options = funcs
}
}
func WithQueryTenantsLimit(limit int) QueryTenantsOptionFunc {
return func(opts *QueryTenantsOptions) {
opts.Limit = &limit
}
}
func WithQueryTenantsOffset(offset int) QueryTenantsOptionFunc {
return func(opts *QueryTenantsOptions) {
opts.Offset = &offset
}
}
func WithQueryTenantsID(ids ...datastore.TenantID) QueryTenantsOptionFunc {
return func(opts *QueryTenantsOptions) {
opts.IDs = ids
}
}
func (c *Client) QueryTenants(ctx context.Context, funcs ...QueryTenantsOptionFunc) ([]*Tenant, int, error) {
options := &QueryTenantsOptions{}
for _, fn := range funcs {
fn(options)
}
query := url.Values{}
if options.IDs != nil && len(options.IDs) > 0 {
query.Set("ids", joinSlice(options.IDs))
}
path := fmt.Sprintf("/api/v1/tenants?%s", query.Encode())
response := withResponse[struct {
Tenants []*datastore.Tenant `json:"tenants"`
Total int `json:"total"`
}]()
if options.Options == nil {
options.Options = make([]OptionFunc, 0)
}
if err := c.apiGet(ctx, path, &response, options.Options...); err != nil {
return nil, 0, errors.WithStack(err)
}
if response.Error != nil {
return nil, 0, errors.WithStack(response.Error)
}
return response.Data.Tenants, response.Data.Total, nil
}