From f6d1f6aa15a404f0357db3eb42d9daa5e1c9de8b Mon Sep 17 00:00:00 2001 From: Tim Rots Date: Fri, 8 Sep 2023 17:06:19 +0200 Subject: [PATCH] Add All and AllWithOpts methods to DedicatedServerApi type Add All and AllWithOpts method to the DedicatedServerApi type. to handle pagination and easily allow custom filtering options. Fixes #87 --- dedicated_server.go | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/dedicated_server.go b/dedicated_server.go index 65274fe..bc7da0a 100644 --- a/dedicated_server.go +++ b/dedicated_server.go @@ -467,6 +467,41 @@ func (dsa DedicatedServerApi) List(ctx context.Context, opts DedicatedServerList return result, nil } +// AllWithOpts will return all dedicated servers and allows filtering options be specified as an argument +func (dsa DedicatedServerApi) AllWithOpts(ctx context.Context, opts DedicatedServerListOptions) ([]DedicatedServer, error) { + var allServers []DedicatedServer + + // handle default pagination if Offset or Limit are undefined + if opts.PaginationOptions.Offset == nil || opts.PaginationOptions.Limit == nil { + opts.PaginationOptions = PaginationOptions{Offset: Int(0), Limit: Int(20)} + } + + for { + // List all dedicated servers with defined opts + result, err := DedicatedServerApi{}.List(ctx, opts) + if err != nil { + return nil, err + } + + // Break if no more servers are found + if len(result.Servers) == 0 { + break + } + + // Append servers to list + allServers = append(allServers, result.Servers...) + // Increment Offset with the value of Limit + *opts.PaginationOptions.Offset += *opts.PaginationOptions.Limit + } + + return allServers, nil +} + +// All will return all dedicated servers without optional filters specified +func (dsa DedicatedServerApi) All(ctx context.Context) ([]DedicatedServer, error) { + return dsa.AllWithOpts(ctx, DedicatedServerListOptions{}) +} + func (dsa DedicatedServerApi) Get(ctx context.Context, serverId string) (*DedicatedServer, error) { path := dsa.getPath("/servers/" + serverId) result := &DedicatedServer{}