From 7d2b420026c4e4c0a2956793bf0d0e9f74b106fc Mon Sep 17 00:00:00 2001 From: Pierre Millot Date: Thu, 18 Jul 2024 09:36:17 +0200 Subject: [PATCH 1/4] fix(go): use options for more helpers (#3383) --- .../algolia/utils/options.go | 157 ---------- .../algolia/utils/utils.go | 56 ---- .../cts/tests/ParametersWithDataType.java | 69 ++--- playground/go/personalization.go | 3 +- playground/go/search.go | 3 +- templates/go/api.mustache | 288 ++++++++++++++++-- templates/go/search_helpers.mustache | 279 ++++++++++------- templates/go/snippets/method.mustache | 2 +- templates/go/tests/client/method.mustache | 2 +- templates/go/tests/e2e/e2e.mustache | 2 +- .../go/tests/generateInnerParams.mustache | 4 +- templates/go/tests/requests/requests.mustache | 2 +- 12 files changed, 484 insertions(+), 383 deletions(-) delete mode 100644 clients/algoliasearch-client-go/algolia/utils/options.go diff --git a/clients/algoliasearch-client-go/algolia/utils/options.go b/clients/algoliasearch-client-go/algolia/utils/options.go deleted file mode 100644 index 9e81dbbe5a..0000000000 --- a/clients/algoliasearch-client-go/algolia/utils/options.go +++ /dev/null @@ -1,157 +0,0 @@ -package utils - -import ( - "context" - "net/url" - "time" -) - -type Options struct { - // -- Request options for API calls - Context context.Context - QueryParams url.Values - HeaderParams map[string]string - - // -- ChunkedBatch options - WaitForTasks bool - BatchSize int - - // -- Iterable options - MaxRetries int - Timeout func(int) time.Duration - Aggregator func(any, error) - IterableError *IterableError -} - -// --------- Request options for API calls --------- - -type RequestOption interface { - Apply(*Options) -} - -type requestOption func(*Options) - -func (r requestOption) Apply(o *Options) { - r(o) -} - -func WithContext(ctx context.Context) requestOption { - return requestOption(func(o *Options) { - o.Context = ctx - }) -} - -func WithHeaderParam(key string, value any) requestOption { - return requestOption(func(o *Options) { - o.HeaderParams[key] = ParameterToString(value) - }) -} - -func WithQueryParam(key string, value any) requestOption { - return requestOption(func(o *Options) { - o.QueryParams.Set(QueryParameterToString(key), QueryParameterToString(value)) - }) -} - -// --------- ChunkedBatch options --------- - -type ChunkedBatchOption interface { - RequestOption - chunkedBatch() -} - -type chunkedBatchOption func(*Options) - -var ( - _ ChunkedBatchOption = (*chunkedBatchOption)(nil) - _ ChunkedBatchOption = (*requestOption)(nil) -) - -func (c chunkedBatchOption) Apply(o *Options) { - c(o) -} - -func (c chunkedBatchOption) chunkedBatch() {} - -func (r requestOption) chunkedBatch() {} - -func WithWaitForTasks(waitForTasks bool) chunkedBatchOption { - return chunkedBatchOption(func(o *Options) { - o.WaitForTasks = waitForTasks - }) -} - -func WithBatchSize(batchSize int) chunkedBatchOption { - return chunkedBatchOption(func(o *Options) { - o.BatchSize = batchSize - }) -} - -// --------- Iterable options ---------. -type IterableOption interface { - RequestOption - iterable() -} - -type iterableOption func(*Options) - -var ( - _ IterableOption = (*iterableOption)(nil) - _ IterableOption = (*requestOption)(nil) -) - -func (i iterableOption) Apply(o *Options) { - i(o) -} - -func (r requestOption) iterable() {} - -func (i iterableOption) iterable() {} - -func WithMaxRetries(maxRetries int) iterableOption { - return iterableOption(func(o *Options) { - o.MaxRetries = maxRetries - }) -} - -func WithTimeout(timeout func(int) time.Duration) iterableOption { - return iterableOption(func(o *Options) { - o.Timeout = timeout - }) -} - -func WithAggregator(aggregator func(any, error)) iterableOption { - return iterableOption(func(o *Options) { - o.Aggregator = aggregator - }) -} - -func WithIterableError(iterableError *IterableError) iterableOption { - return iterableOption(func(o *Options) { - o.IterableError = iterableError - }) -} - -// --------- Helper to convert options --------- - -func ToRequestOptions[T RequestOption](opts []T) []RequestOption { - requestOpts := make([]RequestOption, 0, len(opts)) - - for _, opt := range opts { - requestOpts = append(requestOpts, opt) - } - - return requestOpts -} - -func ToIterableOptions(opts []ChunkedBatchOption) []IterableOption { - iterableOpts := make([]IterableOption, 0, len(opts)) - - for _, opt := range opts { - if opt, ok := opt.(IterableOption); ok { - iterableOpts = append(iterableOpts, opt) - } - } - - return iterableOpts -} diff --git a/clients/algoliasearch-client-go/algolia/utils/utils.go b/clients/algoliasearch-client-go/algolia/utils/utils.go index 1498b20f02..64bd179cda 100644 --- a/clients/algoliasearch-client-go/algolia/utils/utils.go +++ b/clients/algoliasearch-client-go/algolia/utils/utils.go @@ -8,8 +8,6 @@ import ( "reflect" "strings" "time" - - "github.com/algolia/algoliasearch-client-go/v4/algolia/errs" ) // ToPtr is a helper routine that returns a pointer to the given value. @@ -68,60 +66,6 @@ func IsNilOrEmpty(i any) bool { } } -type IterableError struct { - Validate func(any, error) bool - Message func(any, error) string -} - -func CreateIterable[T any](execute func(*T, error) (*T, error), validate func(*T, error) bool, opts ...IterableOption) (*T, error) { - options := Options{ - MaxRetries: 50, - Timeout: func(_ int) time.Duration { - return 1 * time.Second - }, - } - - for _, opt := range opts { - opt.Apply(&options) - } - - var executor func(*T, error) (*T, error) - - retryCount := 0 - - executor = func(previousResponse *T, previousError error) (*T, error) { - response, responseErr := execute(previousResponse, previousError) - - retryCount++ - - if options.Aggregator != nil { - options.Aggregator(response, responseErr) - } - - if validate(response, responseErr) { - return response, responseErr - } - - if retryCount >= options.MaxRetries { - return nil, errs.NewWaitError(fmt.Sprintf("The maximum number of retries exceeded. (%d/%d)", retryCount, options.MaxRetries)) - } - - if options.IterableError != nil && options.IterableError.Validate(response, responseErr) { - if options.IterableError.Message != nil { - return nil, errs.NewWaitError(options.IterableError.Message(response, responseErr)) - } - - return nil, errs.NewWaitError("an error occurred") - } - - time.Sleep(options.Timeout(retryCount)) - - return executor(response, responseErr) - } - - return executor(nil, nil) -} - // QueryParameterToString convert any query parameters to string. func QueryParameterToString(obj any) string { return strings.ReplaceAll(url.QueryEscape(ParameterToString(obj)), "+", "%20") diff --git a/generators/src/main/java/com/algolia/codegen/cts/tests/ParametersWithDataType.java b/generators/src/main/java/com/algolia/codegen/cts/tests/ParametersWithDataType.java index cfe65781e0..ec1909cf8f 100644 --- a/generators/src/main/java/com/algolia/codegen/cts/tests/ParametersWithDataType.java +++ b/generators/src/main/java/com/algolia/codegen/cts/tests/ParametersWithDataType.java @@ -91,11 +91,11 @@ private Map traverseParams( Object param, IJsonSchemaValidationProperties spec, String parent, - int suffix, + int depth, boolean isParentFreeFormObject ) throws CTSException { if (spec == null) { - return traverseParamsWithoutSpec(paramName, param, parent, suffix); + return traverseParamsWithoutSpec(paramName, param, parent, depth); } String baseType = getTypeName(spec); if (baseType == null) { @@ -103,15 +103,16 @@ private Map traverseParams( } boolean isCodegenModel = spec instanceof CodegenModel; - - Map testOutput = createDefaultOutput(); + Boolean isRequired = null; if (spec instanceof CodegenParameter parameter) { - testOutput.put("required", parameter.required); + isRequired = parameter.required; } else if (spec instanceof CodegenProperty property) { - testOutput.put("required", property.required); + isRequired = property.required; } + Map testOutput = createDefaultOutput(); + if (!isCodegenModel) { // don't overwrite it if it's already a model sometimes it's in lowercase for some reason String lowerBaseType = baseType.substring(0, 1).toLowerCase() + baseType.substring(1); @@ -128,29 +129,32 @@ private Map traverseParams( testOutput.put("key", finalParamName); testOutput.put("isKeyAllUpperCase", StringUtils.isAllUpperCase(finalParamName)); - testOutput.put("parentSuffix", suffix - 1); - testOutput.put("useAnonymousKey", !finalParamName.matches("(.*)_[0-9]$") && suffix != 0); - testOutput.put("suffix", suffix); + testOutput.put("useAnonymousKey", !finalParamName.matches("(.*)_[0-9]$") && depth != 0); testOutput.put("parent", parent); testOutput.put("isRoot", "".equals(parent)); testOutput.put("objectName", getObjectNameForLanguage(baseType)); testOutput.put("isParentFreeFormObject", isParentFreeFormObject); + if (isRequired != null) { + testOutput.put("required", isRequired); + testOutput.put("goFunctionalParam", !isRequired && depth == 0); + } + if (param == null) { handleNull(spec, testOutput); } else if (spec.getIsArray()) { - handleArray(paramName, param, testOutput, spec, suffix); + handleArray(paramName, param, testOutput, spec, depth); } else if (spec.getIsEnum()) { handleEnum(param, testOutput); } else if (spec.getIsModel() || isCodegenModel) { // recursive object - handleModel(paramName, param, testOutput, spec, baseType, parent, suffix, isParentFreeFormObject); + handleModel(paramName, param, testOutput, spec, baseType, parent, depth, isParentFreeFormObject); } else if (baseType.equals("Object")) { // not var, no item, pure free form - handleObject(paramName, param, testOutput, true, suffix); + handleObject(paramName, param, testOutput, true, depth); } else if (spec.getIsMap()) { // free key but only one type - handleMap(paramName, param, testOutput, spec, suffix); + handleMap(paramName, param, testOutput, spec, depth); } else { handlePrimitive(param, testOutput, spec); } @@ -159,14 +163,12 @@ private Map traverseParams( } /** Same method but with inference only */ - private Map traverseParamsWithoutSpec(String paramName, Object param, String parent, int suffix) throws CTSException { + private Map traverseParamsWithoutSpec(String paramName, Object param, String parent, int depth) throws CTSException { String finalParamName = getFinalParamName(paramName); Map testOutput = createDefaultOutput(); testOutput.put("key", finalParamName); - testOutput.put("parentSuffix", suffix - 1); - testOutput.put("useAnonymousKey", !finalParamName.matches("(.*)_[0-9]$") && suffix != 0); - testOutput.put("suffix", suffix); + testOutput.put("useAnonymousKey", !finalParamName.matches("(.*)_[0-9]$") && depth != 0); testOutput.put("parent", parent); testOutput.put("isRoot", "".equals(parent)); // try to infer the type @@ -180,9 +182,9 @@ private Map traverseParamsWithoutSpec(String paramName, Object p if (param == null) { handleNull(null, testOutput); } else if (param instanceof List) { - handleArray(paramName, param, testOutput, null, suffix); + handleArray(paramName, param, testOutput, null, depth); } else if (param instanceof Map) { - handleObject(paramName, param, testOutput, false, suffix); + handleObject(paramName, param, testOutput, false, depth); } else { handlePrimitive(param, testOutput, null); } @@ -233,18 +235,13 @@ private void handleNull(IJsonSchemaValidationProperties spec, Map testOutput, - IJsonSchemaValidationProperties spec, - int suffix - ) throws CTSException { + private void handleArray(String paramName, Object param, Map testOutput, IJsonSchemaValidationProperties spec, int depth) + throws CTSException { List items = (List) param; List values = new ArrayList<>(); for (int i = 0; i < items.size(); i++) { - values.add(traverseParams(paramName + "_" + i, items.get(i), spec == null ? null : spec.getItems(), paramName, suffix + 1, false)); + values.add(traverseParams(paramName + "_" + i, items.get(i), spec == null ? null : spec.getItems(), paramName, depth + 1, false)); } testOutput.put("isArray", true); @@ -263,7 +260,7 @@ private void handleModel( IJsonSchemaValidationProperties spec, String baseType, String parent, - int suffix, + int depth, boolean isParentFreeFormObject ) throws CTSException { if (!spec.getHasVars()) { @@ -274,7 +271,7 @@ private void handleModel( List allOf = composedSchemas.getAllOf(); if (allOf != null && !allOf.isEmpty()) { - traverseParams(paramName, param, allOf.get(0), parent, suffix, false); + traverseParams(paramName, param, allOf.get(0), parent, depth, false); return; } @@ -294,7 +291,7 @@ private void handleModel( CodegenModel model = (CodegenModel) spec; IJsonSchemaValidationProperties match = findMatchingOneOf(param, model); - testOutput.putAll(traverseParams(paramName, param, match, parent, suffix, isParentFreeFormObject)); + testOutput.putAll(traverseParams(paramName, param, match, parent, depth, isParentFreeFormObject)); Map oneOfModel = new HashMap<>(); IJsonSchemaValidationProperties current = match; @@ -355,7 +352,7 @@ private void handleModel( entry.getValue(), additionalPropertiesSpec, paramName, - suffix + 1, + depth + 1, false ); value.put("isAdditionalProperty", true); @@ -375,7 +372,7 @@ private void handleModel( ); } } else { - Map transformedParam = traverseParams(entry.getKey(), entry.getValue(), varSpec, paramName, suffix + 1, false); + Map transformedParam = traverseParams(entry.getKey(), entry.getValue(), varSpec, paramName, depth + 1, false); values.add(transformedParam); } } @@ -409,7 +406,7 @@ private String getTransformedParamName(String paramName) { return paramName; } - private void handleObject(String paramName, Object param, Map testOutput, boolean isSimpleObject, int suffix) + private void handleObject(String paramName, Object param, Map testOutput, boolean isSimpleObject, int depth) throws CTSException { Map vars = (Map) param; @@ -417,7 +414,7 @@ private void handleObject(String paramName, Object param, Map te for (Entry entry : vars.entrySet()) { CodegenParameter objSpec = new CodegenParameter(); objSpec.dataType = inferDataType(entry.getValue(), objSpec, null); - values.add(traverseParams(entry.getKey(), entry.getValue(), objSpec, paramName, suffix + 1, true)); + values.add(traverseParams(entry.getKey(), entry.getValue(), objSpec, paramName, depth + 1, true)); } testOutput.put("isSimpleObject", isSimpleObject); @@ -425,7 +422,7 @@ private void handleObject(String paramName, Object param, Map te testOutput.put("value", values); } - private void handleMap(String paramName, Object param, Map testOutput, IJsonSchemaValidationProperties spec, int suffix) + private void handleMap(String paramName, Object param, Map testOutput, IJsonSchemaValidationProperties spec, int depth) throws CTSException { if (spec.getHasVars()) { throw new CTSException("Spec has vars."); @@ -452,7 +449,7 @@ private void handleMap(String paramName, Object param, Map testO itemType = maybeMatch; } - values.add(traverseParams(entry.getKey(), entry.getValue(), itemType, paramName, suffix + 1, true)); + values.add(traverseParams(entry.getKey(), entry.getValue(), itemType, paramName, depth + 1, true)); } testOutput.put("isFreeFormObject", true); diff --git a/playground/go/personalization.go b/playground/go/personalization.go index 74d805c3aa..5fa84b4b73 100644 --- a/playground/go/personalization.go +++ b/playground/go/personalization.go @@ -6,7 +6,6 @@ import ( "time" "github.com/algolia/algoliasearch-client-go/v4/algolia/personalization" - "github.com/algolia/algoliasearch-client-go/v4/algolia/utils" ) func testPersonalization(appID, apiKey string) int { @@ -20,7 +19,7 @@ func testPersonalization(appID, apiKey string) int { // it will fail expectedly because of the very short timeout to showcase the context usage. deleteUserProfileResponse, err := personalizationClient.DeleteUserProfile( personalizationClient.NewApiDeleteUserProfileRequest("userToken"), - utils.WithContext(ctx), + personalization.WithContext(ctx), ) if err != nil { fmt.Printf("request error with DeleteUserProfile: %v\n", err) diff --git a/playground/go/search.go b/playground/go/search.go index a975e4caee..4ab11f5053 100644 --- a/playground/go/search.go +++ b/playground/go/search.go @@ -4,7 +4,6 @@ import ( "context" "github.com/algolia/algoliasearch-client-go/v4/algolia/search" - "github.com/algolia/algoliasearch-client-go/v4/algolia/utils" ) func testSearch(appID, apiKey string) int { @@ -14,7 +13,7 @@ func testSearch(appID, apiKey string) int { panic(err) } - res, err := searchClient.WaitForApiKey(search.API_KEY_OPERATION_ADD, "test", &search.ApiKey{}, utils.WithContext(context.Background()), utils.WithMaxRetries(4)) + res, err := searchClient.WaitForApiKey("test", search.API_KEY_OPERATION_ADD, search.WithContext(context.Background()), search.WithMaxRetries(4)) print(res) print(err.Error()) diff --git a/templates/go/api.mustache b/templates/go/api.mustache index af8132646a..7ec2e62718 100644 --- a/templates/go/api.mustache +++ b/templates/go/api.mustache @@ -3,28 +3,278 @@ package {{packageName}} {{#operations}} import ( - "bytes" "context" - "encoding/json" - "io" + "encoding/json" + "fmt" "net/http" "net/url" - "strings" + "strings" {{#isSearchClient}} "github.com/algolia/algoliasearch-client-go/v4/algolia/errs" + "cmp" "crypto/hmac" "crypto/sha256" "encoding/base64" "encoding/hex" + "errors" "slices" "sort" "time" {{/isSearchClient}} "github.com/algolia/algoliasearch-client-go/v4/algolia/utils" - "github.com/algolia/algoliasearch-client-go/v4/algolia/call" ) +type config struct { + // -- Request options for API calls + context context.Context + queryParams url.Values + headerParams map[string]string + + {{#isSearchClient}} + // -- ChunkedBatch options + waitForTasks bool + batchSize int + + // -- Partial update options + createIfNotExists bool + + // -- Iterable options + maxRetries int + timeout func(int) time.Duration + aggregator func(any, error) + iterableError *IterableError + + // -- WaitForApiKey options + apiKey *ApiKey + {{/isSearchClient}} +} + +type RequestOption interface { + apply(*config) +} + +type requestOption func(*config) + +func (r requestOption) apply(c *config) { + r(c) +} + +func WithContext(ctx context.Context) requestOption { + return requestOption(func(c *config) { + c.context = ctx + }) +} + +func WithHeaderParam(key string, value any) requestOption { + return requestOption(func(c *config) { + c.headerParams[key] = utils.ParameterToString(value) + }) +} + +func WithQueryParam(key string, value any) requestOption { + return requestOption(func(c *config) { + c.queryParams.Set(utils.QueryParameterToString(key), utils.QueryParameterToString(value)) + }) +} + +{{#isSearchClient}} + +// --------- ChunkedBatch options --------- + +type ChunkedBatchOption interface { + RequestOption + chunkedBatch() +} + +type chunkedBatchOption func(*config) + +var ( + _ ChunkedBatchOption = (*chunkedBatchOption)(nil) + _ ChunkedBatchOption = (*requestOption)(nil) +) + +func (c chunkedBatchOption) apply(conf *config) { + c(conf) +} + +func (c chunkedBatchOption) chunkedBatch() {} + +func (r requestOption) chunkedBatch() {} + +func WithWaitForTasks(waitForTasks bool) chunkedBatchOption { + return chunkedBatchOption(func(c *config) { + c.waitForTasks = waitForTasks + }) +} + +func WithBatchSize(batchSize int) chunkedBatchOption { + return chunkedBatchOption(func(c *config) { + c.batchSize = batchSize + }) +} + +// --------- ChunkedBatch options --------- + +type PartialUpdateObjectsOption interface { + ChunkedBatchOption + partialUpdateObjects() +} + +type partialUpdateObjectsOption func(*config) + +var ( + _ PartialUpdateObjectsOption = (*partialUpdateObjectsOption)(nil) + _ PartialUpdateObjectsOption = (*chunkedBatchOption)(nil) + _ PartialUpdateObjectsOption = (*requestOption)(nil) +) + +func (p partialUpdateObjectsOption) apply(c *config) { + p(c) +} + +func (p partialUpdateObjectsOption) partialUpdateObjects() {} + +func (p partialUpdateObjectsOption) chunkedBatch() {} + +func (c chunkedBatchOption) partialUpdateObjects() {} + +func (r requestOption) partialUpdateObjects() {} + +func WithCreateIfNotExists(createIfNotExists bool) partialUpdateObjectsOption { + return partialUpdateObjectsOption(func(c *config) { + c.createIfNotExists = createIfNotExists + }) +} + +// --------- Iterable options ---------. + +type IterableOption interface { + RequestOption + iterable() +} + +type iterableOption func(*config) + +var ( + _ IterableOption = (*iterableOption)(nil) + _ IterableOption = (*requestOption)(nil) +) + +func (i iterableOption) apply(c *config) { + i(c) +} + +func (r requestOption) iterable() {} + +func (i iterableOption) iterable() {} + +func WithMaxRetries(maxRetries int) iterableOption { + return iterableOption(func(c *config) { + c.maxRetries = maxRetries + }) +} + +func WithTimeout(timeout func(int) time.Duration) iterableOption { + return iterableOption(func(c *config) { + c.timeout = timeout + }) +} + +func WithAggregator(aggregator func(any, error)) iterableOption { + return iterableOption(func(c *config) { + c.aggregator = aggregator + }) +} + +func WithIterableError(iterableError *IterableError) iterableOption { + return iterableOption(func(c *config) { + c.iterableError = iterableError + }) +} + +// --------- WaitForKey options ---------. + +type WaitForApiKeyOption interface { + IterableOption + waitForApiKey() +} + +type waitForApiKeyOption func(*config) + +var ( + _ WaitForApiKeyOption = (*waitForApiKeyOption)(nil) + _ WaitForApiKeyOption = (*iterableOption)(nil) + _ WaitForApiKeyOption = (*requestOption)(nil) +) + +func (w waitForApiKeyOption) apply(c *config) { + w(c) +} + +func (w waitForApiKeyOption) waitForApiKey() {} + +func (w waitForApiKeyOption) iterable() {} + +func (r requestOption) waitForApiKey() {} + +func (i iterableOption) waitForApiKey() {} + +func WithApiKey(apiKey *ApiKey) waitForApiKeyOption { + return waitForApiKeyOption(func(c *config) { + c.apiKey = apiKey + }) +} + +// --------- Helper to convert options --------- + +func toRequestOptions[T RequestOption](opts []T) []RequestOption { + requestOpts := make([]RequestOption, 0, len(opts)) + + for _, opt := range opts { + requestOpts = append(requestOpts, opt) + } + + return requestOpts +} + +func toIterableOptions(opts []ChunkedBatchOption) []IterableOption { + iterableOpts := make([]IterableOption, 0, len(opts)) + + for _, opt := range opts { + if opt, ok := opt.(IterableOption); ok { + iterableOpts = append(iterableOpts, opt) + } + } + + return iterableOpts +} + +func toIterableOptionsWaitFor(opts []WaitForApiKeyOption) []IterableOption { + iterableOpts := make([]IterableOption, 0, len(opts)) + + for _, opt := range opts { + if opt, ok := opt.(IterableOption); ok { + iterableOpts = append(iterableOpts, opt) + } + } + + return iterableOpts +} + +func toChunkedBatchOptions(opts []PartialUpdateObjectsOption) []ChunkedBatchOption { + chunkedBatchOpts := make([]ChunkedBatchOption, 0, len(opts)) + + for _, opt := range opts { + if opt, ok := opt.(ChunkedBatchOption); ok { + chunkedBatchOpts = append(chunkedBatchOpts, opt) + } + } + + return chunkedBatchOpts +} +{{/isSearchClient}} + {{#operation}} {{#hasParams}} func (r *{{#structPrefix}}{{&classname}}{{/structPrefix}}{{^structPrefix}}Api{{/structPrefix}}{{operationId}}Request) UnmarshalJSON(b []byte) error { @@ -105,7 +355,7 @@ func (r {{#structPrefix}}{{&classname}}{{/structPrefix}}{{^structPrefix}}Api{{/s {{#allParams}} @param {{paramName}} {{dataType}}{{#description}} - {{{.}}}{{/description}} {{/allParams}} - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails @@ -114,7 +364,7 @@ func (r {{#structPrefix}}{{&classname}}{{/structPrefix}}{{^structPrefix}}Api{{/s Deprecated {{/isDeprecated}} */ -func (c *APIClient) {{nickname}}WithHTTPInfo({{#hasParams}}r {{#structPrefix}}{{&classname}}{{/structPrefix}}{{^structPrefix}}Api{{/structPrefix}}{{operationId}}Request,{{/hasParams}} opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) {{nickname}}WithHTTPInfo({{#hasParams}}r {{#structPrefix}}{{&classname}}{{/structPrefix}}{{^structPrefix}}Api{{/structPrefix}}{{operationId}}Request,{{/hasParams}} opts ...RequestOption) (*http.Response, []byte, error) { {{#vendorExtensions}} requestPath := "{{{path}}}"{{#pathParams}} requestPath = strings.ReplaceAll(requestPath, {{=<% %>=}}"{<%baseName%>}"<%={{ }}=%>, {{#x-is-custom-request}}utils.ParameterToString(r.{{paramName}}){{/x-is-custom-request}}{{^x-is-custom-request}}url.PathEscape(utils.ParameterToString(r.{{paramName}})){{/x-is-custom-request}}){{/pathParams}} @@ -172,17 +422,17 @@ func (c *APIClient) {{nickname}}WithHTTPInfo({{#hasParams}}r {{#structPrefix}}{{ {{/required}} {{/allParams}} - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } {{#vendorExtensions.x-is-custom-request}} {{#queryParams}} {{^required}}if !utils.IsNilOrEmpty(r.{{paramName}}) { {{/required}} for k, v := range r.{{paramName}} { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } {{^required}} } {{/required}} {{/queryParams}} @@ -190,29 +440,29 @@ func (c *APIClient) {{nickname}}WithHTTPInfo({{#hasParams}}r {{#structPrefix}}{{ {{^vendorExtensions.x-is-custom-request}} {{#queryParams}} {{#required}} - options.QueryParams.Set("{{baseName}}", utils.QueryParameterToString({{^isFreeFormObject}}{{^isArray}}{{^isPrimitiveType}}{{^isEnumRef}}*{{/isEnumRef}}{{/isPrimitiveType}}{{/isArray}}{{/isFreeFormObject}}r.{{paramName}})) + conf.queryParams.Set("{{baseName}}", utils.QueryParameterToString({{^isFreeFormObject}}{{^isArray}}{{^isPrimitiveType}}{{^isEnumRef}}*{{/isEnumRef}}{{/isPrimitiveType}}{{/isArray}}{{/isFreeFormObject}}r.{{paramName}})) {{/required}} {{^required}} if !utils.IsNilOrEmpty(r.{{paramName}}) { - options.QueryParams.Set("{{baseName}}", utils.QueryParameterToString({{^isFreeFormObject}}{{^isArray}}{{^isEnumRef}}*{{/isEnumRef}}{{/isArray}}{{/isFreeFormObject}}r.{{paramName}})) + conf.queryParams.Set("{{baseName}}", utils.QueryParameterToString({{^isFreeFormObject}}{{^isArray}}{{^isEnumRef}}*{{/isEnumRef}}{{/isArray}}{{/isFreeFormObject}}r.{{paramName}})) } {{/required}} {{/queryParams}} {{/vendorExtensions.x-is-custom-request}} {{#headerParams}} {{#required}} - options.HeaderParams["{{baseName}}"] = utils.ParameterToString({{^isFreeFormObject}}{{^isArray}}{{^isPrimitiveType}}{{^isEnumRef}}*{{/isEnumRef}}{{/isPrimitiveType}}{{/isArray}}{{/isFreeFormObject}}r.{{paramName}}) + conf.headerParams["{{baseName}}"] = utils.ParameterToString({{^isFreeFormObject}}{{^isArray}}{{^isPrimitiveType}}{{^isEnumRef}}*{{/isEnumRef}}{{/isPrimitiveType}}{{/isArray}}{{/isFreeFormObject}}r.{{paramName}}) {{/required}} {{^required}} if !utils.IsNilOrEmpty(r.{{paramName}}) { - options.HeaderParams["{{baseName}}"] = utils.ParameterToString({{^isFreeFormObject}}{{^isArray}}{{^isEnumRef}}*{{/isEnumRef}}{{/isArray}}{{/isFreeFormObject}}r.{{paramName}}) + conf.headerParams["{{baseName}}"] = utils.ParameterToString({{^isFreeFormObject}}{{^isArray}}{{^isEnumRef}}*{{/isEnumRef}}{{/isArray}}{{/isFreeFormObject}}r.{{paramName}}) } {{/required}} {{/headerParams}} // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any @@ -225,7 +475,7 @@ func (c *APIClient) {{nickname}}WithHTTPInfo({{#hasParams}}r {{#structPrefix}}{{ postBody = r.{{paramName}}{{^required}} } {{/required}} {{/bodyParams}} - req, err := c.prepareRequest(options.Context, requestPath, http.Method{{httpMethod}}, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.Method{{httpMethod}}, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -236,7 +486,7 @@ func (c *APIClient) {{nickname}}WithHTTPInfo({{#hasParams}}r {{#structPrefix}}{{ /* {{operationId}} casts the HTTP response body to a defined struct. {{> operation_description}} -func (c *APIClient) {{nickname}}({{#hasParams}}r {{#structPrefix}}{{&classname}}{{/structPrefix}}{{^structPrefix}}Api{{/structPrefix}}{{operationId}}Request,{{/hasParams}} opts ...utils.RequestOption) ({{#returnType}}{{^isArray}}{{^returnTypeIsPrimitive}}*{{/returnTypeIsPrimitive}}{{/isArray}}{{{.}}}, {{/returnType}}error) { +func (c *APIClient) {{nickname}}({{#hasParams}}r {{#structPrefix}}{{&classname}}{{/structPrefix}}{{^structPrefix}}Api{{/structPrefix}}{{operationId}}Request,{{/hasParams}} opts ...RequestOption) ({{#returnType}}{{^isArray}}{{^returnTypeIsPrimitive}}*{{/returnTypeIsPrimitive}}{{/isArray}}{{{.}}}, {{/returnType}}error) { {{#returnType}} var returnValue {{^isArray}}{{^returnTypeIsPrimitive}}*{{/returnTypeIsPrimitive}}{{/isArray}}{{{.}}} {{/returnType}} diff --git a/templates/go/search_helpers.mustache b/templates/go/search_helpers.mustache index a3f2358a96..c95a5c5415 100644 --- a/templates/go/search_helpers.mustache +++ b/templates/go/search_helpers.mustache @@ -1,13 +1,68 @@ + +type IterableError struct { + Validate func(any, error) bool + Message func(any, error) string +} + +func CreateIterable[T any](execute func(*T, error) (*T, error), validate func(*T, error) bool, opts ...IterableOption) (*T, error) { + conf := config{ + maxRetries: 50, + timeout: func(_ int) time.Duration { + return 1 * time.Second + }, + } + + for _, opt := range opts { + opt.apply(&conf) + } + + var executor func(*T, error) (*T, error) + + retryCount := 0 + + executor = func(previousResponse *T, previousError error) (*T, error) { + response, responseErr := execute(previousResponse, previousError) + + retryCount++ + + if conf.aggregator != nil { + conf.aggregator(response, responseErr) + } + + if validate(response, responseErr) { + return response, nil + } + + if retryCount >= conf.maxRetries { + return nil, errs.NewWaitError(fmt.Sprintf("The maximum number of retries exceeded. (%d/%d)", retryCount, conf.maxRetries)) + } + + if conf.iterableError != nil && conf.iterableError.Validate(response, responseErr) { + if conf.iterableError.Message != nil { + return nil, errs.NewWaitError(conf.iterableError.Message(response, responseErr)) + } + + return nil, errs.NewWaitError("an error occurred") + } + + time.Sleep(conf.timeout(retryCount)) + + return executor(response, responseErr) + } + + return executor(nil, nil) +} + /* SearchForHits calls the `search` method but with certainty that we will only request Algolia records (hits) and not facets. Disclaimer: We don't assert that the parameters you pass to this method only contains `hits` requests to prevent impacting search performances, this helper is purely for typing purposes. @param r ApiSearchRequest - Body of the `search` operation. - @param opts ...utils.RequestOption - Optional parameters for the request. + @param opts ...RequestOption - Optional parameters for the request. @return []SearchResponse - List of hits. @return error - Error if any. */ -func (c *APIClient) SearchForHits(r ApiSearchRequest, opts ...utils.RequestOption) ([]SearchResponse, error) { +func (c *APIClient) SearchForHits(r ApiSearchRequest, opts ...RequestOption) ([]SearchResponse, error) { res, err := c.Search(r, opts...) if err != nil { return nil, err @@ -29,11 +84,11 @@ SearchForFacets calls the `search` method but with certainty that we will only r Disclaimer: We don't assert that the parameters you pass to this method only contains `facets` requests to prevent impacting search performances, this helper is purely for typing purposes. @param r ApiSearchRequest - Body of the `search` operation. - @param opts ...utils.RequestOption - Optional parameters for the request. + @param opts ...RequestOption - Optional parameters for the request. @return []SearchForFacetValuesResponse - List of facet hits. @return error - Error if any. */ -func (c *APIClient) SearchForFacets(r ApiSearchRequest, opts ...utils.RequestOption) ([]SearchForFacetValuesResponse, error) { +func (c *APIClient) SearchForFacets(r ApiSearchRequest, opts ...RequestOption) ([]SearchForFacetValuesResponse, error) { res, err := c.Search(r, opts...) if err != nil { return nil, err @@ -57,23 +112,23 @@ It returns an error if the operation failed. @param indexName string - Index name. @param taskID int64 - Task ID. - @param opts ...utils.IterableOption - Optional parameters for the request. + @param opts ...IterableOption - Optional parameters for the request. @return *GetTaskResponse - Task response. @return error - Error if any. */ func (c *APIClient) WaitForTask( indexName string, taskID int64, - opts ...utils.IterableOption, + opts ...IterableOption, ) (*GetTaskResponse, error) { // provide a defalut timeout function - opts = append([]utils.IterableOption{utils.WithTimeout(func(count int) time.Duration { + opts = append([]IterableOption{WithTimeout(func(count int) time.Duration { return time.Duration(min(200*count, 5000)) * time.Millisecond })}, opts...) - return utils.CreateIterable( //nolint:wrapcheck + return CreateIterable( //nolint:wrapcheck func(*GetTaskResponse, error) (*GetTaskResponse, error) { - return c.GetTask(c.NewApiGetTaskRequest(indexName, taskID), utils.ToRequestOptions(opts)...) + return c.GetTask(c.NewApiGetTaskRequest(indexName, taskID), toRequestOptions(opts)...) }, func(response *GetTaskResponse, err error) bool { if err != nil || response == nil { @@ -92,22 +147,22 @@ It returns the task response if the operation was successful. It returns an error if the operation failed. @param taskID int64 - Task ID. - @param opts ...utils.IterableOption - Optional parameters for the request. + @param opts ...IterableOption - Optional parameters for the request. @return *GetTaskResponse - Task response. @return error - Error if any. */ func (c *APIClient) WaitForAppTask( taskID int64, - opts ...utils.IterableOption, + opts ...IterableOption, ) (*GetTaskResponse, error) { // provide a defalut timeout function - opts = append([]utils.IterableOption{utils.WithTimeout(func(count int) time.Duration { + opts = append([]IterableOption{WithTimeout(func(count int) time.Duration { return time.Duration(min(200*count, 5000)) * time.Millisecond })}, opts...) - return utils.CreateIterable( //nolint:wrapcheck + return CreateIterable( //nolint:wrapcheck func(*GetTaskResponse, error) (*GetTaskResponse, error) { - return c.GetAppTask(c.NewApiGetAppTaskRequest(taskID), utils.ToRequestOptions(opts)...) + return c.GetAppTask(c.NewApiGetAppTaskRequest(taskID), toRequestOptions(opts)...) }, func(response *GetTaskResponse, err error) bool { if err != nil || response == nil { @@ -120,6 +175,24 @@ func (c *APIClient) WaitForAppTask( ) } +func slicesEqualUnordered[T cmp.Ordered](a []T, b []T) bool { + if len(a) != len(b) { + return false + } + + // make a copy and sort it to avoid modifying the original slice + aCopy := make([]T, len(a)) + copy(aCopy, a) + + bCopy := make([]T, len(b)) + copy(bCopy, b) + + slices.Sort(aCopy) + slices.Sort(bCopy) + + return slices.Equal(aCopy, bCopy) +} + /* WaitForApiKey waits for an API key to be created, deleted or updated. It returns the API key response if the operation was successful. @@ -133,32 +206,28 @@ The operation can be one of the following: If the operation is "update", the apiKey parameter must be set. If the operation is "delete" or "add", the apiKey parameter is not used. - @param operation ApiKeyOperation - Operation type - add, delete or update. @param key string - API key. - @param apiKey *ApiKey - API key structure - required for update operation. - @param opts ...utils.IterableOption - Optional parameters for the request. + @param operation ApiKeyOperation - Operation type - add, delete or update. + @param opts ...WaitForApiKeyOption - Optional parameters for the request, you must provide WithApiKey if the operation is "update". @return *GetApiKeyResponse - API key response. @return error - Error if any. */ func (c *APIClient) WaitForApiKey( + key string, operation ApiKeyOperation, - key string, - apiKey *ApiKey, - opts ...utils.IterableOption, + opts ...WaitForApiKeyOption, ) (*GetApiKeyResponse, error) { - if operation != API_KEY_OPERATION_ADD && operation != API_KEY_OPERATION_DELETE && operation != API_KEY_OPERATION_UPDATE { - return nil, &errs.WaitKeyOperationError{} - } + conf := config{} - // provide a defalut timeout function - opts = append([]utils.IterableOption{utils.WithTimeout(func(count int) time.Duration { - return time.Duration(min(200*count, 5000)) * time.Millisecond - })}, opts...) + for _, opt := range opts { + opt.apply(&conf) + } - var validateFunc func(*GetApiKeyResponse, error) bool + var validateFunc func(*GetApiKeyResponse, error) bool - if operation == API_KEY_OPERATION_UPDATE { - if apiKey == nil { + switch operation { + case API_KEY_OPERATION_UPDATE: + if conf.apiKey == nil { return nil, &errs.WaitKeyUpdateError{} } @@ -167,75 +236,67 @@ func (c *APIClient) WaitForApiKey( return false } - if apiKey.GetDescription() != response.GetDescription() { + if conf.apiKey.GetDescription() != response.GetDescription() { return false } - if apiKey.GetQueryParameters() != response.GetQueryParameters() { + if conf.apiKey.GetQueryParameters() != response.GetQueryParameters() { return false } - if apiKey.GetMaxHitsPerQuery() != response.GetMaxHitsPerQuery() { + if conf.apiKey.GetMaxHitsPerQuery() != response.GetMaxHitsPerQuery() { return false } - if apiKey.GetMaxQueriesPerIPPerHour() != response.GetMaxQueriesPerIPPerHour() { + if conf.apiKey.GetMaxQueriesPerIPPerHour() != response.GetMaxQueriesPerIPPerHour() { return false } - if apiKey.GetValidity() != response.GetValidity() { + if conf.apiKey.GetValidity() != response.GetValidity() { return false } - slices.Sort(apiKey.Acl) - slices.Sort(response.Acl) - - if !slices.Equal(apiKey.Acl, response.Acl) { + if !slicesEqualUnordered(conf.apiKey.Acl, response.Acl) { return false } - slices.Sort(apiKey.Indexes) - slices.Sort(response.Indexes) - - if !slices.Equal(apiKey.Indexes, response.Indexes) { + if !slicesEqualUnordered(conf.apiKey.Indexes, response.Indexes) { return false } - slices.Sort(apiKey.Referers) - slices.Sort(response.Referers) - - return slices.Equal(apiKey.Referers, response.Referers) + return slicesEqualUnordered(conf.apiKey.Referers, response.Referers) } - } else { + case API_KEY_OPERATION_ADD: validateFunc = func(response *GetApiKeyResponse, err error) bool { - switch operation { - case API_KEY_OPERATION_ADD: - if _, ok := err.(*APIError); ok { - apiErr := err.(*APIError) - - return apiErr.Status != 404 - } - - return true - case API_KEY_OPERATION_DELETE: - if _, ok := err.(*APIError); ok { - apiErr := err.(*APIError) + var apiErr *APIError + if errors.As(err, &apiErr) { + return apiErr.Status != 404 + } - return apiErr.Status == 404 - } + return true + } + case API_KEY_OPERATION_DELETE: + validateFunc = func(response *GetApiKeyResponse, err error) bool { + var apiErr *APIError - return false - } - return false + return errors.As(err, &apiErr) && apiErr.Status == 404 } + default: + return nil, &errs.WaitKeyOperationError{} } - return utils.CreateIterable( //nolint:wrapcheck + + // provide a defalut timeout function + opts = append([]WaitForApiKeyOption{WithTimeout(func(count int) time.Duration { + return time.Duration(min(200*count, 5000)) * time.Millisecond + })}, opts...) + + return CreateIterable( //nolint:wrapcheck func(*GetApiKeyResponse, error) (*GetApiKeyResponse, error) { - return c.GetApiKey(c.NewApiGetApiKeyRequest(key), utils.ToRequestOptions(opts)...) + return c.GetApiKey(c.NewApiGetApiKeyRequest(key), toRequestOptions(opts)...) }, validateFunc, - opts..., + toIterableOptionsWaitFor(opts)..., ) } @@ -244,16 +305,16 @@ BrowseObjects allows to aggregate all the hits returned by the API calls. @param indexName string - Index name. @param browseParams BrowseParamsObject - Browse parameters. - @param opts ...utils.IterableOption - Optional parameters for the request. + @param opts ...IterableOption - Optional parameters for the request. @return *BrowseResponse - Browse response. @return error - Error if any. */ func (c *APIClient) BrowseObjects( indexName string, browseParams BrowseParamsObject, - opts ...utils.IterableOption, + opts ...IterableOption, ) (*BrowseResponse, error) { - return utils.CreateIterable( //nolint:wrapcheck + return CreateIterable( //nolint:wrapcheck func(previousResponse *BrowseResponse, previousErr error) (*BrowseResponse, error) { if previousResponse != nil { browseParams.Cursor = previousResponse.Cursor @@ -261,7 +322,7 @@ func (c *APIClient) BrowseObjects( return c.Browse( c.NewApiBrowseRequest(indexName).WithBrowseParams(BrowseParamsObjectAsBrowseParams(&browseParams)), - utils.ToRequestOptions(opts)..., + toRequestOptions(opts)..., ) }, func(response *BrowseResponse, responseErr error) bool { @@ -276,21 +337,21 @@ BrowseRules allows to aggregate all the rules returned by the API calls. @param indexName string - Index name. @param searchRulesParams SearchRulesParams - Search rules parameters. - @param opts ...utils.IterableOption - Optional parameters for the request. + @param opts ...IterableOption - Optional parameters for the request. @return *SearchRulesResponse - Search rules response. @return error - Error if any. */ func (c *APIClient) BrowseRules( indexName string, searchRulesParams SearchRulesParams, - opts ...utils.IterableOption, + opts ...IterableOption, ) (*SearchRulesResponse, error) { hitsPerPage := int32(1000) if searchRulesParams.HitsPerPage != nil { hitsPerPage = *searchRulesParams.HitsPerPage } - return utils.CreateIterable( //nolint:wrapcheck + return CreateIterable( //nolint:wrapcheck func(previousResponse *SearchRulesResponse, previousErr error) (*SearchRulesResponse, error) { searchRulesParams.HitsPerPage = &hitsPerPage @@ -304,7 +365,7 @@ func (c *APIClient) BrowseRules( return c.SearchRules( c.NewApiSearchRulesRequest(indexName).WithSearchRulesParams(&searchRulesParams), - utils.ToRequestOptions(opts)..., + toRequestOptions(opts)..., ) }, func(response *SearchRulesResponse, responseErr error) bool { @@ -319,14 +380,14 @@ BrowseSynonyms allows to aggregate all the synonyms returned by the API calls. @param indexName string - Index name. @param searchSynonymsParams SearchSynonymsParams - Search synonyms parameters. - @param opts ...utils.IterableOption - Optional parameters for the request. + @param opts ...IterableOption - Optional parameters for the request. @return *SearchSynonymsResponse - Search synonyms response. @return error - Error if any. */ func (c *APIClient) BrowseSynonyms( indexName string, searchSynonymsParams SearchSynonymsParams, - opts ...utils.IterableOption, + opts ...IterableOption, ) (*SearchSynonymsResponse, error) { hitsPerPage := int32(1000) if searchSynonymsParams.HitsPerPage != nil { @@ -337,7 +398,7 @@ func (c *APIClient) BrowseSynonyms( searchSynonymsParams.Page = utils.ToPtr(int32(0)) } - return utils.CreateIterable( //nolint:wrapcheck + return CreateIterable( //nolint:wrapcheck func(previousResponse *SearchSynonymsResponse, previousErr error) (*SearchSynonymsResponse, error) { searchSynonymsParams.HitsPerPage = &hitsPerPage @@ -347,7 +408,7 @@ func (c *APIClient) BrowseSynonyms( return c.SearchSynonyms( c.NewApiSearchSynonymsRequest(indexName).WithSearchSynonymsParams(&searchSynonymsParams), - utils.ToRequestOptions(opts)..., + toRequestOptions(opts)..., ) }, func(response *SearchSynonymsResponse, responseErr error) bool { @@ -454,12 +515,12 @@ func (c *APIClient) GetSecuredApiKeyRemainingValidity(securedApiKey string) (tim // Helper: Saves the given array of objects in the given index. The `chunkedBatch` helper is used under the hood, which creates a `batch` requests with at most 1000 objects in it. -func (c *APIClient) SaveObjects(indexName string, objects []map[string]any, opts ...utils.ChunkedBatchOption) ([]BatchResponse, error) { +func (c *APIClient) SaveObjects(indexName string, objects []map[string]any, opts ...ChunkedBatchOption) ([]BatchResponse, error) { return c.ChunkedBatch(indexName, objects, ACTION_ADD_OBJECT, opts...) } // Helper: Deletes every records for the given objectIDs. The `chunkedBatch` helper is used under the hood, which creates a `batch` requests with at most 1000 objectIDs in it. -func (c *APIClient) DeleteObjects(indexName string, objectIDs []string, opts ...utils.ChunkedBatchOption) ([]BatchResponse, error) { +func (c *APIClient) DeleteObjects(indexName string, objectIDs []string, opts ...ChunkedBatchOption) ([]BatchResponse, error) { objects := make([]map[string]any, 0, len(objectIDs)) for _, id := range objectIDs { @@ -470,49 +531,57 @@ func (c *APIClient) DeleteObjects(indexName string, objectIDs []string, opts ... } // Helper: Replaces object content of all the given objects according to their respective `objectID` field. The `chunkedBatch` helper is used under the hood, which creates a `batch` requests with at most 1000 objects in it. -func (c *APIClient) PartialUpdateObjects(indexName string, objects []map[string]any, createIfNotExists bool, opts ...utils.ChunkedBatchOption) ([]BatchResponse, error) { +func (c *APIClient) PartialUpdateObjects(indexName string, objects []map[string]any, opts ...PartialUpdateObjectsOption) ([]BatchResponse, error) { + conf := config{ + createIfNotExists: true, + } + + for _, opt := range opts { + opt.apply(&conf) + } + var action Action - if createIfNotExists { + if conf.createIfNotExists { action = ACTION_PARTIAL_UPDATE_OBJECT } else { action = ACTION_PARTIAL_UPDATE_OBJECT_NO_CREATE } - return c.ChunkedBatch(indexName, objects, action, opts...) + return c.ChunkedBatch(indexName, objects, action, toChunkedBatchOptions(opts)...) } // ChunkedBatch chunks the given `objects` list in subset of 1000 elements max in order to make it fit in `batch` requests. -func (c *APIClient) ChunkedBatch(indexName string, objects []map[string]any, action Action, opts ...utils.ChunkedBatchOption) ([]BatchResponse, error) { - options := utils.Options{ - WaitForTasks: false, - BatchSize: 1000, +func (c *APIClient) ChunkedBatch(indexName string, objects []map[string]any, action Action, opts ...ChunkedBatchOption) ([]BatchResponse, error) { + conf := config{ + waitForTasks: false, + batchSize: 1000, } for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } - requests := make([]BatchRequest, 0, len(objects)%options.BatchSize) - responses := make([]BatchResponse, 0, len(objects)%options.BatchSize) + requests := make([]BatchRequest, 0, len(objects)%conf.batchSize) + responses := make([]BatchResponse, 0, len(objects)%conf.batchSize) for i, obj := range objects { requests = append(requests, *NewBatchRequest(action, obj)) - if len(requests) == options.BatchSize || i == len(objects)-1 { - resp, err := c.Batch(c.NewApiBatchRequest(indexName, NewBatchWriteParams(requests)), utils.ToRequestOptions(opts)...) + if len(requests) == conf.batchSize || i == len(objects)-1 { + resp, err := c.Batch(c.NewApiBatchRequest(indexName, NewBatchWriteParams(requests)), toRequestOptions(opts)...) if err != nil { return nil, err } responses = append(responses, *resp) - requests = make([]BatchRequest, 0, len(objects)%options.BatchSize) + requests = make([]BatchRequest, 0, len(objects)%conf.batchSize) } } - if options.WaitForTasks { + if conf.waitForTasks { for _, resp := range responses { - _, err := c.WaitForTask(indexName, resp.TaskID, utils.ToIterableOptions(opts)...) + _, err := c.WaitForTask(indexName, resp.TaskID, toIterableOptions(opts)...) if err != nil { return nil, err } @@ -524,42 +593,42 @@ func (c *APIClient) ChunkedBatch(indexName string, objects []map[string]any, act // ReplaceAllObjects replaces all objects (records) in the given `indexName` with the given `objects`. A temporary index is created during this process in order to backup your data. // See https://api-clients-automation.netlify.app/docs/contributing/add-new-api-client#5-helpers for implementation details. -func (c *APIClient) ReplaceAllObjects(indexName string, objects []map[string]any, opts ...utils.ChunkedBatchOption) (*ReplaceAllObjectsResponse, error) { +func (c *APIClient) ReplaceAllObjects(indexName string, objects []map[string]any, opts ...ChunkedBatchOption) (*ReplaceAllObjectsResponse, error) { tmpIndexName := fmt.Sprintf("%s_tmp_%d", indexName, time.Now().UnixNano()) - copyResp, err := c.OperationIndex(c.NewApiOperationIndexRequest(indexName, NewOperationIndexParams(OPERATION_TYPE_COPY, tmpIndexName, WithOperationIndexParamsScope([]ScopeType{SCOPE_TYPE_SETTINGS, SCOPE_TYPE_RULES, SCOPE_TYPE_SYNONYMS}))), utils.ToRequestOptions(opts)...) + copyResp, err := c.OperationIndex(c.NewApiOperationIndexRequest(indexName, NewOperationIndexParams(OPERATION_TYPE_COPY, tmpIndexName, WithOperationIndexParamsScope([]ScopeType{SCOPE_TYPE_SETTINGS, SCOPE_TYPE_RULES, SCOPE_TYPE_SYNONYMS}))), toRequestOptions(opts)...) if err != nil { return nil, err } - opts = append(opts, utils.WithWaitForTasks(true)) + opts = append(opts, WithWaitForTasks(true)) batchResp, err := c.ChunkedBatch(tmpIndexName, objects, ACTION_ADD_OBJECT, opts...) if err != nil { return nil, err } - _, err = c.WaitForTask(tmpIndexName, copyResp.TaskID, utils.ToIterableOptions(opts)...) + _, err = c.WaitForTask(tmpIndexName, copyResp.TaskID, toIterableOptions(opts)...) if err != nil { return nil, err } - copyResp, err = c.OperationIndex(c.NewApiOperationIndexRequest(indexName, NewOperationIndexParams(OPERATION_TYPE_COPY, tmpIndexName, WithOperationIndexParamsScope([]ScopeType{SCOPE_TYPE_SETTINGS, SCOPE_TYPE_RULES, SCOPE_TYPE_SYNONYMS}))), utils.ToRequestOptions(opts)...) + copyResp, err = c.OperationIndex(c.NewApiOperationIndexRequest(indexName, NewOperationIndexParams(OPERATION_TYPE_COPY, tmpIndexName, WithOperationIndexParamsScope([]ScopeType{SCOPE_TYPE_SETTINGS, SCOPE_TYPE_RULES, SCOPE_TYPE_SYNONYMS}))), toRequestOptions(opts)...) if err != nil { return nil, err } - _, err = c.WaitForTask(tmpIndexName, copyResp.TaskID, utils.ToIterableOptions(opts)...) + _, err = c.WaitForTask(tmpIndexName, copyResp.TaskID, toIterableOptions(opts)...) if err != nil { return nil, err } - moveResp, err := c.OperationIndex(c.NewApiOperationIndexRequest(tmpIndexName, NewOperationIndexParams(OPERATION_TYPE_MOVE, indexName)), utils.ToRequestOptions(opts)...) + moveResp, err := c.OperationIndex(c.NewApiOperationIndexRequest(tmpIndexName, NewOperationIndexParams(OPERATION_TYPE_MOVE, indexName)), toRequestOptions(opts)...) if err != nil { return nil, err } - _, err = c.WaitForTask(tmpIndexName, moveResp.TaskID, utils.ToIterableOptions(opts)...) + _, err = c.WaitForTask(tmpIndexName, moveResp.TaskID, toIterableOptions(opts)...) if err != nil { return nil, err } diff --git a/templates/go/snippets/method.mustache b/templates/go/snippets/method.mustache index a70b5dc835..39f9c94e47 100644 --- a/templates/go/snippets/method.mustache +++ b/templates/go/snippets/method.mustache @@ -27,7 +27,7 @@ func SnippetFor{{#lambda.titlecase}}{{method}}{{/lambda.titlecase}}Of{{#lambda.p {{#hasResponsePayload}}response, err :={{/hasResponsePayload}}{{^hasResponsePayload}}err ={{/hasResponsePayload}} client.{{#lambda.titlecase}}{{method}}{{/lambda.titlecase}}({{#hasOperationParams}}client.NewApi{{#lambda.titlecase}}{{method}}{{/lambda.titlecase}}Request( {{#parametersWithDataType}}{{#required}}{{> tests/generateParams}},{{/required}}{{/parametersWithDataType}} ){{#parametersWithDataType}}{{^required}}.With{{#lambda.pascalcase}}{{{key}}}{{/lambda.pascalcase}}({{> tests/generateParams}}){{/required}}{{/parametersWithDataType}}{{/hasOperationParams}}{{#requestOptions}}{{#hasOperationParams}},{{/hasOperationParams}} - {{#queryParameters.parametersWithDataType}}utils.WithQueryParam("{{{key}}}", {{> tests/generateInnerParams}}),{{/queryParameters.parametersWithDataType}}{{#headers.parametersWithDataType}}utils.WithHeaderParam("{{{key}}}", {{> tests/generateInnerParams}}),{{/headers.parametersWithDataType}} + {{#queryParameters.parametersWithDataType}}{{clientPrefix}}.WithQueryParam("{{{key}}}", {{> tests/generateInnerParams}}),{{/queryParameters.parametersWithDataType}}{{#headers.parametersWithDataType}}{{clientPrefix}}.WithHeaderParam("{{{key}}}", {{> tests/generateInnerParams}}),{{/headers.parametersWithDataType}} {{/requestOptions}}) if err != nil { // handle the eventual error diff --git a/templates/go/tests/client/method.mustache b/templates/go/tests/client/method.mustache index 4e81cd95cf..b2ea520d35 100644 --- a/templates/go/tests/client/method.mustache +++ b/templates/go/tests/client/method.mustache @@ -1,5 +1,5 @@ {{^useEchoRequester}}res, err := {{/useEchoRequester}}{{#useEchoRequester}}_, err = {{/useEchoRequester}}client.{{#lambda.titlecase}}{{path}}{{/lambda.titlecase}}({{^isHelper}}client.NewApi{{#lambda.titlecase}}{{path}}{{/lambda.titlecase}}Request({{/isHelper}} {{#parametersWithDataType}}{{#required}}{{> tests/generateParams}},{{/required}}{{/parametersWithDataType}} {{^isHelper}}){{#parametersWithDataType}}{{^required}}.With{{#lambda.pascalcase}}{{{key}}}{{/lambda.pascalcase}}({{> tests/generateParams}}){{/required}}{{/parametersWithDataType}}{{/isHelper}}{{#isHelper}}{{#parametersWithDataType}}{{^required}}{{> tests/generateParams}},{{/required}}{{/parametersWithDataType}}{{/isHelper}}{{#requestOptions}}{{#hasOperationParams}},{{/hasOperationParams}} - {{#queryParameters.parametersWithDataType}}utils.WithQueryParam("{{{key}}}", {{> tests/generateInnerParams}}),{{/queryParameters.parametersWithDataType}}{{#headers.parametersWithDataType}}utils.WithHeaderParam("{{{key}}}", {{> tests/generateInnerParams}}),{{/headers.parametersWithDataType}} + {{#queryParameters.parametersWithDataType}}{{clientPrefix}}.WithQueryParam("{{{key}}}", {{> tests/generateInnerParams}}),{{/queryParameters.parametersWithDataType}}{{#headers.parametersWithDataType}}{{clientPrefix}}.WithHeaderParam("{{{key}}}", {{> tests/generateInnerParams}}),{{/headers.parametersWithDataType}} {{/requestOptions}}) \ No newline at end of file diff --git a/templates/go/tests/e2e/e2e.mustache b/templates/go/tests/e2e/e2e.mustache index 33675c298f..1bf1410d87 100644 --- a/templates/go/tests/e2e/e2e.mustache +++ b/templates/go/tests/e2e/e2e.mustache @@ -36,7 +36,7 @@ func Test{{#lambda.titlecase}}{{clientPrefix}}{{/lambda.titlecase}}E2E_{{#lambda res, err := client.{{#lambda.titlecase}}{{method}}{{/lambda.titlecase}}({{#hasOperationParams}}client.NewApi{{#lambda.titlecase}}{{method}}{{/lambda.titlecase}}Request( {{#parametersWithDataType}}{{#required}}{{> tests/generateParams}},{{/required}}{{/parametersWithDataType}} ){{#parametersWithDataType}}{{^required}}.With{{#lambda.pascalcase}}{{{key}}}{{/lambda.pascalcase}}({{> tests/generateParams}}){{/required}}{{/parametersWithDataType}}{{/hasOperationParams}}{{#requestOptions}}{{#hasOperationParams}},{{/hasOperationParams}} - {{#queryParameters.parametersWithDataType}}utils.WithQueryParam("{{{key}}}", {{> tests/generateInnerParams}}),{{/queryParameters.parametersWithDataType}}{{#headers.parametersWithDataType}}utils.WithHeaderParam("{{{key}}}", {{> tests/generateInnerParams}}),{{/headers.parametersWithDataType}} + {{#queryParameters.parametersWithDataType}}{{clientPrefix}}.WithQueryParam("{{{key}}}", {{> tests/generateInnerParams}}),{{/queryParameters.parametersWithDataType}}{{#headers.parametersWithDataType}}{{clientPrefix}}.WithHeaderParam("{{{key}}}", {{> tests/generateInnerParams}}),{{/headers.parametersWithDataType}} {{/requestOptions}}) require.NoError(t, err) _ = res diff --git a/templates/go/tests/generateInnerParams.mustache b/templates/go/tests/generateInnerParams.mustache index 7c1530407c..7431a4206e 100644 --- a/templates/go/tests/generateInnerParams.mustache +++ b/templates/go/tests/generateInnerParams.mustache @@ -1,3 +1,3 @@ -{{#isNull}}{{#inClientTest}}tests.ZeroValue[{{#isNullObject}}*{{clientPrefix}}.{{/isNullObject}}{{objectName}}](){{/inClientTest}}{{^inClientTest}}nil{{/inClientTest}}{{/isNull}}{{#isString}}"{{{value}}}"{{/isString}}{{#isInteger}}{{#isHelper}}{{^required}}{{^useAnonymousKey}}utils.With{{#lambda.pascalcase}}{{key}}{{/lambda.pascalcase}}({{/useAnonymousKey}}{{/required}}{{/isHelper}}{{{value}}}{{#isHelper}}{{^required}}{{^useAnonymousKey}}){{/useAnonymousKey}}{{/required}}{{/isHelper}}{{/isInteger}}{{#isLong}}{{{value}}}{{/isLong}}{{#isDouble}}{{{value}}}{{/isDouble}}{{#isBoolean}}{{{value}}}{{/isBoolean}}{{#isEnum}}{{clientPrefix}}.{{objectName}}("{{{value}}}"){{/isEnum}}{{#isArray}} +{{#isHelper}}{{#goFunctionalParam}}{{clientPrefix}}.With{{#lambda.pascalcase}}{{key}}{{/lambda.pascalcase}}({{/goFunctionalParam}}{{/isHelper}}{{#isNull}}{{#inClientTest}}tests.ZeroValue[{{#isNullObject}}*{{clientPrefix}}.{{/isNullObject}}{{objectName}}](){{/inClientTest}}{{^inClientTest}}nil{{/inClientTest}}{{/isNull}}{{#isString}}"{{{value}}}"{{/isString}}{{#isInteger}}{{{value}}}{{/isInteger}}{{#isLong}}{{{value}}}{{/isLong}}{{#isDouble}}{{{value}}}{{/isDouble}}{{#isBoolean}}{{{value}}}{{/isBoolean}}{{#isEnum}}{{clientPrefix}}.{{objectName}}("{{{value}}}"){{/isEnum}}{{#isArray}} {{> tests/arrayType}}{{^value.isEmpty}}{ {{#value}}{{#isObject}}*{{/isObject}}{{#oneOfModel}}{{^isObject}}*{{/isObject}}{{/oneOfModel}}{{> tests/generateParams}},{{/value}} }{{/value.isEmpty}}{{/isArray}}{{#isObject}} -{{clientPrefix}}.NewEmpty{{objectName}}(){{#value}}{{#isAdditionalProperty}}.SetAdditionalProperty("{{{key}}}", {{> tests/generateParams}}){{/isAdditionalProperty}}{{^isAdditionalProperty}}.Set{{#lambda.pascalcase}}{{{key}}}{{/lambda.pascalcase}}({{> tests/generateParams}}){{/isAdditionalProperty}}{{/value}}{{/isObject}}{{#isFreeFormObject}}{{#isAnyType}}map[string]any{ {{#value}}{{#entrySet}}"{{{key}}}": "{{{value}}}",{{/entrySet}}{{/value}} }{{/isAnyType}}{{^isAnyType}}{{> tests/mapType}}{ {{#value}}"{{{key}}}": {{#oneOfModel}}{{^isObject}}*{{/isObject}}{{/oneOfModel}}{{#isObject}}*{{/isObject}}{{> tests/generateParams}},{{/value}} }{{/isAnyType}}{{/isFreeFormObject}} \ No newline at end of file +{{clientPrefix}}.NewEmpty{{objectName}}(){{#value}}{{#isAdditionalProperty}}.SetAdditionalProperty("{{{key}}}", {{> tests/generateParams}}){{/isAdditionalProperty}}{{^isAdditionalProperty}}.Set{{#lambda.pascalcase}}{{{key}}}{{/lambda.pascalcase}}({{> tests/generateParams}}){{/isAdditionalProperty}}{{/value}}{{/isObject}}{{#isFreeFormObject}}{{#isAnyType}}map[string]any{ {{#value}}{{#entrySet}}"{{{key}}}": "{{{value}}}",{{/entrySet}}{{/value}} }{{/isAnyType}}{{^isAnyType}}{{> tests/mapType}}{ {{#value}}"{{{key}}}": {{#oneOfModel}}{{^isObject}}*{{/isObject}}{{/oneOfModel}}{{#isObject}}*{{/isObject}}{{> tests/generateParams}},{{/value}} }{{/isAnyType}}{{/isFreeFormObject}}{{#isHelper}}{{#goFunctionalParam}}){{/goFunctionalParam}}{{/isHelper}} \ No newline at end of file diff --git a/templates/go/tests/requests/requests.mustache b/templates/go/tests/requests/requests.mustache index 9138acf5e9..a1cb71b819 100644 --- a/templates/go/tests/requests/requests.mustache +++ b/templates/go/tests/requests/requests.mustache @@ -43,7 +43,7 @@ func Test{{#lambda.titlecase}}{{clientPrefix}}{{/lambda.titlecase}}_{{#lambda.ti {{#hasResponsePayload}}_, {{/hasResponsePayload}}err := client.{{#lambda.titlecase}}{{method}}{{/lambda.titlecase}}({{#hasOperationParams}}client.NewApi{{#lambda.titlecase}}{{method}}{{/lambda.titlecase}}Request( {{#parametersWithDataType}}{{#required}}{{> tests/generateParams}},{{/required}}{{/parametersWithDataType}} ){{#parametersWithDataType}}{{^required}}.With{{#lambda.pascalcase}}{{{key}}}{{/lambda.pascalcase}}({{> tests/generateParams}}){{/required}}{{/parametersWithDataType}}{{/hasOperationParams}}{{#requestOptions}}{{#hasOperationParams}},{{/hasOperationParams}} - {{#queryParameters.parametersWithDataType}}utils.WithQueryParam("{{{key}}}", {{> tests/generateInnerParams}}),{{/queryParameters.parametersWithDataType}}{{#headers.parametersWithDataType}}utils.WithHeaderParam("{{{key}}}", {{> tests/generateInnerParams}}),{{/headers.parametersWithDataType}} + {{#queryParameters.parametersWithDataType}}{{clientPrefix}}.WithQueryParam("{{{key}}}", {{> tests/generateInnerParams}}),{{/queryParameters.parametersWithDataType}}{{#headers.parametersWithDataType}}{{clientPrefix}}.WithHeaderParam("{{{key}}}", {{> tests/generateInnerParams}}),{{/headers.parametersWithDataType}} {{/requestOptions}}) require.NoError(t, err) From 14f42e35e5426891c1321d24b649e6c049518f1d Mon Sep 17 00:00:00 2001 From: algolia-bot Date: Thu, 18 Jul 2024 07:50:54 +0000 Subject: [PATCH 2/4] chore: generated code for commit 7d2b420026c4e4c0a2956793bf0d0e9f74b106fc. [skip ci] Co-authored-by: Pierre Millot --- .../algolia/abtesting/api_abtesting.go | 213 ++- .../algolia/analytics/api_analytics.go | 681 +++---- .../algolia/ingestion/api_ingestion.go | 943 ++++----- .../algolia/insights/api_insights.go | 151 +- .../algolia/monitoring/api_monitoring.go | 277 +-- .../personalization/api_personalization.go | 187 +- .../api_query_suggestions.go | 241 ++- .../algolia/recommend/api_recommend.go | 205 +- .../algolia/search/api_search.go | 1694 ++++++++++------- .../algolia/usage/api_usage.go | 163 +- tests/output/go/tests/client/search_test.go | 7 +- .../go/tests/requests/abtesting_test.go | 23 +- .../go/tests/requests/analytics_test.go | 23 +- .../go/tests/requests/ingestion_test.go | 23 +- .../output/go/tests/requests/insights_test.go | 23 +- .../go/tests/requests/monitoring_test.go | 23 +- .../go/tests/requests/personalization_test.go | 23 +- .../tests/requests/query-suggestions_test.go | 23 +- .../go/tests/requests/recommend_test.go | 23 +- tests/output/go/tests/requests/search_test.go | 23 +- tests/output/go/tests/requests/usage_test.go | 23 +- 21 files changed, 2805 insertions(+), 2187 deletions(-) diff --git a/clients/algoliasearch-client-go/algolia/abtesting/api_abtesting.go b/clients/algoliasearch-client-go/algolia/abtesting/api_abtesting.go index 139854fb61..750c6c0552 100644 --- a/clients/algoliasearch-client-go/algolia/abtesting/api_abtesting.go +++ b/clients/algoliasearch-client-go/algolia/abtesting/api_abtesting.go @@ -12,6 +12,41 @@ import ( "github.com/algolia/algoliasearch-client-go/v4/algolia/utils" ) +type config struct { + // -- Request options for API calls + context context.Context + queryParams url.Values + headerParams map[string]string +} + +type RequestOption interface { + apply(*config) +} + +type requestOption func(*config) + +func (r requestOption) apply(c *config) { + r(c) +} + +func WithContext(ctx context.Context) requestOption { + return requestOption(func(c *config) { + c.context = ctx + }) +} + +func WithHeaderParam(key string, value any) requestOption { + return requestOption(func(c *config) { + c.headerParams[key] = utils.ParameterToString(value) + }) +} + +func WithQueryParam(key string, value any) requestOption { + return requestOption(func(c *config) { + c.queryParams.Set(utils.QueryParameterToString(key), utils.QueryParameterToString(value)) + }) +} + func (r *ApiAddABTestsRequest) UnmarshalJSON(b []byte) error { req := map[string]json.RawMessage{} err := json.Unmarshal(b, &req) @@ -58,34 +93,34 @@ AddABTests calls the API and returns the raw response from it. Request can be constructed by NewApiAddABTestsRequest with parameters below. @param addABTestsRequest AddABTestsRequest - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) AddABTestsWithHTTPInfo(r ApiAddABTestsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) AddABTestsWithHTTPInfo(r ApiAddABTestsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/2/abtests" if r.addABTestsRequest == nil { return nil, nil, reportError("Parameter `addABTestsRequest` is required when calling `AddABTests`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.addABTestsRequest - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -106,7 +141,7 @@ Request can be constructed by NewApiAddABTestsRequest with parameters below. @param addABTestsRequest AddABTestsRequest @return ABTestResponse */ -func (c *APIClient) AddABTests(r ApiAddABTestsRequest, opts ...utils.RequestOption) (*ABTestResponse, error) { +func (c *APIClient) AddABTests(r ApiAddABTestsRequest, opts ...RequestOption) (*ABTestResponse, error) { var returnValue *ABTestResponse res, resBody, err := c.AddABTestsWithHTTPInfo(r, opts...) @@ -197,12 +232,12 @@ CustomDelete calls the API and returns the raw response from it. Request can be constructed by NewApiCustomDeleteRequest with parameters below. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomDeleteWithHTTPInfo(r ApiCustomDeleteRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomDeleteWithHTTPInfo(r ApiCustomDeleteRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -210,26 +245,26 @@ func (c *APIClient) CustomDeleteWithHTTPInfo(r ApiCustomDeleteRequest, opts ...u return nil, nil, reportError("Parameter `path` is required when calling `CustomDelete`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodDelete, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodDelete, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -248,7 +283,7 @@ Request can be constructed by NewApiCustomDeleteRequest with parameters below. @param parameters map[string]any - Query parameters to apply to the current query. @return map[string]any */ -func (c *APIClient) CustomDelete(r ApiCustomDeleteRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomDelete(r ApiCustomDeleteRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomDeleteWithHTTPInfo(r, opts...) @@ -339,12 +374,12 @@ CustomGet calls the API and returns the raw response from it. Request can be constructed by NewApiCustomGetRequest with parameters below. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomGetWithHTTPInfo(r ApiCustomGetRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomGetWithHTTPInfo(r ApiCustomGetRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -352,26 +387,26 @@ func (c *APIClient) CustomGetWithHTTPInfo(r ApiCustomGetRequest, opts ...utils.R return nil, nil, reportError("Parameter `path` is required when calling `CustomGet`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -390,7 +425,7 @@ Request can be constructed by NewApiCustomGetRequest with parameters below. @param parameters map[string]any - Query parameters to apply to the current query. @return map[string]any */ -func (c *APIClient) CustomGet(r ApiCustomGetRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomGet(r ApiCustomGetRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomGetWithHTTPInfo(r, opts...) @@ -498,12 +533,12 @@ CustomPost calls the API and returns the raw response from it. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. @param body map[string]any - Parameters to send with the custom request. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -511,21 +546,21 @@ func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...utils return nil, nil, reportError("Parameter `path` is required when calling `CustomPost`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any @@ -536,7 +571,7 @@ func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...utils } else { postBody = r.body } - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -556,7 +591,7 @@ Request can be constructed by NewApiCustomPostRequest with parameters below. @param body map[string]any - Parameters to send with the custom request. @return map[string]any */ -func (c *APIClient) CustomPost(r ApiCustomPostRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomPost(r ApiCustomPostRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomPostWithHTTPInfo(r, opts...) @@ -664,12 +699,12 @@ CustomPut calls the API and returns the raw response from it. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. @param body map[string]any - Parameters to send with the custom request. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -677,21 +712,21 @@ func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...utils.R return nil, nil, reportError("Parameter `path` is required when calling `CustomPut`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any @@ -702,7 +737,7 @@ func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...utils.R } else { postBody = r.body } - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPut, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPut, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -722,7 +757,7 @@ Request can be constructed by NewApiCustomPutRequest with parameters below. @param body map[string]any - Parameters to send with the custom request. @return map[string]any */ -func (c *APIClient) CustomPut(r ApiCustomPutRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomPut(r ApiCustomPutRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomPutWithHTTPInfo(r, opts...) @@ -798,29 +833,29 @@ DeleteABTest calls the API and returns the raw response from it. Request can be constructed by NewApiDeleteABTestRequest with parameters below. @param id int32 - Unique A/B test identifier. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) DeleteABTestWithHTTPInfo(r ApiDeleteABTestRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) DeleteABTestWithHTTPInfo(r ApiDeleteABTestRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/2/abtests/{id}" requestPath = strings.ReplaceAll(requestPath, "{id}", url.PathEscape(utils.ParameterToString(r.id))) - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodDelete, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodDelete, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -841,7 +876,7 @@ Request can be constructed by NewApiDeleteABTestRequest with parameters below. @param id int32 - Unique A/B test identifier. @return ABTestResponse */ -func (c *APIClient) DeleteABTest(r ApiDeleteABTestRequest, opts ...utils.RequestOption) (*ABTestResponse, error) { +func (c *APIClient) DeleteABTest(r ApiDeleteABTestRequest, opts ...RequestOption) (*ABTestResponse, error) { var returnValue *ABTestResponse res, resBody, err := c.DeleteABTestWithHTTPInfo(r, opts...) @@ -917,29 +952,29 @@ GetABTest calls the API and returns the raw response from it. Request can be constructed by NewApiGetABTestRequest with parameters below. @param id int32 - Unique A/B test identifier. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetABTestWithHTTPInfo(r ApiGetABTestRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetABTestWithHTTPInfo(r ApiGetABTestRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/2/abtests/{id}" requestPath = strings.ReplaceAll(requestPath, "{id}", url.PathEscape(utils.ParameterToString(r.id))) - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -960,7 +995,7 @@ Request can be constructed by NewApiGetABTestRequest with parameters below. @param id int32 - Unique A/B test identifier. @return ABTest */ -func (c *APIClient) GetABTest(r ApiGetABTestRequest, opts ...utils.RequestOption) (*ABTest, error) { +func (c *APIClient) GetABTest(r ApiGetABTestRequest, opts ...RequestOption) (*ABTest, error) { var returnValue *ABTest res, resBody, err := c.GetABTestWithHTTPInfo(r, opts...) @@ -1091,41 +1126,41 @@ ListABTests calls the API and returns the raw response from it. @param limit int32 - Number of items to return. @param indexPrefix string - Index name prefix. Only A/B tests for indices starting with this string are included in the response. @param indexSuffix string - Index name suffix. Only A/B tests for indices ending with this string are included in the response. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) ListABTestsWithHTTPInfo(r ApiListABTestsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) ListABTestsWithHTTPInfo(r ApiListABTestsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/2/abtests" - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.offset) { - options.QueryParams.Set("offset", utils.QueryParameterToString(*r.offset)) + conf.queryParams.Set("offset", utils.QueryParameterToString(*r.offset)) } if !utils.IsNilOrEmpty(r.limit) { - options.QueryParams.Set("limit", utils.QueryParameterToString(*r.limit)) + conf.queryParams.Set("limit", utils.QueryParameterToString(*r.limit)) } if !utils.IsNilOrEmpty(r.indexPrefix) { - options.QueryParams.Set("indexPrefix", utils.QueryParameterToString(*r.indexPrefix)) + conf.queryParams.Set("indexPrefix", utils.QueryParameterToString(*r.indexPrefix)) } if !utils.IsNilOrEmpty(r.indexSuffix) { - options.QueryParams.Set("indexSuffix", utils.QueryParameterToString(*r.indexSuffix)) + conf.queryParams.Set("indexSuffix", utils.QueryParameterToString(*r.indexSuffix)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1149,7 +1184,7 @@ Request can be constructed by NewApiListABTestsRequest with parameters below. @param indexSuffix string - Index name suffix. Only A/B tests for indices ending with this string are included in the response. @return ListABTestsResponse */ -func (c *APIClient) ListABTests(r ApiListABTestsRequest, opts ...utils.RequestOption) (*ListABTestsResponse, error) { +func (c *APIClient) ListABTests(r ApiListABTestsRequest, opts ...RequestOption) (*ListABTestsResponse, error) { var returnValue *ListABTestsResponse res, resBody, err := c.ListABTestsWithHTTPInfo(r, opts...) @@ -1227,29 +1262,29 @@ You can't restart stopped A/B tests. Request can be constructed by NewApiStopABTestRequest with parameters below. @param id int32 - Unique A/B test identifier. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) StopABTestWithHTTPInfo(r ApiStopABTestRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) StopABTestWithHTTPInfo(r ApiStopABTestRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/2/abtests/{id}/stop" requestPath = strings.ReplaceAll(requestPath, "{id}", url.PathEscape(utils.ParameterToString(r.id))) - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1272,7 +1307,7 @@ Request can be constructed by NewApiStopABTestRequest with parameters below. @param id int32 - Unique A/B test identifier. @return ABTestResponse */ -func (c *APIClient) StopABTest(r ApiStopABTestRequest, opts ...utils.RequestOption) (*ABTestResponse, error) { +func (c *APIClient) StopABTest(r ApiStopABTestRequest, opts ...RequestOption) (*ABTestResponse, error) { var returnValue *ABTestResponse res, resBody, err := c.StopABTestWithHTTPInfo(r, opts...) diff --git a/clients/algoliasearch-client-go/algolia/analytics/api_analytics.go b/clients/algoliasearch-client-go/algolia/analytics/api_analytics.go index d60f87522a..0846711f93 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/api_analytics.go +++ b/clients/algoliasearch-client-go/algolia/analytics/api_analytics.go @@ -12,6 +12,41 @@ import ( "github.com/algolia/algoliasearch-client-go/v4/algolia/utils" ) +type config struct { + // -- Request options for API calls + context context.Context + queryParams url.Values + headerParams map[string]string +} + +type RequestOption interface { + apply(*config) +} + +type requestOption func(*config) + +func (r requestOption) apply(c *config) { + r(c) +} + +func WithContext(ctx context.Context) requestOption { + return requestOption(func(c *config) { + c.context = ctx + }) +} + +func WithHeaderParam(key string, value any) requestOption { + return requestOption(func(c *config) { + c.headerParams[key] = utils.ParameterToString(value) + }) +} + +func WithQueryParam(key string, value any) requestOption { + return requestOption(func(c *config) { + c.queryParams.Set(utils.QueryParameterToString(key), utils.QueryParameterToString(value)) + }) +} + func (r *ApiCustomDeleteRequest) UnmarshalJSON(b []byte) error { req := map[string]json.RawMessage{} err := json.Unmarshal(b, &req) @@ -68,12 +103,12 @@ CustomDelete calls the API and returns the raw response from it. Request can be constructed by NewApiCustomDeleteRequest with parameters below. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomDeleteWithHTTPInfo(r ApiCustomDeleteRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomDeleteWithHTTPInfo(r ApiCustomDeleteRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -81,26 +116,26 @@ func (c *APIClient) CustomDeleteWithHTTPInfo(r ApiCustomDeleteRequest, opts ...u return nil, nil, reportError("Parameter `path` is required when calling `CustomDelete`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodDelete, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodDelete, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -119,7 +154,7 @@ Request can be constructed by NewApiCustomDeleteRequest with parameters below. @param parameters map[string]any - Query parameters to apply to the current query. @return map[string]any */ -func (c *APIClient) CustomDelete(r ApiCustomDeleteRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomDelete(r ApiCustomDeleteRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomDeleteWithHTTPInfo(r, opts...) @@ -210,12 +245,12 @@ CustomGet calls the API and returns the raw response from it. Request can be constructed by NewApiCustomGetRequest with parameters below. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomGetWithHTTPInfo(r ApiCustomGetRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomGetWithHTTPInfo(r ApiCustomGetRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -223,26 +258,26 @@ func (c *APIClient) CustomGetWithHTTPInfo(r ApiCustomGetRequest, opts ...utils.R return nil, nil, reportError("Parameter `path` is required when calling `CustomGet`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -261,7 +296,7 @@ Request can be constructed by NewApiCustomGetRequest with parameters below. @param parameters map[string]any - Query parameters to apply to the current query. @return map[string]any */ -func (c *APIClient) CustomGet(r ApiCustomGetRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomGet(r ApiCustomGetRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomGetWithHTTPInfo(r, opts...) @@ -369,12 +404,12 @@ CustomPost calls the API and returns the raw response from it. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. @param body map[string]any - Parameters to send with the custom request. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -382,21 +417,21 @@ func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...utils return nil, nil, reportError("Parameter `path` is required when calling `CustomPost`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any @@ -407,7 +442,7 @@ func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...utils } else { postBody = r.body } - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -427,7 +462,7 @@ Request can be constructed by NewApiCustomPostRequest with parameters below. @param body map[string]any - Parameters to send with the custom request. @return map[string]any */ -func (c *APIClient) CustomPost(r ApiCustomPostRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomPost(r ApiCustomPostRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomPostWithHTTPInfo(r, opts...) @@ -535,12 +570,12 @@ CustomPut calls the API and returns the raw response from it. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. @param body map[string]any - Parameters to send with the custom request. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -548,21 +583,21 @@ func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...utils.R return nil, nil, reportError("Parameter `path` is required when calling `CustomPut`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any @@ -573,7 +608,7 @@ func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...utils.R } else { postBody = r.body } - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPut, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPut, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -593,7 +628,7 @@ Request can be constructed by NewApiCustomPutRequest with parameters below. @param body map[string]any - Parameters to send with the custom request. @return map[string]any */ -func (c *APIClient) CustomPut(r ApiCustomPutRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomPut(r ApiCustomPutRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomPutWithHTTPInfo(r, opts...) @@ -722,43 +757,43 @@ By default, the analyzed period includes the last eight days including the curre @param startDate string - Start date of the period to analyze, in `YYYY-MM-DD` format. @param endDate string - End date of the period to analyze, in `YYYY-MM-DD` format. @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetAddToCartRateWithHTTPInfo(r ApiGetAddToCartRateRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetAddToCartRateWithHTTPInfo(r ApiGetAddToCartRateRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/2/conversions/addToCartRate" if r.index == "" { return nil, nil, reportError("Parameter `index` is required when calling `GetAddToCartRate`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } - options.QueryParams.Set("index", utils.QueryParameterToString(r.index)) + conf.queryParams.Set("index", utils.QueryParameterToString(r.index)) if !utils.IsNilOrEmpty(r.startDate) { - options.QueryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) + conf.queryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) } if !utils.IsNilOrEmpty(r.endDate) { - options.QueryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) + conf.queryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) } if !utils.IsNilOrEmpty(r.tags) { - options.QueryParams.Set("tags", utils.QueryParameterToString(*r.tags)) + conf.queryParams.Set("tags", utils.QueryParameterToString(*r.tags)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -784,7 +819,7 @@ Request can be constructed by NewApiGetAddToCartRateRequest with parameters belo @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). @return GetAddToCartRateResponse */ -func (c *APIClient) GetAddToCartRate(r ApiGetAddToCartRateRequest, opts ...utils.RequestOption) (*GetAddToCartRateResponse, error) { +func (c *APIClient) GetAddToCartRate(r ApiGetAddToCartRateRequest, opts ...RequestOption) (*GetAddToCartRateResponse, error) { var returnValue *GetAddToCartRateResponse res, resBody, err := c.GetAddToCartRateWithHTTPInfo(r, opts...) @@ -915,43 +950,43 @@ By default, the analyzed period includes the last eight days including the curre @param startDate string - Start date of the period to analyze, in `YYYY-MM-DD` format. @param endDate string - End date of the period to analyze, in `YYYY-MM-DD` format. @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetAverageClickPositionWithHTTPInfo(r ApiGetAverageClickPositionRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetAverageClickPositionWithHTTPInfo(r ApiGetAverageClickPositionRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/2/clicks/averageClickPosition" if r.index == "" { return nil, nil, reportError("Parameter `index` is required when calling `GetAverageClickPosition`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } - options.QueryParams.Set("index", utils.QueryParameterToString(r.index)) + conf.queryParams.Set("index", utils.QueryParameterToString(r.index)) if !utils.IsNilOrEmpty(r.startDate) { - options.QueryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) + conf.queryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) } if !utils.IsNilOrEmpty(r.endDate) { - options.QueryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) + conf.queryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) } if !utils.IsNilOrEmpty(r.tags) { - options.QueryParams.Set("tags", utils.QueryParameterToString(*r.tags)) + conf.queryParams.Set("tags", utils.QueryParameterToString(*r.tags)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -979,7 +1014,7 @@ Request can be constructed by NewApiGetAverageClickPositionRequest with paramete @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). @return GetAverageClickPositionResponse */ -func (c *APIClient) GetAverageClickPosition(r ApiGetAverageClickPositionRequest, opts ...utils.RequestOption) (*GetAverageClickPositionResponse, error) { +func (c *APIClient) GetAverageClickPosition(r ApiGetAverageClickPositionRequest, opts ...RequestOption) (*GetAverageClickPositionResponse, error) { var returnValue *GetAverageClickPositionResponse res, resBody, err := c.GetAverageClickPositionWithHTTPInfo(r, opts...) @@ -1108,43 +1143,43 @@ This lets you check how many clicks the first, second, or tenth search results r @param startDate string - Start date of the period to analyze, in `YYYY-MM-DD` format. @param endDate string - End date of the period to analyze, in `YYYY-MM-DD` format. @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetClickPositionsWithHTTPInfo(r ApiGetClickPositionsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetClickPositionsWithHTTPInfo(r ApiGetClickPositionsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/2/clicks/positions" if r.index == "" { return nil, nil, reportError("Parameter `index` is required when calling `GetClickPositions`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } - options.QueryParams.Set("index", utils.QueryParameterToString(r.index)) + conf.queryParams.Set("index", utils.QueryParameterToString(r.index)) if !utils.IsNilOrEmpty(r.startDate) { - options.QueryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) + conf.queryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) } if !utils.IsNilOrEmpty(r.endDate) { - options.QueryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) + conf.queryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) } if !utils.IsNilOrEmpty(r.tags) { - options.QueryParams.Set("tags", utils.QueryParameterToString(*r.tags)) + conf.queryParams.Set("tags", utils.QueryParameterToString(*r.tags)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1170,7 +1205,7 @@ Request can be constructed by NewApiGetClickPositionsRequest with parameters bel @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). @return GetClickPositionsResponse */ -func (c *APIClient) GetClickPositions(r ApiGetClickPositionsRequest, opts ...utils.RequestOption) (*GetClickPositionsResponse, error) { +func (c *APIClient) GetClickPositions(r ApiGetClickPositionsRequest, opts ...RequestOption) (*GetClickPositionsResponse, error) { var returnValue *GetClickPositionsResponse res, resBody, err := c.GetClickPositionsWithHTTPInfo(r, opts...) @@ -1299,43 +1334,43 @@ By default, the analyzed period includes the last eight days including the curre @param startDate string - Start date of the period to analyze, in `YYYY-MM-DD` format. @param endDate string - End date of the period to analyze, in `YYYY-MM-DD` format. @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetClickThroughRateWithHTTPInfo(r ApiGetClickThroughRateRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetClickThroughRateWithHTTPInfo(r ApiGetClickThroughRateRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/2/clicks/clickThroughRate" if r.index == "" { return nil, nil, reportError("Parameter `index` is required when calling `GetClickThroughRate`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } - options.QueryParams.Set("index", utils.QueryParameterToString(r.index)) + conf.queryParams.Set("index", utils.QueryParameterToString(r.index)) if !utils.IsNilOrEmpty(r.startDate) { - options.QueryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) + conf.queryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) } if !utils.IsNilOrEmpty(r.endDate) { - options.QueryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) + conf.queryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) } if !utils.IsNilOrEmpty(r.tags) { - options.QueryParams.Set("tags", utils.QueryParameterToString(*r.tags)) + conf.queryParams.Set("tags", utils.QueryParameterToString(*r.tags)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1361,7 +1396,7 @@ Request can be constructed by NewApiGetClickThroughRateRequest with parameters b @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). @return GetClickThroughRateResponse */ -func (c *APIClient) GetClickThroughRate(r ApiGetClickThroughRateRequest, opts ...utils.RequestOption) (*GetClickThroughRateResponse, error) { +func (c *APIClient) GetClickThroughRate(r ApiGetClickThroughRateRequest, opts ...RequestOption) (*GetClickThroughRateResponse, error) { var returnValue *GetClickThroughRateResponse res, resBody, err := c.GetClickThroughRateWithHTTPInfo(r, opts...) @@ -1490,43 +1525,43 @@ By default, the analyzed period includes the last eight days including the curre @param startDate string - Start date of the period to analyze, in `YYYY-MM-DD` format. @param endDate string - End date of the period to analyze, in `YYYY-MM-DD` format. @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetConversionRateWithHTTPInfo(r ApiGetConversionRateRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetConversionRateWithHTTPInfo(r ApiGetConversionRateRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/2/conversions/conversionRate" if r.index == "" { return nil, nil, reportError("Parameter `index` is required when calling `GetConversionRate`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } - options.QueryParams.Set("index", utils.QueryParameterToString(r.index)) + conf.queryParams.Set("index", utils.QueryParameterToString(r.index)) if !utils.IsNilOrEmpty(r.startDate) { - options.QueryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) + conf.queryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) } if !utils.IsNilOrEmpty(r.endDate) { - options.QueryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) + conf.queryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) } if !utils.IsNilOrEmpty(r.tags) { - options.QueryParams.Set("tags", utils.QueryParameterToString(*r.tags)) + conf.queryParams.Set("tags", utils.QueryParameterToString(*r.tags)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1552,7 +1587,7 @@ Request can be constructed by NewApiGetConversionRateRequest with parameters bel @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). @return GetConversionRateResponse */ -func (c *APIClient) GetConversionRate(r ApiGetConversionRateRequest, opts ...utils.RequestOption) (*GetConversionRateResponse, error) { +func (c *APIClient) GetConversionRate(r ApiGetConversionRateRequest, opts ...RequestOption) (*GetConversionRateResponse, error) { var returnValue *GetConversionRateResponse res, resBody, err := c.GetConversionRateWithHTTPInfo(r, opts...) @@ -1681,43 +1716,43 @@ By default, the analyzed period includes the last eight days including the curre @param startDate string - Start date of the period to analyze, in `YYYY-MM-DD` format. @param endDate string - End date of the period to analyze, in `YYYY-MM-DD` format. @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetNoClickRateWithHTTPInfo(r ApiGetNoClickRateRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetNoClickRateWithHTTPInfo(r ApiGetNoClickRateRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/2/searches/noClickRate" if r.index == "" { return nil, nil, reportError("Parameter `index` is required when calling `GetNoClickRate`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } - options.QueryParams.Set("index", utils.QueryParameterToString(r.index)) + conf.queryParams.Set("index", utils.QueryParameterToString(r.index)) if !utils.IsNilOrEmpty(r.startDate) { - options.QueryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) + conf.queryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) } if !utils.IsNilOrEmpty(r.endDate) { - options.QueryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) + conf.queryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) } if !utils.IsNilOrEmpty(r.tags) { - options.QueryParams.Set("tags", utils.QueryParameterToString(*r.tags)) + conf.queryParams.Set("tags", utils.QueryParameterToString(*r.tags)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1743,7 +1778,7 @@ Request can be constructed by NewApiGetNoClickRateRequest with parameters below. @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). @return GetNoClickRateResponse */ -func (c *APIClient) GetNoClickRate(r ApiGetNoClickRateRequest, opts ...utils.RequestOption) (*GetNoClickRateResponse, error) { +func (c *APIClient) GetNoClickRate(r ApiGetNoClickRateRequest, opts ...RequestOption) (*GetNoClickRateResponse, error) { var returnValue *GetNoClickRateResponse res, resBody, err := c.GetNoClickRateWithHTTPInfo(r, opts...) @@ -1872,43 +1907,43 @@ By default, the analyzed period includes the last eight days including the curre @param startDate string - Start date of the period to analyze, in `YYYY-MM-DD` format. @param endDate string - End date of the period to analyze, in `YYYY-MM-DD` format. @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetNoResultsRateWithHTTPInfo(r ApiGetNoResultsRateRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetNoResultsRateWithHTTPInfo(r ApiGetNoResultsRateRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/2/searches/noResultRate" if r.index == "" { return nil, nil, reportError("Parameter `index` is required when calling `GetNoResultsRate`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } - options.QueryParams.Set("index", utils.QueryParameterToString(r.index)) + conf.queryParams.Set("index", utils.QueryParameterToString(r.index)) if !utils.IsNilOrEmpty(r.startDate) { - options.QueryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) + conf.queryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) } if !utils.IsNilOrEmpty(r.endDate) { - options.QueryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) + conf.queryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) } if !utils.IsNilOrEmpty(r.tags) { - options.QueryParams.Set("tags", utils.QueryParameterToString(*r.tags)) + conf.queryParams.Set("tags", utils.QueryParameterToString(*r.tags)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1934,7 +1969,7 @@ Request can be constructed by NewApiGetNoResultsRateRequest with parameters belo @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). @return GetNoResultsRateResponse */ -func (c *APIClient) GetNoResultsRate(r ApiGetNoResultsRateRequest, opts ...utils.RequestOption) (*GetNoResultsRateResponse, error) { +func (c *APIClient) GetNoResultsRate(r ApiGetNoResultsRateRequest, opts ...RequestOption) (*GetNoResultsRateResponse, error) { var returnValue *GetNoResultsRateResponse res, resBody, err := c.GetNoResultsRateWithHTTPInfo(r, opts...) @@ -2063,43 +2098,43 @@ By default, the analyzed period includes the last eight days including the curre @param startDate string - Start date of the period to analyze, in `YYYY-MM-DD` format. @param endDate string - End date of the period to analyze, in `YYYY-MM-DD` format. @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetPurchaseRateWithHTTPInfo(r ApiGetPurchaseRateRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetPurchaseRateWithHTTPInfo(r ApiGetPurchaseRateRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/2/conversions/purchaseRate" if r.index == "" { return nil, nil, reportError("Parameter `index` is required when calling `GetPurchaseRate`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } - options.QueryParams.Set("index", utils.QueryParameterToString(r.index)) + conf.queryParams.Set("index", utils.QueryParameterToString(r.index)) if !utils.IsNilOrEmpty(r.startDate) { - options.QueryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) + conf.queryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) } if !utils.IsNilOrEmpty(r.endDate) { - options.QueryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) + conf.queryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) } if !utils.IsNilOrEmpty(r.tags) { - options.QueryParams.Set("tags", utils.QueryParameterToString(*r.tags)) + conf.queryParams.Set("tags", utils.QueryParameterToString(*r.tags)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -2125,7 +2160,7 @@ Request can be constructed by NewApiGetPurchaseRateRequest with parameters below @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). @return GetPurchaseRateResponse */ -func (c *APIClient) GetPurchaseRate(r ApiGetPurchaseRateRequest, opts ...utils.RequestOption) (*GetPurchaseRateResponse, error) { +func (c *APIClient) GetPurchaseRate(r ApiGetPurchaseRateRequest, opts ...RequestOption) (*GetPurchaseRateResponse, error) { var returnValue *GetPurchaseRateResponse res, resBody, err := c.GetPurchaseRateWithHTTPInfo(r, opts...) @@ -2255,43 +2290,43 @@ By default, the analyzed period includes the last eight days including the curre @param startDate string - Start date of the period to analyze, in `YYYY-MM-DD` format. @param endDate string - End date of the period to analyze, in `YYYY-MM-DD` format. @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetRevenueWithHTTPInfo(r ApiGetRevenueRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetRevenueWithHTTPInfo(r ApiGetRevenueRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/2/conversions/revenue" if r.index == "" { return nil, nil, reportError("Parameter `index` is required when calling `GetRevenue`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } - options.QueryParams.Set("index", utils.QueryParameterToString(r.index)) + conf.queryParams.Set("index", utils.QueryParameterToString(r.index)) if !utils.IsNilOrEmpty(r.startDate) { - options.QueryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) + conf.queryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) } if !utils.IsNilOrEmpty(r.endDate) { - options.QueryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) + conf.queryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) } if !utils.IsNilOrEmpty(r.tags) { - options.QueryParams.Set("tags", utils.QueryParameterToString(*r.tags)) + conf.queryParams.Set("tags", utils.QueryParameterToString(*r.tags)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -2318,7 +2353,7 @@ Request can be constructed by NewApiGetRevenueRequest with parameters below. @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). @return GetRevenue */ -func (c *APIClient) GetRevenue(r ApiGetRevenueRequest, opts ...utils.RequestOption) (*GetRevenue, error) { +func (c *APIClient) GetRevenue(r ApiGetRevenueRequest, opts ...RequestOption) (*GetRevenue, error) { var returnValue *GetRevenue res, resBody, err := c.GetRevenueWithHTTPInfo(r, opts...) @@ -2447,43 +2482,43 @@ By default, the analyzed period includes the last eight days including the curre @param startDate string - Start date of the period to analyze, in `YYYY-MM-DD` format. @param endDate string - End date of the period to analyze, in `YYYY-MM-DD` format. @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetSearchesCountWithHTTPInfo(r ApiGetSearchesCountRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetSearchesCountWithHTTPInfo(r ApiGetSearchesCountRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/2/searches/count" if r.index == "" { return nil, nil, reportError("Parameter `index` is required when calling `GetSearchesCount`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } - options.QueryParams.Set("index", utils.QueryParameterToString(r.index)) + conf.queryParams.Set("index", utils.QueryParameterToString(r.index)) if !utils.IsNilOrEmpty(r.startDate) { - options.QueryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) + conf.queryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) } if !utils.IsNilOrEmpty(r.endDate) { - options.QueryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) + conf.queryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) } if !utils.IsNilOrEmpty(r.tags) { - options.QueryParams.Set("tags", utils.QueryParameterToString(*r.tags)) + conf.queryParams.Set("tags", utils.QueryParameterToString(*r.tags)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -2509,7 +2544,7 @@ Request can be constructed by NewApiGetSearchesCountRequest with parameters belo @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). @return GetSearchesCountResponse */ -func (c *APIClient) GetSearchesCount(r ApiGetSearchesCountRequest, opts ...utils.RequestOption) (*GetSearchesCountResponse, error) { +func (c *APIClient) GetSearchesCount(r ApiGetSearchesCountRequest, opts ...RequestOption) (*GetSearchesCountResponse, error) { var returnValue *GetSearchesCountResponse res, resBody, err := c.GetSearchesCountWithHTTPInfo(r, opts...) @@ -2670,49 +2705,49 @@ GetSearchesNoClicks calls the API and returns the raw response from it. @param limit int32 - Number of items to return. @param offset int32 - Position of the first item to return. @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetSearchesNoClicksWithHTTPInfo(r ApiGetSearchesNoClicksRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetSearchesNoClicksWithHTTPInfo(r ApiGetSearchesNoClicksRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/2/searches/noClicks" if r.index == "" { return nil, nil, reportError("Parameter `index` is required when calling `GetSearchesNoClicks`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } - options.QueryParams.Set("index", utils.QueryParameterToString(r.index)) + conf.queryParams.Set("index", utils.QueryParameterToString(r.index)) if !utils.IsNilOrEmpty(r.startDate) { - options.QueryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) + conf.queryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) } if !utils.IsNilOrEmpty(r.endDate) { - options.QueryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) + conf.queryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) } if !utils.IsNilOrEmpty(r.limit) { - options.QueryParams.Set("limit", utils.QueryParameterToString(*r.limit)) + conf.queryParams.Set("limit", utils.QueryParameterToString(*r.limit)) } if !utils.IsNilOrEmpty(r.offset) { - options.QueryParams.Set("offset", utils.QueryParameterToString(*r.offset)) + conf.queryParams.Set("offset", utils.QueryParameterToString(*r.offset)) } if !utils.IsNilOrEmpty(r.tags) { - options.QueryParams.Set("tags", utils.QueryParameterToString(*r.tags)) + conf.queryParams.Set("tags", utils.QueryParameterToString(*r.tags)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -2738,7 +2773,7 @@ Request can be constructed by NewApiGetSearchesNoClicksRequest with parameters b @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). @return GetSearchesNoClicksResponse */ -func (c *APIClient) GetSearchesNoClicks(r ApiGetSearchesNoClicksRequest, opts ...utils.RequestOption) (*GetSearchesNoClicksResponse, error) { +func (c *APIClient) GetSearchesNoClicks(r ApiGetSearchesNoClicksRequest, opts ...RequestOption) (*GetSearchesNoClicksResponse, error) { var returnValue *GetSearchesNoClicksResponse res, resBody, err := c.GetSearchesNoClicksWithHTTPInfo(r, opts...) @@ -2899,49 +2934,49 @@ GetSearchesNoResults calls the API and returns the raw response from it. @param limit int32 - Number of items to return. @param offset int32 - Position of the first item to return. @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetSearchesNoResultsWithHTTPInfo(r ApiGetSearchesNoResultsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetSearchesNoResultsWithHTTPInfo(r ApiGetSearchesNoResultsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/2/searches/noResults" if r.index == "" { return nil, nil, reportError("Parameter `index` is required when calling `GetSearchesNoResults`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } - options.QueryParams.Set("index", utils.QueryParameterToString(r.index)) + conf.queryParams.Set("index", utils.QueryParameterToString(r.index)) if !utils.IsNilOrEmpty(r.startDate) { - options.QueryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) + conf.queryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) } if !utils.IsNilOrEmpty(r.endDate) { - options.QueryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) + conf.queryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) } if !utils.IsNilOrEmpty(r.limit) { - options.QueryParams.Set("limit", utils.QueryParameterToString(*r.limit)) + conf.queryParams.Set("limit", utils.QueryParameterToString(*r.limit)) } if !utils.IsNilOrEmpty(r.offset) { - options.QueryParams.Set("offset", utils.QueryParameterToString(*r.offset)) + conf.queryParams.Set("offset", utils.QueryParameterToString(*r.offset)) } if !utils.IsNilOrEmpty(r.tags) { - options.QueryParams.Set("tags", utils.QueryParameterToString(*r.tags)) + conf.queryParams.Set("tags", utils.QueryParameterToString(*r.tags)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -2967,7 +3002,7 @@ Request can be constructed by NewApiGetSearchesNoResultsRequest with parameters @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). @return GetSearchesNoResultsResponse */ -func (c *APIClient) GetSearchesNoResults(r ApiGetSearchesNoResultsRequest, opts ...utils.RequestOption) (*GetSearchesNoResultsResponse, error) { +func (c *APIClient) GetSearchesNoResults(r ApiGetSearchesNoResultsRequest, opts ...RequestOption) (*GetSearchesNoResultsResponse, error) { var returnValue *GetSearchesNoResultsResponse res, resBody, err := c.GetSearchesNoResultsWithHTTPInfo(r, opts...) @@ -3045,34 +3080,34 @@ The Analytics data is updated every 5 minutes. Request can be constructed by NewApiGetStatusRequest with parameters below. @param index string - Index name. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetStatusWithHTTPInfo(r ApiGetStatusRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetStatusWithHTTPInfo(r ApiGetStatusRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/2/status" if r.index == "" { return nil, nil, reportError("Parameter `index` is required when calling `GetStatus`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } - options.QueryParams.Set("index", utils.QueryParameterToString(r.index)) + conf.queryParams.Set("index", utils.QueryParameterToString(r.index)) // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -3095,7 +3130,7 @@ Request can be constructed by NewApiGetStatusRequest with parameters below. @param index string - Index name. @return GetStatusResponse */ -func (c *APIClient) GetStatus(r ApiGetStatusRequest, opts ...utils.RequestOption) (*GetStatusResponse, error) { +func (c *APIClient) GetStatus(r ApiGetStatusRequest, opts ...RequestOption) (*GetStatusResponse, error) { var returnValue *GetStatusResponse res, resBody, err := c.GetStatusWithHTTPInfo(r, opts...) @@ -3256,49 +3291,49 @@ GetTopCountries calls the API and returns the raw response from it. @param limit int32 - Number of items to return. @param offset int32 - Position of the first item to return. @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetTopCountriesWithHTTPInfo(r ApiGetTopCountriesRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetTopCountriesWithHTTPInfo(r ApiGetTopCountriesRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/2/countries" if r.index == "" { return nil, nil, reportError("Parameter `index` is required when calling `GetTopCountries`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } - options.QueryParams.Set("index", utils.QueryParameterToString(r.index)) + conf.queryParams.Set("index", utils.QueryParameterToString(r.index)) if !utils.IsNilOrEmpty(r.startDate) { - options.QueryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) + conf.queryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) } if !utils.IsNilOrEmpty(r.endDate) { - options.QueryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) + conf.queryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) } if !utils.IsNilOrEmpty(r.limit) { - options.QueryParams.Set("limit", utils.QueryParameterToString(*r.limit)) + conf.queryParams.Set("limit", utils.QueryParameterToString(*r.limit)) } if !utils.IsNilOrEmpty(r.offset) { - options.QueryParams.Set("offset", utils.QueryParameterToString(*r.offset)) + conf.queryParams.Set("offset", utils.QueryParameterToString(*r.offset)) } if !utils.IsNilOrEmpty(r.tags) { - options.QueryParams.Set("tags", utils.QueryParameterToString(*r.tags)) + conf.queryParams.Set("tags", utils.QueryParameterToString(*r.tags)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -3324,7 +3359,7 @@ Request can be constructed by NewApiGetTopCountriesRequest with parameters below @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). @return GetTopCountriesResponse */ -func (c *APIClient) GetTopCountries(r ApiGetTopCountriesRequest, opts ...utils.RequestOption) (*GetTopCountriesResponse, error) { +func (c *APIClient) GetTopCountries(r ApiGetTopCountriesRequest, opts ...RequestOption) (*GetTopCountriesResponse, error) { var returnValue *GetTopCountriesResponse res, resBody, err := c.GetTopCountriesWithHTTPInfo(r, opts...) @@ -3504,52 +3539,52 @@ These are attributes of your records that you included in the `attributesForFace @param limit int32 - Number of items to return. @param offset int32 - Position of the first item to return. @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetTopFilterAttributesWithHTTPInfo(r ApiGetTopFilterAttributesRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetTopFilterAttributesWithHTTPInfo(r ApiGetTopFilterAttributesRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/2/filters" if r.index == "" { return nil, nil, reportError("Parameter `index` is required when calling `GetTopFilterAttributes`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } - options.QueryParams.Set("index", utils.QueryParameterToString(r.index)) + conf.queryParams.Set("index", utils.QueryParameterToString(r.index)) if !utils.IsNilOrEmpty(r.search) { - options.QueryParams.Set("search", utils.QueryParameterToString(*r.search)) + conf.queryParams.Set("search", utils.QueryParameterToString(*r.search)) } if !utils.IsNilOrEmpty(r.startDate) { - options.QueryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) + conf.queryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) } if !utils.IsNilOrEmpty(r.endDate) { - options.QueryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) + conf.queryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) } if !utils.IsNilOrEmpty(r.limit) { - options.QueryParams.Set("limit", utils.QueryParameterToString(*r.limit)) + conf.queryParams.Set("limit", utils.QueryParameterToString(*r.limit)) } if !utils.IsNilOrEmpty(r.offset) { - options.QueryParams.Set("offset", utils.QueryParameterToString(*r.offset)) + conf.queryParams.Set("offset", utils.QueryParameterToString(*r.offset)) } if !utils.IsNilOrEmpty(r.tags) { - options.QueryParams.Set("tags", utils.QueryParameterToString(*r.tags)) + conf.queryParams.Set("tags", utils.QueryParameterToString(*r.tags)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -3578,7 +3613,7 @@ Request can be constructed by NewApiGetTopFilterAttributesRequest with parameter @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). @return GetTopFilterAttributesResponse */ -func (c *APIClient) GetTopFilterAttributes(r ApiGetTopFilterAttributesRequest, opts ...utils.RequestOption) (*GetTopFilterAttributesResponse, error) { +func (c *APIClient) GetTopFilterAttributes(r ApiGetTopFilterAttributesRequest, opts ...RequestOption) (*GetTopFilterAttributesResponse, error) { var returnValue *GetTopFilterAttributesResponse res, resBody, err := c.GetTopFilterAttributesWithHTTPInfo(r, opts...) @@ -3770,12 +3805,12 @@ These are attributes of your records that you included in the `attributesForFace @param limit int32 - Number of items to return. @param offset int32 - Position of the first item to return. @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetTopFilterForAttributeWithHTTPInfo(r ApiGetTopFilterForAttributeRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetTopFilterForAttributeWithHTTPInfo(r ApiGetTopFilterForAttributeRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/2/filters/{attribute}" requestPath = strings.ReplaceAll(requestPath, "{attribute}", url.PathEscape(utils.ParameterToString(r.attribute))) @@ -3786,40 +3821,40 @@ func (c *APIClient) GetTopFilterForAttributeWithHTTPInfo(r ApiGetTopFilterForAtt return nil, nil, reportError("Parameter `index` is required when calling `GetTopFilterForAttribute`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } - options.QueryParams.Set("index", utils.QueryParameterToString(r.index)) + conf.queryParams.Set("index", utils.QueryParameterToString(r.index)) if !utils.IsNilOrEmpty(r.search) { - options.QueryParams.Set("search", utils.QueryParameterToString(*r.search)) + conf.queryParams.Set("search", utils.QueryParameterToString(*r.search)) } if !utils.IsNilOrEmpty(r.startDate) { - options.QueryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) + conf.queryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) } if !utils.IsNilOrEmpty(r.endDate) { - options.QueryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) + conf.queryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) } if !utils.IsNilOrEmpty(r.limit) { - options.QueryParams.Set("limit", utils.QueryParameterToString(*r.limit)) + conf.queryParams.Set("limit", utils.QueryParameterToString(*r.limit)) } if !utils.IsNilOrEmpty(r.offset) { - options.QueryParams.Set("offset", utils.QueryParameterToString(*r.offset)) + conf.queryParams.Set("offset", utils.QueryParameterToString(*r.offset)) } if !utils.IsNilOrEmpty(r.tags) { - options.QueryParams.Set("tags", utils.QueryParameterToString(*r.tags)) + conf.queryParams.Set("tags", utils.QueryParameterToString(*r.tags)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -3849,7 +3884,7 @@ Request can be constructed by NewApiGetTopFilterForAttributeRequest with paramet @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). @return GetTopFilterForAttributeResponse */ -func (c *APIClient) GetTopFilterForAttribute(r ApiGetTopFilterForAttributeRequest, opts ...utils.RequestOption) (*GetTopFilterForAttributeResponse, error) { +func (c *APIClient) GetTopFilterForAttribute(r ApiGetTopFilterForAttributeRequest, opts ...RequestOption) (*GetTopFilterForAttributeResponse, error) { var returnValue *GetTopFilterForAttributeResponse res, resBody, err := c.GetTopFilterForAttributeWithHTTPInfo(r, opts...) @@ -4029,52 +4064,52 @@ To get the most frequent searches without results, use the [Retrieve searches wi @param limit int32 - Number of items to return. @param offset int32 - Position of the first item to return. @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetTopFiltersNoResultsWithHTTPInfo(r ApiGetTopFiltersNoResultsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetTopFiltersNoResultsWithHTTPInfo(r ApiGetTopFiltersNoResultsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/2/filters/noResults" if r.index == "" { return nil, nil, reportError("Parameter `index` is required when calling `GetTopFiltersNoResults`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } - options.QueryParams.Set("index", utils.QueryParameterToString(r.index)) + conf.queryParams.Set("index", utils.QueryParameterToString(r.index)) if !utils.IsNilOrEmpty(r.search) { - options.QueryParams.Set("search", utils.QueryParameterToString(*r.search)) + conf.queryParams.Set("search", utils.QueryParameterToString(*r.search)) } if !utils.IsNilOrEmpty(r.startDate) { - options.QueryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) + conf.queryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) } if !utils.IsNilOrEmpty(r.endDate) { - options.QueryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) + conf.queryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) } if !utils.IsNilOrEmpty(r.limit) { - options.QueryParams.Set("limit", utils.QueryParameterToString(*r.limit)) + conf.queryParams.Set("limit", utils.QueryParameterToString(*r.limit)) } if !utils.IsNilOrEmpty(r.offset) { - options.QueryParams.Set("offset", utils.QueryParameterToString(*r.offset)) + conf.queryParams.Set("offset", utils.QueryParameterToString(*r.offset)) } if !utils.IsNilOrEmpty(r.tags) { - options.QueryParams.Set("tags", utils.QueryParameterToString(*r.tags)) + conf.queryParams.Set("tags", utils.QueryParameterToString(*r.tags)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -4103,7 +4138,7 @@ Request can be constructed by NewApiGetTopFiltersNoResultsRequest with parameter @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). @return GetTopFiltersNoResultsResponse */ -func (c *APIClient) GetTopFiltersNoResults(r ApiGetTopFiltersNoResultsRequest, opts ...utils.RequestOption) (*GetTopFiltersNoResultsResponse, error) { +func (c *APIClient) GetTopFiltersNoResults(r ApiGetTopFiltersNoResultsRequest, opts ...RequestOption) (*GetTopFiltersNoResultsResponse, error) { var returnValue *GetTopFiltersNoResultsResponse res, resBody, err := c.GetTopFiltersNoResultsWithHTTPInfo(r, opts...) @@ -4315,58 +4350,58 @@ GetTopHits calls the API and returns the raw response from it. @param limit int32 - Number of items to return. @param offset int32 - Position of the first item to return. @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetTopHitsWithHTTPInfo(r ApiGetTopHitsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetTopHitsWithHTTPInfo(r ApiGetTopHitsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/2/hits" if r.index == "" { return nil, nil, reportError("Parameter `index` is required when calling `GetTopHits`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } - options.QueryParams.Set("index", utils.QueryParameterToString(r.index)) + conf.queryParams.Set("index", utils.QueryParameterToString(r.index)) if !utils.IsNilOrEmpty(r.search) { - options.QueryParams.Set("search", utils.QueryParameterToString(*r.search)) + conf.queryParams.Set("search", utils.QueryParameterToString(*r.search)) } if !utils.IsNilOrEmpty(r.clickAnalytics) { - options.QueryParams.Set("clickAnalytics", utils.QueryParameterToString(*r.clickAnalytics)) + conf.queryParams.Set("clickAnalytics", utils.QueryParameterToString(*r.clickAnalytics)) } if !utils.IsNilOrEmpty(r.revenueAnalytics) { - options.QueryParams.Set("revenueAnalytics", utils.QueryParameterToString(*r.revenueAnalytics)) + conf.queryParams.Set("revenueAnalytics", utils.QueryParameterToString(*r.revenueAnalytics)) } if !utils.IsNilOrEmpty(r.startDate) { - options.QueryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) + conf.queryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) } if !utils.IsNilOrEmpty(r.endDate) { - options.QueryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) + conf.queryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) } if !utils.IsNilOrEmpty(r.limit) { - options.QueryParams.Set("limit", utils.QueryParameterToString(*r.limit)) + conf.queryParams.Set("limit", utils.QueryParameterToString(*r.limit)) } if !utils.IsNilOrEmpty(r.offset) { - options.QueryParams.Set("offset", utils.QueryParameterToString(*r.offset)) + conf.queryParams.Set("offset", utils.QueryParameterToString(*r.offset)) } if !utils.IsNilOrEmpty(r.tags) { - options.QueryParams.Set("tags", utils.QueryParameterToString(*r.tags)) + conf.queryParams.Set("tags", utils.QueryParameterToString(*r.tags)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -4395,7 +4430,7 @@ Request can be constructed by NewApiGetTopHitsRequest with parameters below. @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). @return GetTopHitsResponse */ -func (c *APIClient) GetTopHits(r ApiGetTopHitsRequest, opts ...utils.RequestOption) (*GetTopHitsResponse, error) { +func (c *APIClient) GetTopHits(r ApiGetTopHitsRequest, opts ...RequestOption) (*GetTopHitsResponse, error) { var returnValue *GetTopHitsResponse res, resBody, err := c.GetTopHitsWithHTTPInfo(r, opts...) @@ -4624,61 +4659,61 @@ GetTopSearches calls the API and returns the raw response from it. @param limit int32 - Number of items to return. @param offset int32 - Position of the first item to return. @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetTopSearchesWithHTTPInfo(r ApiGetTopSearchesRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetTopSearchesWithHTTPInfo(r ApiGetTopSearchesRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/2/searches" if r.index == "" { return nil, nil, reportError("Parameter `index` is required when calling `GetTopSearches`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } - options.QueryParams.Set("index", utils.QueryParameterToString(r.index)) + conf.queryParams.Set("index", utils.QueryParameterToString(r.index)) if !utils.IsNilOrEmpty(r.clickAnalytics) { - options.QueryParams.Set("clickAnalytics", utils.QueryParameterToString(*r.clickAnalytics)) + conf.queryParams.Set("clickAnalytics", utils.QueryParameterToString(*r.clickAnalytics)) } if !utils.IsNilOrEmpty(r.revenueAnalytics) { - options.QueryParams.Set("revenueAnalytics", utils.QueryParameterToString(*r.revenueAnalytics)) + conf.queryParams.Set("revenueAnalytics", utils.QueryParameterToString(*r.revenueAnalytics)) } if !utils.IsNilOrEmpty(r.startDate) { - options.QueryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) + conf.queryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) } if !utils.IsNilOrEmpty(r.endDate) { - options.QueryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) + conf.queryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) } if !utils.IsNilOrEmpty(r.orderBy) { - options.QueryParams.Set("orderBy", utils.QueryParameterToString(r.orderBy)) + conf.queryParams.Set("orderBy", utils.QueryParameterToString(r.orderBy)) } if !utils.IsNilOrEmpty(r.direction) { - options.QueryParams.Set("direction", utils.QueryParameterToString(r.direction)) + conf.queryParams.Set("direction", utils.QueryParameterToString(r.direction)) } if !utils.IsNilOrEmpty(r.limit) { - options.QueryParams.Set("limit", utils.QueryParameterToString(*r.limit)) + conf.queryParams.Set("limit", utils.QueryParameterToString(*r.limit)) } if !utils.IsNilOrEmpty(r.offset) { - options.QueryParams.Set("offset", utils.QueryParameterToString(*r.offset)) + conf.queryParams.Set("offset", utils.QueryParameterToString(*r.offset)) } if !utils.IsNilOrEmpty(r.tags) { - options.QueryParams.Set("tags", utils.QueryParameterToString(*r.tags)) + conf.queryParams.Set("tags", utils.QueryParameterToString(*r.tags)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -4708,7 +4743,7 @@ Request can be constructed by NewApiGetTopSearchesRequest with parameters below. @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). @return GetTopSearchesResponse */ -func (c *APIClient) GetTopSearches(r ApiGetTopSearchesRequest, opts ...utils.RequestOption) (*GetTopSearchesResponse, error) { +func (c *APIClient) GetTopSearches(r ApiGetTopSearchesRequest, opts ...RequestOption) (*GetTopSearchesResponse, error) { var returnValue *GetTopSearchesResponse res, resBody, err := c.GetTopSearchesWithHTTPInfo(r, opts...) @@ -4840,43 +4875,43 @@ By default, the analyzed period includes the last eight days including the curre @param startDate string - Start date of the period to analyze, in `YYYY-MM-DD` format. @param endDate string - End date of the period to analyze, in `YYYY-MM-DD` format. @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetUsersCountWithHTTPInfo(r ApiGetUsersCountRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetUsersCountWithHTTPInfo(r ApiGetUsersCountRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/2/users/count" if r.index == "" { return nil, nil, reportError("Parameter `index` is required when calling `GetUsersCount`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } - options.QueryParams.Set("index", utils.QueryParameterToString(r.index)) + conf.queryParams.Set("index", utils.QueryParameterToString(r.index)) if !utils.IsNilOrEmpty(r.startDate) { - options.QueryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) + conf.queryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) } if !utils.IsNilOrEmpty(r.endDate) { - options.QueryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) + conf.queryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) } if !utils.IsNilOrEmpty(r.tags) { - options.QueryParams.Set("tags", utils.QueryParameterToString(*r.tags)) + conf.queryParams.Set("tags", utils.QueryParameterToString(*r.tags)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -4905,7 +4940,7 @@ Request can be constructed by NewApiGetUsersCountRequest with parameters below. @param tags string - Tags by which to segment the analytics. You can combine multiple tags with `OR` and `AND`. Tags must be URL-encoded. For more information, see [Segment your analytics data](https://www.algolia.com/doc/guides/search-analytics/guides/segments/). @return GetUsersCountResponse */ -func (c *APIClient) GetUsersCount(r ApiGetUsersCountRequest, opts ...utils.RequestOption) (*GetUsersCountResponse, error) { +func (c *APIClient) GetUsersCount(r ApiGetUsersCountRequest, opts ...RequestOption) (*GetUsersCountResponse, error) { var returnValue *GetUsersCountResponse res, resBody, err := c.GetUsersCountWithHTTPInfo(r, opts...) diff --git a/clients/algoliasearch-client-go/algolia/ingestion/api_ingestion.go b/clients/algoliasearch-client-go/algolia/ingestion/api_ingestion.go index c5d95074d0..1afe9f4c9a 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/api_ingestion.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/api_ingestion.go @@ -12,6 +12,41 @@ import ( "github.com/algolia/algoliasearch-client-go/v4/algolia/utils" ) +type config struct { + // -- Request options for API calls + context context.Context + queryParams url.Values + headerParams map[string]string +} + +type RequestOption interface { + apply(*config) +} + +type requestOption func(*config) + +func (r requestOption) apply(c *config) { + r(c) +} + +func WithContext(ctx context.Context) requestOption { + return requestOption(func(c *config) { + c.context = ctx + }) +} + +func WithHeaderParam(key string, value any) requestOption { + return requestOption(func(c *config) { + c.headerParams[key] = utils.ParameterToString(value) + }) +} + +func WithQueryParam(key string, value any) requestOption { + return requestOption(func(c *config) { + c.queryParams.Set(utils.QueryParameterToString(key), utils.QueryParameterToString(value)) + }) +} + func (r *ApiCreateAuthenticationRequest) UnmarshalJSON(b []byte) error { req := map[string]json.RawMessage{} err := json.Unmarshal(b, &req) @@ -60,34 +95,34 @@ CreateAuthentication calls the API and returns the raw response from it. Request can be constructed by NewApiCreateAuthenticationRequest with parameters below. @param authenticationCreate AuthenticationCreate - - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CreateAuthenticationWithHTTPInfo(r ApiCreateAuthenticationRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CreateAuthenticationWithHTTPInfo(r ApiCreateAuthenticationRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/authentications" if r.authenticationCreate == nil { return nil, nil, reportError("Parameter `authenticationCreate` is required when calling `CreateAuthentication`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.authenticationCreate - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -110,7 +145,7 @@ Request can be constructed by NewApiCreateAuthenticationRequest with parameters @param authenticationCreate AuthenticationCreate - @return AuthenticationCreateResponse */ -func (c *APIClient) CreateAuthentication(r ApiCreateAuthenticationRequest, opts ...utils.RequestOption) (*AuthenticationCreateResponse, error) { +func (c *APIClient) CreateAuthentication(r ApiCreateAuthenticationRequest, opts ...RequestOption) (*AuthenticationCreateResponse, error) { var returnValue *AuthenticationCreateResponse res, resBody, err := c.CreateAuthenticationWithHTTPInfo(r, opts...) @@ -193,34 +228,34 @@ CreateDestination calls the API and returns the raw response from it. Request can be constructed by NewApiCreateDestinationRequest with parameters below. @param destinationCreate DestinationCreate - - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CreateDestinationWithHTTPInfo(r ApiCreateDestinationRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CreateDestinationWithHTTPInfo(r ApiCreateDestinationRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/destinations" if r.destinationCreate == nil { return nil, nil, reportError("Parameter `destinationCreate` is required when calling `CreateDestination`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.destinationCreate - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -243,7 +278,7 @@ Request can be constructed by NewApiCreateDestinationRequest with parameters bel @param destinationCreate DestinationCreate - @return DestinationCreateResponse */ -func (c *APIClient) CreateDestination(r ApiCreateDestinationRequest, opts ...utils.RequestOption) (*DestinationCreateResponse, error) { +func (c *APIClient) CreateDestination(r ApiCreateDestinationRequest, opts ...RequestOption) (*DestinationCreateResponse, error) { var returnValue *DestinationCreateResponse res, resBody, err := c.CreateDestinationWithHTTPInfo(r, opts...) @@ -326,34 +361,34 @@ CreateSource calls the API and returns the raw response from it. Request can be constructed by NewApiCreateSourceRequest with parameters below. @param sourceCreate SourceCreate - - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CreateSourceWithHTTPInfo(r ApiCreateSourceRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CreateSourceWithHTTPInfo(r ApiCreateSourceRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/sources" if r.sourceCreate == nil { return nil, nil, reportError("Parameter `sourceCreate` is required when calling `CreateSource`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.sourceCreate - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -376,7 +411,7 @@ Request can be constructed by NewApiCreateSourceRequest with parameters below. @param sourceCreate SourceCreate - @return SourceCreateResponse */ -func (c *APIClient) CreateSource(r ApiCreateSourceRequest, opts ...utils.RequestOption) (*SourceCreateResponse, error) { +func (c *APIClient) CreateSource(r ApiCreateSourceRequest, opts ...RequestOption) (*SourceCreateResponse, error) { var returnValue *SourceCreateResponse res, resBody, err := c.CreateSourceWithHTTPInfo(r, opts...) @@ -455,34 +490,34 @@ CreateTask calls the API and returns the raw response from it. Request can be constructed by NewApiCreateTaskRequest with parameters below. @param taskCreate TaskCreate - Request body for creating a task. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CreateTaskWithHTTPInfo(r ApiCreateTaskRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CreateTaskWithHTTPInfo(r ApiCreateTaskRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/tasks" if r.taskCreate == nil { return nil, nil, reportError("Parameter `taskCreate` is required when calling `CreateTask`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.taskCreate - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -500,7 +535,7 @@ Request can be constructed by NewApiCreateTaskRequest with parameters below. @param taskCreate TaskCreate - Request body for creating a task. @return TaskCreateResponse */ -func (c *APIClient) CreateTask(r ApiCreateTaskRequest, opts ...utils.RequestOption) (*TaskCreateResponse, error) { +func (c *APIClient) CreateTask(r ApiCreateTaskRequest, opts ...RequestOption) (*TaskCreateResponse, error) { var returnValue *TaskCreateResponse res, resBody, err := c.CreateTaskWithHTTPInfo(r, opts...) @@ -579,34 +614,34 @@ CreateTransformation calls the API and returns the raw response from it. Request can be constructed by NewApiCreateTransformationRequest with parameters below. @param transformationCreate TransformationCreate - Request body for creating a transformation. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CreateTransformationWithHTTPInfo(r ApiCreateTransformationRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CreateTransformationWithHTTPInfo(r ApiCreateTransformationRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/transformations" if r.transformationCreate == nil { return nil, nil, reportError("Parameter `transformationCreate` is required when calling `CreateTransformation`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.transformationCreate - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -624,7 +659,7 @@ Request can be constructed by NewApiCreateTransformationRequest with parameters @param transformationCreate TransformationCreate - Request body for creating a transformation. @return TransformationCreateResponse */ -func (c *APIClient) CreateTransformation(r ApiCreateTransformationRequest, opts ...utils.RequestOption) (*TransformationCreateResponse, error) { +func (c *APIClient) CreateTransformation(r ApiCreateTransformationRequest, opts ...RequestOption) (*TransformationCreateResponse, error) { var returnValue *TransformationCreateResponse res, resBody, err := c.CreateTransformationWithHTTPInfo(r, opts...) @@ -715,12 +750,12 @@ CustomDelete calls the API and returns the raw response from it. Request can be constructed by NewApiCustomDeleteRequest with parameters below. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomDeleteWithHTTPInfo(r ApiCustomDeleteRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomDeleteWithHTTPInfo(r ApiCustomDeleteRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -728,26 +763,26 @@ func (c *APIClient) CustomDeleteWithHTTPInfo(r ApiCustomDeleteRequest, opts ...u return nil, nil, reportError("Parameter `path` is required when calling `CustomDelete`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodDelete, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodDelete, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -766,7 +801,7 @@ Request can be constructed by NewApiCustomDeleteRequest with parameters below. @param parameters map[string]any - Query parameters to apply to the current query. @return map[string]any */ -func (c *APIClient) CustomDelete(r ApiCustomDeleteRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomDelete(r ApiCustomDeleteRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomDeleteWithHTTPInfo(r, opts...) @@ -857,12 +892,12 @@ CustomGet calls the API and returns the raw response from it. Request can be constructed by NewApiCustomGetRequest with parameters below. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomGetWithHTTPInfo(r ApiCustomGetRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomGetWithHTTPInfo(r ApiCustomGetRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -870,26 +905,26 @@ func (c *APIClient) CustomGetWithHTTPInfo(r ApiCustomGetRequest, opts ...utils.R return nil, nil, reportError("Parameter `path` is required when calling `CustomGet`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -908,7 +943,7 @@ Request can be constructed by NewApiCustomGetRequest with parameters below. @param parameters map[string]any - Query parameters to apply to the current query. @return map[string]any */ -func (c *APIClient) CustomGet(r ApiCustomGetRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomGet(r ApiCustomGetRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomGetWithHTTPInfo(r, opts...) @@ -1016,12 +1051,12 @@ CustomPost calls the API and returns the raw response from it. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. @param body map[string]any - Parameters to send with the custom request. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -1029,21 +1064,21 @@ func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...utils return nil, nil, reportError("Parameter `path` is required when calling `CustomPost`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any @@ -1054,7 +1089,7 @@ func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...utils } else { postBody = r.body } - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1074,7 +1109,7 @@ Request can be constructed by NewApiCustomPostRequest with parameters below. @param body map[string]any - Parameters to send with the custom request. @return map[string]any */ -func (c *APIClient) CustomPost(r ApiCustomPostRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomPost(r ApiCustomPostRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomPostWithHTTPInfo(r, opts...) @@ -1182,12 +1217,12 @@ CustomPut calls the API and returns the raw response from it. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. @param body map[string]any - Parameters to send with the custom request. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -1195,21 +1230,21 @@ func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...utils.R return nil, nil, reportError("Parameter `path` is required when calling `CustomPut`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any @@ -1220,7 +1255,7 @@ func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...utils.R } else { postBody = r.body } - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPut, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPut, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1240,7 +1275,7 @@ Request can be constructed by NewApiCustomPutRequest with parameters below. @param body map[string]any - Parameters to send with the custom request. @return map[string]any */ -func (c *APIClient) CustomPut(r ApiCustomPutRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomPut(r ApiCustomPutRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomPutWithHTTPInfo(r, opts...) @@ -1318,12 +1353,12 @@ DeleteAuthentication calls the API and returns the raw response from it. Request can be constructed by NewApiDeleteAuthenticationRequest with parameters below. @param authenticationID string - Unique identifier of an authentication resource. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) DeleteAuthenticationWithHTTPInfo(r ApiDeleteAuthenticationRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) DeleteAuthenticationWithHTTPInfo(r ApiDeleteAuthenticationRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/authentications/{authenticationID}" requestPath = strings.ReplaceAll(requestPath, "{authenticationID}", url.PathEscape(utils.ParameterToString(r.authenticationID))) @@ -1331,20 +1366,20 @@ func (c *APIClient) DeleteAuthenticationWithHTTPInfo(r ApiDeleteAuthenticationRe return nil, nil, reportError("Parameter `authenticationID` is required when calling `DeleteAuthentication`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodDelete, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodDelete, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1367,7 +1402,7 @@ Request can be constructed by NewApiDeleteAuthenticationRequest with parameters @param authenticationID string - Unique identifier of an authentication resource. @return DeleteResponse */ -func (c *APIClient) DeleteAuthentication(r ApiDeleteAuthenticationRequest, opts ...utils.RequestOption) (*DeleteResponse, error) { +func (c *APIClient) DeleteAuthentication(r ApiDeleteAuthenticationRequest, opts ...RequestOption) (*DeleteResponse, error) { var returnValue *DeleteResponse res, resBody, err := c.DeleteAuthenticationWithHTTPInfo(r, opts...) @@ -1445,12 +1480,12 @@ DeleteDestination calls the API and returns the raw response from it. Request can be constructed by NewApiDeleteDestinationRequest with parameters below. @param destinationID string - Unique identifier of a destination. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) DeleteDestinationWithHTTPInfo(r ApiDeleteDestinationRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) DeleteDestinationWithHTTPInfo(r ApiDeleteDestinationRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/destinations/{destinationID}" requestPath = strings.ReplaceAll(requestPath, "{destinationID}", url.PathEscape(utils.ParameterToString(r.destinationID))) @@ -1458,20 +1493,20 @@ func (c *APIClient) DeleteDestinationWithHTTPInfo(r ApiDeleteDestinationRequest, return nil, nil, reportError("Parameter `destinationID` is required when calling `DeleteDestination`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodDelete, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodDelete, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1494,7 +1529,7 @@ Request can be constructed by NewApiDeleteDestinationRequest with parameters bel @param destinationID string - Unique identifier of a destination. @return DeleteResponse */ -func (c *APIClient) DeleteDestination(r ApiDeleteDestinationRequest, opts ...utils.RequestOption) (*DeleteResponse, error) { +func (c *APIClient) DeleteDestination(r ApiDeleteDestinationRequest, opts ...RequestOption) (*DeleteResponse, error) { var returnValue *DeleteResponse res, resBody, err := c.DeleteDestinationWithHTTPInfo(r, opts...) @@ -1572,12 +1607,12 @@ DeleteSource calls the API and returns the raw response from it. Request can be constructed by NewApiDeleteSourceRequest with parameters below. @param sourceID string - Unique identifier of a source. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) DeleteSourceWithHTTPInfo(r ApiDeleteSourceRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) DeleteSourceWithHTTPInfo(r ApiDeleteSourceRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/sources/{sourceID}" requestPath = strings.ReplaceAll(requestPath, "{sourceID}", url.PathEscape(utils.ParameterToString(r.sourceID))) @@ -1585,20 +1620,20 @@ func (c *APIClient) DeleteSourceWithHTTPInfo(r ApiDeleteSourceRequest, opts ...u return nil, nil, reportError("Parameter `sourceID` is required when calling `DeleteSource`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodDelete, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodDelete, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1621,7 +1656,7 @@ Request can be constructed by NewApiDeleteSourceRequest with parameters below. @param sourceID string - Unique identifier of a source. @return DeleteResponse */ -func (c *APIClient) DeleteSource(r ApiDeleteSourceRequest, opts ...utils.RequestOption) (*DeleteResponse, error) { +func (c *APIClient) DeleteSource(r ApiDeleteSourceRequest, opts ...RequestOption) (*DeleteResponse, error) { var returnValue *DeleteResponse res, resBody, err := c.DeleteSourceWithHTTPInfo(r, opts...) @@ -1695,12 +1730,12 @@ DeleteTask calls the API and returns the raw response from it. Request can be constructed by NewApiDeleteTaskRequest with parameters below. @param taskID string - Unique identifier of a task. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) DeleteTaskWithHTTPInfo(r ApiDeleteTaskRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) DeleteTaskWithHTTPInfo(r ApiDeleteTaskRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/tasks/{taskID}" requestPath = strings.ReplaceAll(requestPath, "{taskID}", url.PathEscape(utils.ParameterToString(r.taskID))) @@ -1708,20 +1743,20 @@ func (c *APIClient) DeleteTaskWithHTTPInfo(r ApiDeleteTaskRequest, opts ...utils return nil, nil, reportError("Parameter `taskID` is required when calling `DeleteTask`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodDelete, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodDelete, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1739,7 +1774,7 @@ Request can be constructed by NewApiDeleteTaskRequest with parameters below. @param taskID string - Unique identifier of a task. @return DeleteResponse */ -func (c *APIClient) DeleteTask(r ApiDeleteTaskRequest, opts ...utils.RequestOption) (*DeleteResponse, error) { +func (c *APIClient) DeleteTask(r ApiDeleteTaskRequest, opts ...RequestOption) (*DeleteResponse, error) { var returnValue *DeleteResponse res, resBody, err := c.DeleteTaskWithHTTPInfo(r, opts...) @@ -1813,12 +1848,12 @@ DeleteTransformation calls the API and returns the raw response from it. Request can be constructed by NewApiDeleteTransformationRequest with parameters below. @param transformationID string - Unique identifier of a transformation. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) DeleteTransformationWithHTTPInfo(r ApiDeleteTransformationRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) DeleteTransformationWithHTTPInfo(r ApiDeleteTransformationRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/transformations/{transformationID}" requestPath = strings.ReplaceAll(requestPath, "{transformationID}", url.PathEscape(utils.ParameterToString(r.transformationID))) @@ -1826,20 +1861,20 @@ func (c *APIClient) DeleteTransformationWithHTTPInfo(r ApiDeleteTransformationRe return nil, nil, reportError("Parameter `transformationID` is required when calling `DeleteTransformation`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodDelete, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodDelete, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1857,7 +1892,7 @@ Request can be constructed by NewApiDeleteTransformationRequest with parameters @param transformationID string - Unique identifier of a transformation. @return DeleteResponse */ -func (c *APIClient) DeleteTransformation(r ApiDeleteTransformationRequest, opts ...utils.RequestOption) (*DeleteResponse, error) { +func (c *APIClient) DeleteTransformation(r ApiDeleteTransformationRequest, opts ...RequestOption) (*DeleteResponse, error) { var returnValue *DeleteResponse res, resBody, err := c.DeleteTransformationWithHTTPInfo(r, opts...) @@ -1935,12 +1970,12 @@ DisableTask calls the API and returns the raw response from it. Request can be constructed by NewApiDisableTaskRequest with parameters below. @param taskID string - Unique identifier of a task. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) DisableTaskWithHTTPInfo(r ApiDisableTaskRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) DisableTaskWithHTTPInfo(r ApiDisableTaskRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/tasks/{taskID}/disable" requestPath = strings.ReplaceAll(requestPath, "{taskID}", url.PathEscape(utils.ParameterToString(r.taskID))) @@ -1948,20 +1983,20 @@ func (c *APIClient) DisableTaskWithHTTPInfo(r ApiDisableTaskRequest, opts ...uti return nil, nil, reportError("Parameter `taskID` is required when calling `DisableTask`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPut, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPut, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1984,7 +2019,7 @@ Request can be constructed by NewApiDisableTaskRequest with parameters below. @param taskID string - Unique identifier of a task. @return TaskUpdateResponse */ -func (c *APIClient) DisableTask(r ApiDisableTaskRequest, opts ...utils.RequestOption) (*TaskUpdateResponse, error) { +func (c *APIClient) DisableTask(r ApiDisableTaskRequest, opts ...RequestOption) (*TaskUpdateResponse, error) { var returnValue *TaskUpdateResponse res, resBody, err := c.DisableTaskWithHTTPInfo(r, opts...) @@ -2062,12 +2097,12 @@ EnableTask calls the API and returns the raw response from it. Request can be constructed by NewApiEnableTaskRequest with parameters below. @param taskID string - Unique identifier of a task. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) EnableTaskWithHTTPInfo(r ApiEnableTaskRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) EnableTaskWithHTTPInfo(r ApiEnableTaskRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/tasks/{taskID}/enable" requestPath = strings.ReplaceAll(requestPath, "{taskID}", url.PathEscape(utils.ParameterToString(r.taskID))) @@ -2075,20 +2110,20 @@ func (c *APIClient) EnableTaskWithHTTPInfo(r ApiEnableTaskRequest, opts ...utils return nil, nil, reportError("Parameter `taskID` is required when calling `EnableTask`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPut, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPut, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -2111,7 +2146,7 @@ Request can be constructed by NewApiEnableTaskRequest with parameters below. @param taskID string - Unique identifier of a task. @return TaskUpdateResponse */ -func (c *APIClient) EnableTask(r ApiEnableTaskRequest, opts ...utils.RequestOption) (*TaskUpdateResponse, error) { +func (c *APIClient) EnableTask(r ApiEnableTaskRequest, opts ...RequestOption) (*TaskUpdateResponse, error) { var returnValue *TaskUpdateResponse res, resBody, err := c.EnableTaskWithHTTPInfo(r, opts...) @@ -2189,12 +2224,12 @@ GetAuthentication calls the API and returns the raw response from it. Request can be constructed by NewApiGetAuthenticationRequest with parameters below. @param authenticationID string - Unique identifier of an authentication resource. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetAuthenticationWithHTTPInfo(r ApiGetAuthenticationRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetAuthenticationWithHTTPInfo(r ApiGetAuthenticationRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/authentications/{authenticationID}" requestPath = strings.ReplaceAll(requestPath, "{authenticationID}", url.PathEscape(utils.ParameterToString(r.authenticationID))) @@ -2202,20 +2237,20 @@ func (c *APIClient) GetAuthenticationWithHTTPInfo(r ApiGetAuthenticationRequest, return nil, nil, reportError("Parameter `authenticationID` is required when calling `GetAuthentication`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -2238,7 +2273,7 @@ Request can be constructed by NewApiGetAuthenticationRequest with parameters bel @param authenticationID string - Unique identifier of an authentication resource. @return Authentication */ -func (c *APIClient) GetAuthentication(r ApiGetAuthenticationRequest, opts ...utils.RequestOption) (*Authentication, error) { +func (c *APIClient) GetAuthentication(r ApiGetAuthenticationRequest, opts ...RequestOption) (*Authentication, error) { var returnValue *Authentication res, resBody, err := c.GetAuthenticationWithHTTPInfo(r, opts...) @@ -2405,47 +2440,47 @@ GetAuthentications calls the API and returns the raw response from it. @param platform []PlatformWithNone - Ecommerce platform for which to retrieve authentication resources. @param sort AuthenticationSortKeys - Property by which to sort the list of authentication resources. @param order OrderKeys - Sort order of the response, ascending or descending. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetAuthenticationsWithHTTPInfo(r ApiGetAuthenticationsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetAuthenticationsWithHTTPInfo(r ApiGetAuthenticationsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/authentications" - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.itemsPerPage) { - options.QueryParams.Set("itemsPerPage", utils.QueryParameterToString(*r.itemsPerPage)) + conf.queryParams.Set("itemsPerPage", utils.QueryParameterToString(*r.itemsPerPage)) } if !utils.IsNilOrEmpty(r.page) { - options.QueryParams.Set("page", utils.QueryParameterToString(*r.page)) + conf.queryParams.Set("page", utils.QueryParameterToString(*r.page)) } if !utils.IsNilOrEmpty(r.type_) { - options.QueryParams.Set("type", utils.QueryParameterToString(r.type_)) + conf.queryParams.Set("type", utils.QueryParameterToString(r.type_)) } if !utils.IsNilOrEmpty(r.platform) { - options.QueryParams.Set("platform", utils.QueryParameterToString(r.platform)) + conf.queryParams.Set("platform", utils.QueryParameterToString(r.platform)) } if !utils.IsNilOrEmpty(r.sort) { - options.QueryParams.Set("sort", utils.QueryParameterToString(r.sort)) + conf.queryParams.Set("sort", utils.QueryParameterToString(r.sort)) } if !utils.IsNilOrEmpty(r.order) { - options.QueryParams.Set("order", utils.QueryParameterToString(r.order)) + conf.queryParams.Set("order", utils.QueryParameterToString(r.order)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -2473,7 +2508,7 @@ Request can be constructed by NewApiGetAuthenticationsRequest with parameters be @param order OrderKeys - Sort order of the response, ascending or descending. @return ListAuthenticationsResponse */ -func (c *APIClient) GetAuthentications(r ApiGetAuthenticationsRequest, opts ...utils.RequestOption) (*ListAuthenticationsResponse, error) { +func (c *APIClient) GetAuthentications(r ApiGetAuthenticationsRequest, opts ...RequestOption) (*ListAuthenticationsResponse, error) { var returnValue *ListAuthenticationsResponse res, resBody, err := c.GetAuthenticationsWithHTTPInfo(r, opts...) @@ -2551,12 +2586,12 @@ GetDestination calls the API and returns the raw response from it. Request can be constructed by NewApiGetDestinationRequest with parameters below. @param destinationID string - Unique identifier of a destination. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetDestinationWithHTTPInfo(r ApiGetDestinationRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetDestinationWithHTTPInfo(r ApiGetDestinationRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/destinations/{destinationID}" requestPath = strings.ReplaceAll(requestPath, "{destinationID}", url.PathEscape(utils.ParameterToString(r.destinationID))) @@ -2564,20 +2599,20 @@ func (c *APIClient) GetDestinationWithHTTPInfo(r ApiGetDestinationRequest, opts return nil, nil, reportError("Parameter `destinationID` is required when calling `GetDestination`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -2600,7 +2635,7 @@ Request can be constructed by NewApiGetDestinationRequest with parameters below. @param destinationID string - Unique identifier of a destination. @return Destination */ -func (c *APIClient) GetDestination(r ApiGetDestinationRequest, opts ...utils.RequestOption) (*Destination, error) { +func (c *APIClient) GetDestination(r ApiGetDestinationRequest, opts ...RequestOption) (*Destination, error) { var returnValue *Destination res, resBody, err := c.GetDestinationWithHTTPInfo(r, opts...) @@ -2767,47 +2802,47 @@ GetDestinations calls the API and returns the raw response from it. @param authenticationID []string - Authentication ID used by destinations. @param sort DestinationSortKeys - Property by which to sort the destinations. @param order OrderKeys - Sort order of the response, ascending or descending. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetDestinationsWithHTTPInfo(r ApiGetDestinationsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetDestinationsWithHTTPInfo(r ApiGetDestinationsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/destinations" - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.itemsPerPage) { - options.QueryParams.Set("itemsPerPage", utils.QueryParameterToString(*r.itemsPerPage)) + conf.queryParams.Set("itemsPerPage", utils.QueryParameterToString(*r.itemsPerPage)) } if !utils.IsNilOrEmpty(r.page) { - options.QueryParams.Set("page", utils.QueryParameterToString(*r.page)) + conf.queryParams.Set("page", utils.QueryParameterToString(*r.page)) } if !utils.IsNilOrEmpty(r.type_) { - options.QueryParams.Set("type", utils.QueryParameterToString(r.type_)) + conf.queryParams.Set("type", utils.QueryParameterToString(r.type_)) } if !utils.IsNilOrEmpty(r.authenticationID) { - options.QueryParams.Set("authenticationID", utils.QueryParameterToString(r.authenticationID)) + conf.queryParams.Set("authenticationID", utils.QueryParameterToString(r.authenticationID)) } if !utils.IsNilOrEmpty(r.sort) { - options.QueryParams.Set("sort", utils.QueryParameterToString(r.sort)) + conf.queryParams.Set("sort", utils.QueryParameterToString(r.sort)) } if !utils.IsNilOrEmpty(r.order) { - options.QueryParams.Set("order", utils.QueryParameterToString(r.order)) + conf.queryParams.Set("order", utils.QueryParameterToString(r.order)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -2835,7 +2870,7 @@ Request can be constructed by NewApiGetDestinationsRequest with parameters below @param order OrderKeys - Sort order of the response, ascending or descending. @return ListDestinationsResponse */ -func (c *APIClient) GetDestinations(r ApiGetDestinationsRequest, opts ...utils.RequestOption) (*ListDestinationsResponse, error) { +func (c *APIClient) GetDestinations(r ApiGetDestinationsRequest, opts ...RequestOption) (*ListDestinationsResponse, error) { var returnValue *ListDestinationsResponse res, resBody, err := c.GetDestinationsWithHTTPInfo(r, opts...) @@ -2925,12 +2960,12 @@ GetEvent calls the API and returns the raw response from it. Request can be constructed by NewApiGetEventRequest with parameters below. @param runID string - Unique identifier of a task run. @param eventID string - Unique identifier of an event. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetEventWithHTTPInfo(r ApiGetEventRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetEventWithHTTPInfo(r ApiGetEventRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/runs/{runID}/events/{eventID}" requestPath = strings.ReplaceAll(requestPath, "{runID}", url.PathEscape(utils.ParameterToString(r.runID))) requestPath = strings.ReplaceAll(requestPath, "{eventID}", url.PathEscape(utils.ParameterToString(r.eventID))) @@ -2942,20 +2977,20 @@ func (c *APIClient) GetEventWithHTTPInfo(r ApiGetEventRequest, opts ...utils.Req return nil, nil, reportError("Parameter `eventID` is required when calling `GetEvent`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -2979,7 +3014,7 @@ Request can be constructed by NewApiGetEventRequest with parameters below. @param eventID string - Unique identifier of an event. @return Event */ -func (c *APIClient) GetEvent(r ApiGetEventRequest, opts ...utils.RequestOption) (*Event, error) { +func (c *APIClient) GetEvent(r ApiGetEventRequest, opts ...RequestOption) (*Event, error) { var returnValue *Event res, resBody, err := c.GetEventWithHTTPInfo(r, opts...) @@ -3193,12 +3228,12 @@ GetEvents calls the API and returns the raw response from it. @param order OrderKeys - Sort order of the response, ascending or descending. @param startDate string - Date and time in RFC 3339 format for the earliest events to retrieve. By default, the current time minus three hours is used. @param endDate string - Date and time in RFC 3339 format for the latest events to retrieve. By default, the current time is used. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetEventsWithHTTPInfo(r ApiGetEventsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetEventsWithHTTPInfo(r ApiGetEventsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/runs/{runID}/events" requestPath = strings.ReplaceAll(requestPath, "{runID}", url.PathEscape(utils.ParameterToString(r.runID))) @@ -3206,45 +3241,45 @@ func (c *APIClient) GetEventsWithHTTPInfo(r ApiGetEventsRequest, opts ...utils.R return nil, nil, reportError("Parameter `runID` is required when calling `GetEvents`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.itemsPerPage) { - options.QueryParams.Set("itemsPerPage", utils.QueryParameterToString(*r.itemsPerPage)) + conf.queryParams.Set("itemsPerPage", utils.QueryParameterToString(*r.itemsPerPage)) } if !utils.IsNilOrEmpty(r.page) { - options.QueryParams.Set("page", utils.QueryParameterToString(*r.page)) + conf.queryParams.Set("page", utils.QueryParameterToString(*r.page)) } if !utils.IsNilOrEmpty(r.status) { - options.QueryParams.Set("status", utils.QueryParameterToString(r.status)) + conf.queryParams.Set("status", utils.QueryParameterToString(r.status)) } if !utils.IsNilOrEmpty(r.type_) { - options.QueryParams.Set("type", utils.QueryParameterToString(r.type_)) + conf.queryParams.Set("type", utils.QueryParameterToString(r.type_)) } if !utils.IsNilOrEmpty(r.sort) { - options.QueryParams.Set("sort", utils.QueryParameterToString(r.sort)) + conf.queryParams.Set("sort", utils.QueryParameterToString(r.sort)) } if !utils.IsNilOrEmpty(r.order) { - options.QueryParams.Set("order", utils.QueryParameterToString(r.order)) + conf.queryParams.Set("order", utils.QueryParameterToString(r.order)) } if !utils.IsNilOrEmpty(r.startDate) { - options.QueryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) + conf.queryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) } if !utils.IsNilOrEmpty(r.endDate) { - options.QueryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) + conf.queryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -3275,7 +3310,7 @@ Request can be constructed by NewApiGetEventsRequest with parameters below. @param endDate string - Date and time in RFC 3339 format for the latest events to retrieve. By default, the current time is used. @return ListEventsResponse */ -func (c *APIClient) GetEvents(r ApiGetEventsRequest, opts ...utils.RequestOption) (*ListEventsResponse, error) { +func (c *APIClient) GetEvents(r ApiGetEventsRequest, opts ...RequestOption) (*ListEventsResponse, error) { var returnValue *ListEventsResponse res, resBody, err := c.GetEventsWithHTTPInfo(r, opts...) @@ -3353,12 +3388,12 @@ GetRun calls the API and returns the raw response from it. Request can be constructed by NewApiGetRunRequest with parameters below. @param runID string - Unique identifier of a task run. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetRunWithHTTPInfo(r ApiGetRunRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetRunWithHTTPInfo(r ApiGetRunRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/runs/{runID}" requestPath = strings.ReplaceAll(requestPath, "{runID}", url.PathEscape(utils.ParameterToString(r.runID))) @@ -3366,20 +3401,20 @@ func (c *APIClient) GetRunWithHTTPInfo(r ApiGetRunRequest, opts ...utils.Request return nil, nil, reportError("Parameter `runID` is required when calling `GetRun`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -3402,7 +3437,7 @@ Request can be constructed by NewApiGetRunRequest with parameters below. @param runID string - Unique identifier of a task run. @return Run */ -func (c *APIClient) GetRun(r ApiGetRunRequest, opts ...utils.RequestOption) (*Run, error) { +func (c *APIClient) GetRun(r ApiGetRunRequest, opts ...RequestOption) (*Run, error) { var returnValue *Run res, resBody, err := c.GetRunWithHTTPInfo(r, opts...) @@ -3603,53 +3638,53 @@ GetRuns calls the API and returns the raw response from it. @param order OrderKeys - Sort order of the response, ascending or descending. @param startDate string - Date in RFC 3339 format for the earliest run to retrieve. By default, the current day minus seven days is used. @param endDate string - Date in RFC 3339 format for the latest run to retrieve. By default, the current day is used. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetRunsWithHTTPInfo(r ApiGetRunsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetRunsWithHTTPInfo(r ApiGetRunsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/runs" - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.itemsPerPage) { - options.QueryParams.Set("itemsPerPage", utils.QueryParameterToString(*r.itemsPerPage)) + conf.queryParams.Set("itemsPerPage", utils.QueryParameterToString(*r.itemsPerPage)) } if !utils.IsNilOrEmpty(r.page) { - options.QueryParams.Set("page", utils.QueryParameterToString(*r.page)) + conf.queryParams.Set("page", utils.QueryParameterToString(*r.page)) } if !utils.IsNilOrEmpty(r.status) { - options.QueryParams.Set("status", utils.QueryParameterToString(r.status)) + conf.queryParams.Set("status", utils.QueryParameterToString(r.status)) } if !utils.IsNilOrEmpty(r.taskID) { - options.QueryParams.Set("taskID", utils.QueryParameterToString(*r.taskID)) + conf.queryParams.Set("taskID", utils.QueryParameterToString(*r.taskID)) } if !utils.IsNilOrEmpty(r.sort) { - options.QueryParams.Set("sort", utils.QueryParameterToString(r.sort)) + conf.queryParams.Set("sort", utils.QueryParameterToString(r.sort)) } if !utils.IsNilOrEmpty(r.order) { - options.QueryParams.Set("order", utils.QueryParameterToString(r.order)) + conf.queryParams.Set("order", utils.QueryParameterToString(r.order)) } if !utils.IsNilOrEmpty(r.startDate) { - options.QueryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) + conf.queryParams.Set("startDate", utils.QueryParameterToString(*r.startDate)) } if !utils.IsNilOrEmpty(r.endDate) { - options.QueryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) + conf.queryParams.Set("endDate", utils.QueryParameterToString(*r.endDate)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -3679,7 +3714,7 @@ Request can be constructed by NewApiGetRunsRequest with parameters below. @param endDate string - Date in RFC 3339 format for the latest run to retrieve. By default, the current day is used. @return RunListResponse */ -func (c *APIClient) GetRuns(r ApiGetRunsRequest, opts ...utils.RequestOption) (*RunListResponse, error) { +func (c *APIClient) GetRuns(r ApiGetRunsRequest, opts ...RequestOption) (*RunListResponse, error) { var returnValue *RunListResponse res, resBody, err := c.GetRunsWithHTTPInfo(r, opts...) @@ -3757,12 +3792,12 @@ GetSource calls the API and returns the raw response from it. Request can be constructed by NewApiGetSourceRequest with parameters below. @param sourceID string - Unique identifier of a source. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetSourceWithHTTPInfo(r ApiGetSourceRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetSourceWithHTTPInfo(r ApiGetSourceRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/sources/{sourceID}" requestPath = strings.ReplaceAll(requestPath, "{sourceID}", url.PathEscape(utils.ParameterToString(r.sourceID))) @@ -3770,20 +3805,20 @@ func (c *APIClient) GetSourceWithHTTPInfo(r ApiGetSourceRequest, opts ...utils.R return nil, nil, reportError("Parameter `sourceID` is required when calling `GetSource`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -3806,7 +3841,7 @@ Request can be constructed by NewApiGetSourceRequest with parameters below. @param sourceID string - Unique identifier of a source. @return Source */ -func (c *APIClient) GetSource(r ApiGetSourceRequest, opts ...utils.RequestOption) (*Source, error) { +func (c *APIClient) GetSource(r ApiGetSourceRequest, opts ...RequestOption) (*Source, error) { var returnValue *Source res, resBody, err := c.GetSourceWithHTTPInfo(r, opts...) @@ -3973,47 +4008,47 @@ GetSources calls the API and returns the raw response from it. @param authenticationID []string - Authentication IDs of the sources to retrieve. 'none' returns sources that doesn't have an authentication resource. @param sort SourceSortKeys - Property by which to sort the list of sources. @param order OrderKeys - Sort order of the response, ascending or descending. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetSourcesWithHTTPInfo(r ApiGetSourcesRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetSourcesWithHTTPInfo(r ApiGetSourcesRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/sources" - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.itemsPerPage) { - options.QueryParams.Set("itemsPerPage", utils.QueryParameterToString(*r.itemsPerPage)) + conf.queryParams.Set("itemsPerPage", utils.QueryParameterToString(*r.itemsPerPage)) } if !utils.IsNilOrEmpty(r.page) { - options.QueryParams.Set("page", utils.QueryParameterToString(*r.page)) + conf.queryParams.Set("page", utils.QueryParameterToString(*r.page)) } if !utils.IsNilOrEmpty(r.type_) { - options.QueryParams.Set("type", utils.QueryParameterToString(r.type_)) + conf.queryParams.Set("type", utils.QueryParameterToString(r.type_)) } if !utils.IsNilOrEmpty(r.authenticationID) { - options.QueryParams.Set("authenticationID", utils.QueryParameterToString(r.authenticationID)) + conf.queryParams.Set("authenticationID", utils.QueryParameterToString(r.authenticationID)) } if !utils.IsNilOrEmpty(r.sort) { - options.QueryParams.Set("sort", utils.QueryParameterToString(r.sort)) + conf.queryParams.Set("sort", utils.QueryParameterToString(r.sort)) } if !utils.IsNilOrEmpty(r.order) { - options.QueryParams.Set("order", utils.QueryParameterToString(r.order)) + conf.queryParams.Set("order", utils.QueryParameterToString(r.order)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -4041,7 +4076,7 @@ Request can be constructed by NewApiGetSourcesRequest with parameters below. @param order OrderKeys - Sort order of the response, ascending or descending. @return ListSourcesResponse */ -func (c *APIClient) GetSources(r ApiGetSourcesRequest, opts ...utils.RequestOption) (*ListSourcesResponse, error) { +func (c *APIClient) GetSources(r ApiGetSourcesRequest, opts ...RequestOption) (*ListSourcesResponse, error) { var returnValue *ListSourcesResponse res, resBody, err := c.GetSourcesWithHTTPInfo(r, opts...) @@ -4119,12 +4154,12 @@ GetTask calls the API and returns the raw response from it. Request can be constructed by NewApiGetTaskRequest with parameters below. @param taskID string - Unique identifier of a task. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetTaskWithHTTPInfo(r ApiGetTaskRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetTaskWithHTTPInfo(r ApiGetTaskRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/tasks/{taskID}" requestPath = strings.ReplaceAll(requestPath, "{taskID}", url.PathEscape(utils.ParameterToString(r.taskID))) @@ -4132,20 +4167,20 @@ func (c *APIClient) GetTaskWithHTTPInfo(r ApiGetTaskRequest, opts ...utils.Reque return nil, nil, reportError("Parameter `taskID` is required when calling `GetTask`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -4168,7 +4203,7 @@ Request can be constructed by NewApiGetTaskRequest with parameters below. @param taskID string - Unique identifier of a task. @return Task */ -func (c *APIClient) GetTask(r ApiGetTaskRequest, opts ...utils.RequestOption) (*Task, error) { +func (c *APIClient) GetTask(r ApiGetTaskRequest, opts ...RequestOption) (*Task, error) { var returnValue *Task res, resBody, err := c.GetTaskWithHTTPInfo(r, opts...) @@ -4386,56 +4421,56 @@ GetTasks calls the API and returns the raw response from it. @param triggerType []TriggerType - Type of task trigger for filtering the list of tasks. @param sort TaskSortKeys - Property by which to sort the list of tasks. @param order OrderKeys - Sort order of the response, ascending or descending. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetTasksWithHTTPInfo(r ApiGetTasksRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetTasksWithHTTPInfo(r ApiGetTasksRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/tasks" - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.itemsPerPage) { - options.QueryParams.Set("itemsPerPage", utils.QueryParameterToString(*r.itemsPerPage)) + conf.queryParams.Set("itemsPerPage", utils.QueryParameterToString(*r.itemsPerPage)) } if !utils.IsNilOrEmpty(r.page) { - options.QueryParams.Set("page", utils.QueryParameterToString(*r.page)) + conf.queryParams.Set("page", utils.QueryParameterToString(*r.page)) } if !utils.IsNilOrEmpty(r.action) { - options.QueryParams.Set("action", utils.QueryParameterToString(r.action)) + conf.queryParams.Set("action", utils.QueryParameterToString(r.action)) } if !utils.IsNilOrEmpty(r.enabled) { - options.QueryParams.Set("enabled", utils.QueryParameterToString(*r.enabled)) + conf.queryParams.Set("enabled", utils.QueryParameterToString(*r.enabled)) } if !utils.IsNilOrEmpty(r.sourceID) { - options.QueryParams.Set("sourceID", utils.QueryParameterToString(r.sourceID)) + conf.queryParams.Set("sourceID", utils.QueryParameterToString(r.sourceID)) } if !utils.IsNilOrEmpty(r.destinationID) { - options.QueryParams.Set("destinationID", utils.QueryParameterToString(r.destinationID)) + conf.queryParams.Set("destinationID", utils.QueryParameterToString(r.destinationID)) } if !utils.IsNilOrEmpty(r.triggerType) { - options.QueryParams.Set("triggerType", utils.QueryParameterToString(r.triggerType)) + conf.queryParams.Set("triggerType", utils.QueryParameterToString(r.triggerType)) } if !utils.IsNilOrEmpty(r.sort) { - options.QueryParams.Set("sort", utils.QueryParameterToString(r.sort)) + conf.queryParams.Set("sort", utils.QueryParameterToString(r.sort)) } if !utils.IsNilOrEmpty(r.order) { - options.QueryParams.Set("order", utils.QueryParameterToString(r.order)) + conf.queryParams.Set("order", utils.QueryParameterToString(r.order)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -4466,7 +4501,7 @@ Request can be constructed by NewApiGetTasksRequest with parameters below. @param order OrderKeys - Sort order of the response, ascending or descending. @return ListTasksResponse */ -func (c *APIClient) GetTasks(r ApiGetTasksRequest, opts ...utils.RequestOption) (*ListTasksResponse, error) { +func (c *APIClient) GetTasks(r ApiGetTasksRequest, opts ...RequestOption) (*ListTasksResponse, error) { var returnValue *ListTasksResponse res, resBody, err := c.GetTasksWithHTTPInfo(r, opts...) @@ -4544,12 +4579,12 @@ GetTransformation calls the API and returns the raw response from it. Request can be constructed by NewApiGetTransformationRequest with parameters below. @param transformationID string - Unique identifier of a transformation. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetTransformationWithHTTPInfo(r ApiGetTransformationRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetTransformationWithHTTPInfo(r ApiGetTransformationRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/transformations/{transformationID}" requestPath = strings.ReplaceAll(requestPath, "{transformationID}", url.PathEscape(utils.ParameterToString(r.transformationID))) @@ -4557,20 +4592,20 @@ func (c *APIClient) GetTransformationWithHTTPInfo(r ApiGetTransformationRequest, return nil, nil, reportError("Parameter `transformationID` is required when calling `GetTransformation`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -4593,7 +4628,7 @@ Request can be constructed by NewApiGetTransformationRequest with parameters bel @param transformationID string - Unique identifier of a transformation. @return Transformation */ -func (c *APIClient) GetTransformation(r ApiGetTransformationRequest, opts ...utils.RequestOption) (*Transformation, error) { +func (c *APIClient) GetTransformation(r ApiGetTransformationRequest, opts ...RequestOption) (*Transformation, error) { var returnValue *Transformation res, resBody, err := c.GetTransformationWithHTTPInfo(r, opts...) @@ -4692,35 +4727,35 @@ GetTransformations calls the API and returns the raw response from it. Request can be constructed by NewApiGetTransformationsRequest with parameters below. @param sort SortKeys - Property by which to sort the list. @param order OrderKeys - Sort order of the response, ascending or descending. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetTransformationsWithHTTPInfo(r ApiGetTransformationsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetTransformationsWithHTTPInfo(r ApiGetTransformationsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/transformations" - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.sort) { - options.QueryParams.Set("sort", utils.QueryParameterToString(r.sort)) + conf.queryParams.Set("sort", utils.QueryParameterToString(r.sort)) } if !utils.IsNilOrEmpty(r.order) { - options.QueryParams.Set("order", utils.QueryParameterToString(r.order)) + conf.queryParams.Set("order", utils.QueryParameterToString(r.order)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -4744,7 +4779,7 @@ Request can be constructed by NewApiGetTransformationsRequest with parameters be @param order OrderKeys - Sort order of the response, ascending or descending. @return ListTransformationsResponse */ -func (c *APIClient) GetTransformations(r ApiGetTransformationsRequest, opts ...utils.RequestOption) (*ListTransformationsResponse, error) { +func (c *APIClient) GetTransformations(r ApiGetTransformationsRequest, opts ...RequestOption) (*ListTransformationsResponse, error) { var returnValue *ListTransformationsResponse res, resBody, err := c.GetTransformationsWithHTTPInfo(r, opts...) @@ -4822,12 +4857,12 @@ RunTask calls the API and returns the raw response from it. Request can be constructed by NewApiRunTaskRequest with parameters below. @param taskID string - Unique identifier of a task. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) RunTaskWithHTTPInfo(r ApiRunTaskRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) RunTaskWithHTTPInfo(r ApiRunTaskRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/tasks/{taskID}/run" requestPath = strings.ReplaceAll(requestPath, "{taskID}", url.PathEscape(utils.ParameterToString(r.taskID))) @@ -4835,20 +4870,20 @@ func (c *APIClient) RunTaskWithHTTPInfo(r ApiRunTaskRequest, opts ...utils.Reque return nil, nil, reportError("Parameter `taskID` is required when calling `RunTask`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -4871,7 +4906,7 @@ Request can be constructed by NewApiRunTaskRequest with parameters below. @param taskID string - Unique identifier of a task. @return RunResponse */ -func (c *APIClient) RunTask(r ApiRunTaskRequest, opts ...utils.RequestOption) (*RunResponse, error) { +func (c *APIClient) RunTask(r ApiRunTaskRequest, opts ...RequestOption) (*RunResponse, error) { var returnValue *RunResponse res, resBody, err := c.RunTaskWithHTTPInfo(r, opts...) @@ -4954,34 +4989,34 @@ SearchAuthentications calls the API and returns the raw response from it. Request can be constructed by NewApiSearchAuthenticationsRequest with parameters below. @param authenticationSearch AuthenticationSearch - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) SearchAuthenticationsWithHTTPInfo(r ApiSearchAuthenticationsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) SearchAuthenticationsWithHTTPInfo(r ApiSearchAuthenticationsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/authentications/search" if r.authenticationSearch == nil { return nil, nil, reportError("Parameter `authenticationSearch` is required when calling `SearchAuthentications`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.authenticationSearch - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -5004,7 +5039,7 @@ Request can be constructed by NewApiSearchAuthenticationsRequest with parameters @param authenticationSearch AuthenticationSearch @return []Authentication */ -func (c *APIClient) SearchAuthentications(r ApiSearchAuthenticationsRequest, opts ...utils.RequestOption) ([]Authentication, error) { +func (c *APIClient) SearchAuthentications(r ApiSearchAuthenticationsRequest, opts ...RequestOption) ([]Authentication, error) { var returnValue []Authentication res, resBody, err := c.SearchAuthenticationsWithHTTPInfo(r, opts...) @@ -5087,34 +5122,34 @@ SearchDestinations calls the API and returns the raw response from it. Request can be constructed by NewApiSearchDestinationsRequest with parameters below. @param destinationSearch DestinationSearch - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) SearchDestinationsWithHTTPInfo(r ApiSearchDestinationsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) SearchDestinationsWithHTTPInfo(r ApiSearchDestinationsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/destinations/search" if r.destinationSearch == nil { return nil, nil, reportError("Parameter `destinationSearch` is required when calling `SearchDestinations`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.destinationSearch - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -5137,7 +5172,7 @@ Request can be constructed by NewApiSearchDestinationsRequest with parameters be @param destinationSearch DestinationSearch @return []Destination */ -func (c *APIClient) SearchDestinations(r ApiSearchDestinationsRequest, opts ...utils.RequestOption) ([]Destination, error) { +func (c *APIClient) SearchDestinations(r ApiSearchDestinationsRequest, opts ...RequestOption) ([]Destination, error) { var returnValue []Destination res, resBody, err := c.SearchDestinationsWithHTTPInfo(r, opts...) @@ -5220,34 +5255,34 @@ SearchSources calls the API and returns the raw response from it. Request can be constructed by NewApiSearchSourcesRequest with parameters below. @param sourceSearch SourceSearch - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) SearchSourcesWithHTTPInfo(r ApiSearchSourcesRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) SearchSourcesWithHTTPInfo(r ApiSearchSourcesRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/sources/search" if r.sourceSearch == nil { return nil, nil, reportError("Parameter `sourceSearch` is required when calling `SearchSources`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.sourceSearch - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -5270,7 +5305,7 @@ Request can be constructed by NewApiSearchSourcesRequest with parameters below. @param sourceSearch SourceSearch @return []Source */ -func (c *APIClient) SearchSources(r ApiSearchSourcesRequest, opts ...utils.RequestOption) ([]Source, error) { +func (c *APIClient) SearchSources(r ApiSearchSourcesRequest, opts ...RequestOption) ([]Source, error) { var returnValue []Source res, resBody, err := c.SearchSourcesWithHTTPInfo(r, opts...) @@ -5353,34 +5388,34 @@ SearchTasks calls the API and returns the raw response from it. Request can be constructed by NewApiSearchTasksRequest with parameters below. @param taskSearch TaskSearch - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) SearchTasksWithHTTPInfo(r ApiSearchTasksRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) SearchTasksWithHTTPInfo(r ApiSearchTasksRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/tasks/search" if r.taskSearch == nil { return nil, nil, reportError("Parameter `taskSearch` is required when calling `SearchTasks`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.taskSearch - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -5403,7 +5438,7 @@ Request can be constructed by NewApiSearchTasksRequest with parameters below. @param taskSearch TaskSearch @return []Task */ -func (c *APIClient) SearchTasks(r ApiSearchTasksRequest, opts ...utils.RequestOption) ([]Task, error) { +func (c *APIClient) SearchTasks(r ApiSearchTasksRequest, opts ...RequestOption) ([]Task, error) { var returnValue []Task res, resBody, err := c.SearchTasksWithHTTPInfo(r, opts...) @@ -5486,34 +5521,34 @@ SearchTransformations calls the API and returns the raw response from it. Request can be constructed by NewApiSearchTransformationsRequest with parameters below. @param transformationSearch TransformationSearch - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) SearchTransformationsWithHTTPInfo(r ApiSearchTransformationsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) SearchTransformationsWithHTTPInfo(r ApiSearchTransformationsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/transformations/search" if r.transformationSearch == nil { return nil, nil, reportError("Parameter `transformationSearch` is required when calling `SearchTransformations`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.transformationSearch - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -5536,7 +5571,7 @@ Request can be constructed by NewApiSearchTransformationsRequest with parameters @param transformationSearch TransformationSearch @return []Transformation */ -func (c *APIClient) SearchTransformations(r ApiSearchTransformationsRequest, opts ...utils.RequestOption) ([]Transformation, error) { +func (c *APIClient) SearchTransformations(r ApiSearchTransformationsRequest, opts ...RequestOption) ([]Transformation, error) { var returnValue []Transformation res, resBody, err := c.SearchTransformationsWithHTTPInfo(r, opts...) @@ -5616,12 +5651,12 @@ Triggering stream-listing requests only works with sources with `type: docker` a Request can be constructed by NewApiTriggerDockerSourceDiscoverRequest with parameters below. @param sourceID string - Unique identifier of a source. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) TriggerDockerSourceDiscoverWithHTTPInfo(r ApiTriggerDockerSourceDiscoverRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) TriggerDockerSourceDiscoverWithHTTPInfo(r ApiTriggerDockerSourceDiscoverRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/sources/{sourceID}/discover" requestPath = strings.ReplaceAll(requestPath, "{sourceID}", url.PathEscape(utils.ParameterToString(r.sourceID))) @@ -5629,20 +5664,20 @@ func (c *APIClient) TriggerDockerSourceDiscoverWithHTTPInfo(r ApiTriggerDockerSo return nil, nil, reportError("Parameter `sourceID` is required when calling `TriggerDockerSourceDiscover`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -5666,7 +5701,7 @@ Request can be constructed by NewApiTriggerDockerSourceDiscoverRequest with para @param sourceID string - Unique identifier of a source. @return SourceWatchResponse */ -func (c *APIClient) TriggerDockerSourceDiscover(r ApiTriggerDockerSourceDiscoverRequest, opts ...utils.RequestOption) (*SourceWatchResponse, error) { +func (c *APIClient) TriggerDockerSourceDiscover(r ApiTriggerDockerSourceDiscoverRequest, opts ...RequestOption) (*SourceWatchResponse, error) { var returnValue *SourceWatchResponse res, resBody, err := c.TriggerDockerSourceDiscoverWithHTTPInfo(r, opts...) @@ -5749,34 +5784,34 @@ TryTransformations calls the API and returns the raw response from it. Request can be constructed by NewApiTryTransformationsRequest with parameters below. @param transformationTry TransformationTry - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) TryTransformationsWithHTTPInfo(r ApiTryTransformationsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) TryTransformationsWithHTTPInfo(r ApiTryTransformationsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/transformations/try" if r.transformationTry == nil { return nil, nil, reportError("Parameter `transformationTry` is required when calling `TryTransformations`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.transformationTry - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -5799,7 +5834,7 @@ Request can be constructed by NewApiTryTransformationsRequest with parameters be @param transformationTry TransformationTry @return TransformationTryResponse */ -func (c *APIClient) TryTransformations(r ApiTryTransformationsRequest, opts ...utils.RequestOption) (*TransformationTryResponse, error) { +func (c *APIClient) TryTransformations(r ApiTryTransformationsRequest, opts ...RequestOption) (*TransformationTryResponse, error) { var returnValue *TransformationTryResponse res, resBody, err := c.TryTransformationsWithHTTPInfo(r, opts...) @@ -5894,12 +5929,12 @@ UpdateAuthentication calls the API and returns the raw response from it. Request can be constructed by NewApiUpdateAuthenticationRequest with parameters below. @param authenticationID string - Unique identifier of an authentication resource. @param authenticationUpdate AuthenticationUpdate - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) UpdateAuthenticationWithHTTPInfo(r ApiUpdateAuthenticationRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) UpdateAuthenticationWithHTTPInfo(r ApiUpdateAuthenticationRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/authentications/{authenticationID}" requestPath = strings.ReplaceAll(requestPath, "{authenticationID}", url.PathEscape(utils.ParameterToString(r.authenticationID))) @@ -5911,22 +5946,22 @@ func (c *APIClient) UpdateAuthenticationWithHTTPInfo(r ApiUpdateAuthenticationRe return nil, nil, reportError("Parameter `authenticationUpdate` is required when calling `UpdateAuthentication`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.authenticationUpdate - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPatch, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPatch, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -5950,7 +5985,7 @@ Request can be constructed by NewApiUpdateAuthenticationRequest with parameters @param authenticationUpdate AuthenticationUpdate @return AuthenticationUpdateResponse */ -func (c *APIClient) UpdateAuthentication(r ApiUpdateAuthenticationRequest, opts ...utils.RequestOption) (*AuthenticationUpdateResponse, error) { +func (c *APIClient) UpdateAuthentication(r ApiUpdateAuthenticationRequest, opts ...RequestOption) (*AuthenticationUpdateResponse, error) { var returnValue *AuthenticationUpdateResponse res, resBody, err := c.UpdateAuthenticationWithHTTPInfo(r, opts...) @@ -6045,12 +6080,12 @@ UpdateDestination calls the API and returns the raw response from it. Request can be constructed by NewApiUpdateDestinationRequest with parameters below. @param destinationID string - Unique identifier of a destination. @param destinationUpdate DestinationUpdate - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) UpdateDestinationWithHTTPInfo(r ApiUpdateDestinationRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) UpdateDestinationWithHTTPInfo(r ApiUpdateDestinationRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/destinations/{destinationID}" requestPath = strings.ReplaceAll(requestPath, "{destinationID}", url.PathEscape(utils.ParameterToString(r.destinationID))) @@ -6062,22 +6097,22 @@ func (c *APIClient) UpdateDestinationWithHTTPInfo(r ApiUpdateDestinationRequest, return nil, nil, reportError("Parameter `destinationUpdate` is required when calling `UpdateDestination`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.destinationUpdate - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPatch, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPatch, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -6101,7 +6136,7 @@ Request can be constructed by NewApiUpdateDestinationRequest with parameters bel @param destinationUpdate DestinationUpdate @return DestinationUpdateResponse */ -func (c *APIClient) UpdateDestination(r ApiUpdateDestinationRequest, opts ...utils.RequestOption) (*DestinationUpdateResponse, error) { +func (c *APIClient) UpdateDestination(r ApiUpdateDestinationRequest, opts ...RequestOption) (*DestinationUpdateResponse, error) { var returnValue *DestinationUpdateResponse res, resBody, err := c.UpdateDestinationWithHTTPInfo(r, opts...) @@ -6196,12 +6231,12 @@ UpdateSource calls the API and returns the raw response from it. Request can be constructed by NewApiUpdateSourceRequest with parameters below. @param sourceID string - Unique identifier of a source. @param sourceUpdate SourceUpdate - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) UpdateSourceWithHTTPInfo(r ApiUpdateSourceRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) UpdateSourceWithHTTPInfo(r ApiUpdateSourceRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/sources/{sourceID}" requestPath = strings.ReplaceAll(requestPath, "{sourceID}", url.PathEscape(utils.ParameterToString(r.sourceID))) @@ -6213,22 +6248,22 @@ func (c *APIClient) UpdateSourceWithHTTPInfo(r ApiUpdateSourceRequest, opts ...u return nil, nil, reportError("Parameter `sourceUpdate` is required when calling `UpdateSource`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.sourceUpdate - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPatch, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPatch, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -6252,7 +6287,7 @@ Request can be constructed by NewApiUpdateSourceRequest with parameters below. @param sourceUpdate SourceUpdate @return SourceUpdateResponse */ -func (c *APIClient) UpdateSource(r ApiUpdateSourceRequest, opts ...utils.RequestOption) (*SourceUpdateResponse, error) { +func (c *APIClient) UpdateSource(r ApiUpdateSourceRequest, opts ...RequestOption) (*SourceUpdateResponse, error) { var returnValue *SourceUpdateResponse res, resBody, err := c.UpdateSourceWithHTTPInfo(r, opts...) @@ -6343,12 +6378,12 @@ UpdateTask calls the API and returns the raw response from it. Request can be constructed by NewApiUpdateTaskRequest with parameters below. @param taskID string - Unique identifier of a task. @param taskUpdate TaskUpdate - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) UpdateTaskWithHTTPInfo(r ApiUpdateTaskRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) UpdateTaskWithHTTPInfo(r ApiUpdateTaskRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/tasks/{taskID}" requestPath = strings.ReplaceAll(requestPath, "{taskID}", url.PathEscape(utils.ParameterToString(r.taskID))) @@ -6360,22 +6395,22 @@ func (c *APIClient) UpdateTaskWithHTTPInfo(r ApiUpdateTaskRequest, opts ...utils return nil, nil, reportError("Parameter `taskUpdate` is required when calling `UpdateTask`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.taskUpdate - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPatch, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPatch, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -6394,7 +6429,7 @@ Request can be constructed by NewApiUpdateTaskRequest with parameters below. @param taskUpdate TaskUpdate @return TaskUpdateResponse */ -func (c *APIClient) UpdateTask(r ApiUpdateTaskRequest, opts ...utils.RequestOption) (*TaskUpdateResponse, error) { +func (c *APIClient) UpdateTask(r ApiUpdateTaskRequest, opts ...RequestOption) (*TaskUpdateResponse, error) { var returnValue *TaskUpdateResponse res, resBody, err := c.UpdateTaskWithHTTPInfo(r, opts...) @@ -6485,12 +6520,12 @@ UpdateTransformation calls the API and returns the raw response from it. Request can be constructed by NewApiUpdateTransformationRequest with parameters below. @param transformationID string - Unique identifier of a transformation. @param transformationCreate TransformationCreate - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) UpdateTransformationWithHTTPInfo(r ApiUpdateTransformationRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) UpdateTransformationWithHTTPInfo(r ApiUpdateTransformationRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/transformations/{transformationID}" requestPath = strings.ReplaceAll(requestPath, "{transformationID}", url.PathEscape(utils.ParameterToString(r.transformationID))) @@ -6502,22 +6537,22 @@ func (c *APIClient) UpdateTransformationWithHTTPInfo(r ApiUpdateTransformationRe return nil, nil, reportError("Parameter `transformationCreate` is required when calling `UpdateTransformation`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.transformationCreate - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPut, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPut, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -6536,7 +6571,7 @@ Request can be constructed by NewApiUpdateTransformationRequest with parameters @param transformationCreate TransformationCreate @return TransformationUpdateResponse */ -func (c *APIClient) UpdateTransformation(r ApiUpdateTransformationRequest, opts ...utils.RequestOption) (*TransformationUpdateResponse, error) { +func (c *APIClient) UpdateTransformation(r ApiUpdateTransformationRequest, opts ...RequestOption) (*TransformationUpdateResponse, error) { var returnValue *TransformationUpdateResponse res, resBody, err := c.UpdateTransformationWithHTTPInfo(r, opts...) @@ -6619,23 +6654,23 @@ ValidateSource calls the API and returns the raw response from it. Request can be constructed by NewApiValidateSourceRequest with parameters below. @param sourceCreate SourceCreate - - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) ValidateSourceWithHTTPInfo(r ApiValidateSourceRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) ValidateSourceWithHTTPInfo(r ApiValidateSourceRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/sources/validate" - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any @@ -6646,7 +6681,7 @@ func (c *APIClient) ValidateSourceWithHTTPInfo(r ApiValidateSourceRequest, opts } else { postBody = r.sourceCreate } - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -6669,7 +6704,7 @@ Request can be constructed by NewApiValidateSourceRequest with parameters below. @param sourceCreate SourceCreate - @return SourceWatchResponse */ -func (c *APIClient) ValidateSource(r ApiValidateSourceRequest, opts ...utils.RequestOption) (*SourceWatchResponse, error) { +func (c *APIClient) ValidateSource(r ApiValidateSourceRequest, opts ...RequestOption) (*SourceWatchResponse, error) { var returnValue *SourceWatchResponse res, resBody, err := c.ValidateSourceWithHTTPInfo(r, opts...) @@ -6765,12 +6800,12 @@ ValidateSourceBeforeUpdate calls the API and returns the raw response from it. Request can be constructed by NewApiValidateSourceBeforeUpdateRequest with parameters below. @param sourceID string - Unique identifier of a source. @param sourceUpdate SourceUpdate - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) ValidateSourceBeforeUpdateWithHTTPInfo(r ApiValidateSourceBeforeUpdateRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) ValidateSourceBeforeUpdateWithHTTPInfo(r ApiValidateSourceBeforeUpdateRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/sources/{sourceID}/validate" requestPath = strings.ReplaceAll(requestPath, "{sourceID}", url.PathEscape(utils.ParameterToString(r.sourceID))) @@ -6782,22 +6817,22 @@ func (c *APIClient) ValidateSourceBeforeUpdateWithHTTPInfo(r ApiValidateSourceBe return nil, nil, reportError("Parameter `sourceUpdate` is required when calling `ValidateSourceBeforeUpdate`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.sourceUpdate - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -6821,7 +6856,7 @@ Request can be constructed by NewApiValidateSourceBeforeUpdateRequest with param @param sourceUpdate SourceUpdate @return SourceWatchResponse */ -func (c *APIClient) ValidateSourceBeforeUpdate(r ApiValidateSourceBeforeUpdateRequest, opts ...utils.RequestOption) (*SourceWatchResponse, error) { +func (c *APIClient) ValidateSourceBeforeUpdate(r ApiValidateSourceBeforeUpdateRequest, opts ...RequestOption) (*SourceWatchResponse, error) { var returnValue *SourceWatchResponse res, resBody, err := c.ValidateSourceBeforeUpdateWithHTTPInfo(r, opts...) diff --git a/clients/algoliasearch-client-go/algolia/insights/api_insights.go b/clients/algoliasearch-client-go/algolia/insights/api_insights.go index 03396faef1..b310f62285 100644 --- a/clients/algoliasearch-client-go/algolia/insights/api_insights.go +++ b/clients/algoliasearch-client-go/algolia/insights/api_insights.go @@ -12,6 +12,41 @@ import ( "github.com/algolia/algoliasearch-client-go/v4/algolia/utils" ) +type config struct { + // -- Request options for API calls + context context.Context + queryParams url.Values + headerParams map[string]string +} + +type RequestOption interface { + apply(*config) +} + +type requestOption func(*config) + +func (r requestOption) apply(c *config) { + r(c) +} + +func WithContext(ctx context.Context) requestOption { + return requestOption(func(c *config) { + c.context = ctx + }) +} + +func WithHeaderParam(key string, value any) requestOption { + return requestOption(func(c *config) { + c.headerParams[key] = utils.ParameterToString(value) + }) +} + +func WithQueryParam(key string, value any) requestOption { + return requestOption(func(c *config) { + c.queryParams.Set(utils.QueryParameterToString(key), utils.QueryParameterToString(value)) + }) +} + func (r *ApiCustomDeleteRequest) UnmarshalJSON(b []byte) error { req := map[string]json.RawMessage{} err := json.Unmarshal(b, &req) @@ -68,12 +103,12 @@ CustomDelete calls the API and returns the raw response from it. Request can be constructed by NewApiCustomDeleteRequest with parameters below. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomDeleteWithHTTPInfo(r ApiCustomDeleteRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomDeleteWithHTTPInfo(r ApiCustomDeleteRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -81,26 +116,26 @@ func (c *APIClient) CustomDeleteWithHTTPInfo(r ApiCustomDeleteRequest, opts ...u return nil, nil, reportError("Parameter `path` is required when calling `CustomDelete`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodDelete, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodDelete, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -119,7 +154,7 @@ Request can be constructed by NewApiCustomDeleteRequest with parameters below. @param parameters map[string]any - Query parameters to apply to the current query. @return map[string]any */ -func (c *APIClient) CustomDelete(r ApiCustomDeleteRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomDelete(r ApiCustomDeleteRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomDeleteWithHTTPInfo(r, opts...) @@ -210,12 +245,12 @@ CustomGet calls the API and returns the raw response from it. Request can be constructed by NewApiCustomGetRequest with parameters below. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomGetWithHTTPInfo(r ApiCustomGetRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomGetWithHTTPInfo(r ApiCustomGetRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -223,26 +258,26 @@ func (c *APIClient) CustomGetWithHTTPInfo(r ApiCustomGetRequest, opts ...utils.R return nil, nil, reportError("Parameter `path` is required when calling `CustomGet`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -261,7 +296,7 @@ Request can be constructed by NewApiCustomGetRequest with parameters below. @param parameters map[string]any - Query parameters to apply to the current query. @return map[string]any */ -func (c *APIClient) CustomGet(r ApiCustomGetRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomGet(r ApiCustomGetRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomGetWithHTTPInfo(r, opts...) @@ -369,12 +404,12 @@ CustomPost calls the API and returns the raw response from it. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. @param body map[string]any - Parameters to send with the custom request. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -382,21 +417,21 @@ func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...utils return nil, nil, reportError("Parameter `path` is required when calling `CustomPost`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any @@ -407,7 +442,7 @@ func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...utils } else { postBody = r.body } - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -427,7 +462,7 @@ Request can be constructed by NewApiCustomPostRequest with parameters below. @param body map[string]any - Parameters to send with the custom request. @return map[string]any */ -func (c *APIClient) CustomPost(r ApiCustomPostRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomPost(r ApiCustomPostRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomPostWithHTTPInfo(r, opts...) @@ -535,12 +570,12 @@ CustomPut calls the API and returns the raw response from it. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. @param body map[string]any - Parameters to send with the custom request. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -548,21 +583,21 @@ func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...utils.R return nil, nil, reportError("Parameter `path` is required when calling `CustomPut`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any @@ -573,7 +608,7 @@ func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...utils.R } else { postBody = r.body } - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPut, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPut, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -593,7 +628,7 @@ Request can be constructed by NewApiCustomPutRequest with parameters below. @param body map[string]any - Parameters to send with the custom request. @return map[string]any */ -func (c *APIClient) CustomPut(r ApiCustomPutRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomPut(r ApiCustomPutRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomPutWithHTTPInfo(r, opts...) @@ -668,12 +703,12 @@ To delete a personalization user profile, see [Delete a user profile](/specs/per Request can be constructed by NewApiDeleteUserTokenRequest with parameters below. @param userToken string - User token for which to delete all associated events. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) DeleteUserTokenWithHTTPInfo(r ApiDeleteUserTokenRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) DeleteUserTokenWithHTTPInfo(r ApiDeleteUserTokenRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/usertokens/{userToken}" requestPath = strings.ReplaceAll(requestPath, "{userToken}", url.PathEscape(utils.ParameterToString(r.userToken))) @@ -687,20 +722,20 @@ func (c *APIClient) DeleteUserTokenWithHTTPInfo(r ApiDeleteUserTokenRequest, opt return nil, nil, reportError("userToken must have less than 129 elements") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodDelete, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodDelete, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -718,7 +753,7 @@ Request can be constructed by NewApiDeleteUserTokenRequest with parameters below @param userToken string - User token for which to delete all associated events. */ -func (c *APIClient) DeleteUserToken(r ApiDeleteUserTokenRequest, opts ...utils.RequestOption) error { +func (c *APIClient) DeleteUserToken(r ApiDeleteUserTokenRequest, opts ...RequestOption) error { res, resBody, err := c.DeleteUserTokenWithHTTPInfo(r, opts...) if err != nil { return err @@ -792,34 +827,34 @@ but the request body must be smaller than 2 MB. Request can be constructed by NewApiPushEventsRequest with parameters below. @param insightsEvents InsightsEvents - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) PushEventsWithHTTPInfo(r ApiPushEventsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) PushEventsWithHTTPInfo(r ApiPushEventsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/events" if r.insightsEvents == nil { return nil, nil, reportError("Parameter `insightsEvents` is required when calling `PushEvents`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.insightsEvents - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -840,7 +875,7 @@ Request can be constructed by NewApiPushEventsRequest with parameters below. @param insightsEvents InsightsEvents @return EventsResponse */ -func (c *APIClient) PushEvents(r ApiPushEventsRequest, opts ...utils.RequestOption) (*EventsResponse, error) { +func (c *APIClient) PushEvents(r ApiPushEventsRequest, opts ...RequestOption) (*EventsResponse, error) { var returnValue *EventsResponse res, resBody, err := c.PushEventsWithHTTPInfo(r, opts...) diff --git a/clients/algoliasearch-client-go/algolia/monitoring/api_monitoring.go b/clients/algoliasearch-client-go/algolia/monitoring/api_monitoring.go index 36645bb95a..6d8e4f6ffc 100644 --- a/clients/algoliasearch-client-go/algolia/monitoring/api_monitoring.go +++ b/clients/algoliasearch-client-go/algolia/monitoring/api_monitoring.go @@ -12,6 +12,41 @@ import ( "github.com/algolia/algoliasearch-client-go/v4/algolia/utils" ) +type config struct { + // -- Request options for API calls + context context.Context + queryParams url.Values + headerParams map[string]string +} + +type RequestOption interface { + apply(*config) +} + +type requestOption func(*config) + +func (r requestOption) apply(c *config) { + r(c) +} + +func WithContext(ctx context.Context) requestOption { + return requestOption(func(c *config) { + c.context = ctx + }) +} + +func WithHeaderParam(key string, value any) requestOption { + return requestOption(func(c *config) { + c.headerParams[key] = utils.ParameterToString(value) + }) +} + +func WithQueryParam(key string, value any) requestOption { + return requestOption(func(c *config) { + c.queryParams.Set(utils.QueryParameterToString(key), utils.QueryParameterToString(value)) + }) +} + func (r *ApiCustomDeleteRequest) UnmarshalJSON(b []byte) error { req := map[string]json.RawMessage{} err := json.Unmarshal(b, &req) @@ -68,12 +103,12 @@ CustomDelete calls the API and returns the raw response from it. Request can be constructed by NewApiCustomDeleteRequest with parameters below. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomDeleteWithHTTPInfo(r ApiCustomDeleteRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomDeleteWithHTTPInfo(r ApiCustomDeleteRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -81,26 +116,26 @@ func (c *APIClient) CustomDeleteWithHTTPInfo(r ApiCustomDeleteRequest, opts ...u return nil, nil, reportError("Parameter `path` is required when calling `CustomDelete`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodDelete, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodDelete, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -119,7 +154,7 @@ Request can be constructed by NewApiCustomDeleteRequest with parameters below. @param parameters map[string]any - Query parameters to apply to the current query. @return map[string]any */ -func (c *APIClient) CustomDelete(r ApiCustomDeleteRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomDelete(r ApiCustomDeleteRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomDeleteWithHTTPInfo(r, opts...) @@ -210,12 +245,12 @@ CustomGet calls the API and returns the raw response from it. Request can be constructed by NewApiCustomGetRequest with parameters below. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomGetWithHTTPInfo(r ApiCustomGetRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomGetWithHTTPInfo(r ApiCustomGetRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -223,26 +258,26 @@ func (c *APIClient) CustomGetWithHTTPInfo(r ApiCustomGetRequest, opts ...utils.R return nil, nil, reportError("Parameter `path` is required when calling `CustomGet`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -261,7 +296,7 @@ Request can be constructed by NewApiCustomGetRequest with parameters below. @param parameters map[string]any - Query parameters to apply to the current query. @return map[string]any */ -func (c *APIClient) CustomGet(r ApiCustomGetRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomGet(r ApiCustomGetRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomGetWithHTTPInfo(r, opts...) @@ -369,12 +404,12 @@ CustomPost calls the API and returns the raw response from it. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. @param body map[string]any - Parameters to send with the custom request. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -382,21 +417,21 @@ func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...utils return nil, nil, reportError("Parameter `path` is required when calling `CustomPost`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any @@ -407,7 +442,7 @@ func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...utils } else { postBody = r.body } - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -427,7 +462,7 @@ Request can be constructed by NewApiCustomPostRequest with parameters below. @param body map[string]any - Parameters to send with the custom request. @return map[string]any */ -func (c *APIClient) CustomPost(r ApiCustomPostRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomPost(r ApiCustomPostRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomPostWithHTTPInfo(r, opts...) @@ -535,12 +570,12 @@ CustomPut calls the API and returns the raw response from it. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. @param body map[string]any - Parameters to send with the custom request. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -548,21 +583,21 @@ func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...utils.R return nil, nil, reportError("Parameter `path` is required when calling `CustomPut`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any @@ -573,7 +608,7 @@ func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...utils.R } else { postBody = r.body } - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPut, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPut, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -593,7 +628,7 @@ Request can be constructed by NewApiCustomPutRequest with parameters below. @param body map[string]any - Parameters to send with the custom request. @return map[string]any */ -func (c *APIClient) CustomPut(r ApiCustomPutRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomPut(r ApiCustomPutRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomPutWithHTTPInfo(r, opts...) @@ -667,12 +702,12 @@ GetClusterIncidents calls the API and returns the raw response from it. Request can be constructed by NewApiGetClusterIncidentsRequest with parameters below. @param clusters string - Subset of clusters, separated by comma. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetClusterIncidentsWithHTTPInfo(r ApiGetClusterIncidentsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetClusterIncidentsWithHTTPInfo(r ApiGetClusterIncidentsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/incidents/{clusters}" requestPath = strings.ReplaceAll(requestPath, "{clusters}", url.PathEscape(utils.ParameterToString(r.clusters))) @@ -680,20 +715,20 @@ func (c *APIClient) GetClusterIncidentsWithHTTPInfo(r ApiGetClusterIncidentsRequ return nil, nil, reportError("Parameter `clusters` is required when calling `GetClusterIncidents`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -711,7 +746,7 @@ Request can be constructed by NewApiGetClusterIncidentsRequest with parameters b @param clusters string - Subset of clusters, separated by comma. @return IncidentsResponse */ -func (c *APIClient) GetClusterIncidents(r ApiGetClusterIncidentsRequest, opts ...utils.RequestOption) (*IncidentsResponse, error) { +func (c *APIClient) GetClusterIncidents(r ApiGetClusterIncidentsRequest, opts ...RequestOption) (*IncidentsResponse, error) { var returnValue *IncidentsResponse res, resBody, err := c.GetClusterIncidentsWithHTTPInfo(r, opts...) @@ -785,12 +820,12 @@ GetClusterStatus calls the API and returns the raw response from it. Request can be constructed by NewApiGetClusterStatusRequest with parameters below. @param clusters string - Subset of clusters, separated by comma. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetClusterStatusWithHTTPInfo(r ApiGetClusterStatusRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetClusterStatusWithHTTPInfo(r ApiGetClusterStatusRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/status/{clusters}" requestPath = strings.ReplaceAll(requestPath, "{clusters}", url.PathEscape(utils.ParameterToString(r.clusters))) @@ -798,20 +833,20 @@ func (c *APIClient) GetClusterStatusWithHTTPInfo(r ApiGetClusterStatusRequest, o return nil, nil, reportError("Parameter `clusters` is required when calling `GetClusterStatus`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -829,7 +864,7 @@ Request can be constructed by NewApiGetClusterStatusRequest with parameters belo @param clusters string - Subset of clusters, separated by comma. @return StatusResponse */ -func (c *APIClient) GetClusterStatus(r ApiGetClusterStatusRequest, opts ...utils.RequestOption) (*StatusResponse, error) { +func (c *APIClient) GetClusterStatus(r ApiGetClusterStatusRequest, opts ...RequestOption) (*StatusResponse, error) { var returnValue *StatusResponse res, resBody, err := c.GetClusterStatusWithHTTPInfo(r, opts...) @@ -871,28 +906,28 @@ GetIncidents calls the API and returns the raw response from it. Request can be constructed by NewApiGetIncidentsRequest with parameters below. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetIncidentsWithHTTPInfo(opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetIncidentsWithHTTPInfo(opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/incidents" - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -909,7 +944,7 @@ Request can be constructed by NewApiGetIncidentsRequest with parameters below. @return IncidentsResponse */ -func (c *APIClient) GetIncidents(opts ...utils.RequestOption) (*IncidentsResponse, error) { +func (c *APIClient) GetIncidents(opts ...RequestOption) (*IncidentsResponse, error) { var returnValue *IncidentsResponse res, resBody, err := c.GetIncidentsWithHTTPInfo(opts...) @@ -983,12 +1018,12 @@ GetIndexingTime calls the API and returns the raw response from it. Request can be constructed by NewApiGetIndexingTimeRequest with parameters below. @param clusters string - Subset of clusters, separated by comma. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetIndexingTimeWithHTTPInfo(r ApiGetIndexingTimeRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetIndexingTimeWithHTTPInfo(r ApiGetIndexingTimeRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexing/{clusters}" requestPath = strings.ReplaceAll(requestPath, "{clusters}", url.PathEscape(utils.ParameterToString(r.clusters))) @@ -996,20 +1031,20 @@ func (c *APIClient) GetIndexingTimeWithHTTPInfo(r ApiGetIndexingTimeRequest, opt return nil, nil, reportError("Parameter `clusters` is required when calling `GetIndexingTime`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1027,7 +1062,7 @@ Request can be constructed by NewApiGetIndexingTimeRequest with parameters below @param clusters string - Subset of clusters, separated by comma. @return IndexingTimeResponse */ -func (c *APIClient) GetIndexingTime(r ApiGetIndexingTimeRequest, opts ...utils.RequestOption) (*IndexingTimeResponse, error) { +func (c *APIClient) GetIndexingTime(r ApiGetIndexingTimeRequest, opts ...RequestOption) (*IndexingTimeResponse, error) { var returnValue *IndexingTimeResponse res, resBody, err := c.GetIndexingTimeWithHTTPInfo(r, opts...) @@ -1101,12 +1136,12 @@ GetLatency calls the API and returns the raw response from it. Request can be constructed by NewApiGetLatencyRequest with parameters below. @param clusters string - Subset of clusters, separated by comma. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetLatencyWithHTTPInfo(r ApiGetLatencyRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetLatencyWithHTTPInfo(r ApiGetLatencyRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/latency/{clusters}" requestPath = strings.ReplaceAll(requestPath, "{clusters}", url.PathEscape(utils.ParameterToString(r.clusters))) @@ -1114,20 +1149,20 @@ func (c *APIClient) GetLatencyWithHTTPInfo(r ApiGetLatencyRequest, opts ...utils return nil, nil, reportError("Parameter `clusters` is required when calling `GetLatency`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1145,7 +1180,7 @@ Request can be constructed by NewApiGetLatencyRequest with parameters below. @param clusters string - Subset of clusters, separated by comma. @return LatencyResponse */ -func (c *APIClient) GetLatency(r ApiGetLatencyRequest, opts ...utils.RequestOption) (*LatencyResponse, error) { +func (c *APIClient) GetLatency(r ApiGetLatencyRequest, opts ...RequestOption) (*LatencyResponse, error) { var returnValue *LatencyResponse res, resBody, err := c.GetLatencyWithHTTPInfo(r, opts...) @@ -1233,30 +1268,30 @@ You must authenticate requests with the `x-algolia-application-id` and `x-algoli Request can be constructed by NewApiGetMetricsRequest with parameters below. @param metric Metric - Metric to report. For more information about the individual metrics, see the description of the API response. To include all metrics, use `*`. @param period Period - Period over which to aggregate the metrics: - `minute`. Aggregate the last minute. 1 data point per 10 seconds. - `hour`. Aggregate the last hour. 1 data point per minute. - `day`. Aggregate the last day. 1 data point per 10 minutes. - `week`. Aggregate the last week. 1 data point per hour. - `month`. Aggregate the last month. 1 data point per day. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetMetricsWithHTTPInfo(r ApiGetMetricsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetMetricsWithHTTPInfo(r ApiGetMetricsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/infrastructure/{metric}/period/{period}" requestPath = strings.ReplaceAll(requestPath, "{metric}", url.PathEscape(utils.ParameterToString(r.metric))) requestPath = strings.ReplaceAll(requestPath, "{period}", url.PathEscape(utils.ParameterToString(r.period))) - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1278,7 +1313,7 @@ Request can be constructed by NewApiGetMetricsRequest with parameters below. @param period Period - Period over which to aggregate the metrics: - `minute`. Aggregate the last minute. 1 data point per 10 seconds. - `hour`. Aggregate the last hour. 1 data point per minute. - `day`. Aggregate the last day. 1 data point per 10 minutes. - `week`. Aggregate the last week. 1 data point per hour. - `month`. Aggregate the last month. 1 data point per day. @return InfrastructureResponse */ -func (c *APIClient) GetMetrics(r ApiGetMetricsRequest, opts ...utils.RequestOption) (*InfrastructureResponse, error) { +func (c *APIClient) GetMetrics(r ApiGetMetricsRequest, opts ...RequestOption) (*InfrastructureResponse, error) { var returnValue *InfrastructureResponse res, resBody, err := c.GetMetricsWithHTTPInfo(r, opts...) @@ -1352,12 +1387,12 @@ GetReachability calls the API and returns the raw response from it. Request can be constructed by NewApiGetReachabilityRequest with parameters below. @param clusters string - Subset of clusters, separated by comma. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetReachabilityWithHTTPInfo(r ApiGetReachabilityRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetReachabilityWithHTTPInfo(r ApiGetReachabilityRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/reachability/{clusters}/probes" requestPath = strings.ReplaceAll(requestPath, "{clusters}", url.PathEscape(utils.ParameterToString(r.clusters))) @@ -1365,20 +1400,20 @@ func (c *APIClient) GetReachabilityWithHTTPInfo(r ApiGetReachabilityRequest, opt return nil, nil, reportError("Parameter `clusters` is required when calling `GetReachability`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1396,7 +1431,7 @@ Request can be constructed by NewApiGetReachabilityRequest with parameters below @param clusters string - Subset of clusters, separated by comma. @return map[string]map[string]bool */ -func (c *APIClient) GetReachability(r ApiGetReachabilityRequest, opts ...utils.RequestOption) (*map[string]map[string]bool, error) { +func (c *APIClient) GetReachability(r ApiGetReachabilityRequest, opts ...RequestOption) (*map[string]map[string]bool, error) { var returnValue *map[string]map[string]bool res, resBody, err := c.GetReachabilityWithHTTPInfo(r, opts...) @@ -1445,28 +1480,28 @@ Algolia application's cluster. clusters. Request can be constructed by NewApiGetServersRequest with parameters below. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetServersWithHTTPInfo(opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetServersWithHTTPInfo(opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/inventory/servers" - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1491,7 +1526,7 @@ Request can be constructed by NewApiGetServersRequest with parameters below. @return InventoryResponse */ -func (c *APIClient) GetServers(opts ...utils.RequestOption) (*InventoryResponse, error) { +func (c *APIClient) GetServers(opts ...RequestOption) (*InventoryResponse, error) { var returnValue *InventoryResponse res, resBody, err := c.GetServersWithHTTPInfo(opts...) @@ -1533,28 +1568,28 @@ GetStatus calls the API and returns the raw response from it. Request can be constructed by NewApiGetStatusRequest with parameters below. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetStatusWithHTTPInfo(opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetStatusWithHTTPInfo(opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/status" - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1571,7 +1606,7 @@ Request can be constructed by NewApiGetStatusRequest with parameters below. @return StatusResponse */ -func (c *APIClient) GetStatus(opts ...utils.RequestOption) (*StatusResponse, error) { +func (c *APIClient) GetStatus(opts ...RequestOption) (*StatusResponse, error) { var returnValue *StatusResponse res, resBody, err := c.GetStatusWithHTTPInfo(opts...) diff --git a/clients/algoliasearch-client-go/algolia/personalization/api_personalization.go b/clients/algoliasearch-client-go/algolia/personalization/api_personalization.go index dae3d98624..b6d763c50f 100644 --- a/clients/algoliasearch-client-go/algolia/personalization/api_personalization.go +++ b/clients/algoliasearch-client-go/algolia/personalization/api_personalization.go @@ -12,6 +12,41 @@ import ( "github.com/algolia/algoliasearch-client-go/v4/algolia/utils" ) +type config struct { + // -- Request options for API calls + context context.Context + queryParams url.Values + headerParams map[string]string +} + +type RequestOption interface { + apply(*config) +} + +type requestOption func(*config) + +func (r requestOption) apply(c *config) { + r(c) +} + +func WithContext(ctx context.Context) requestOption { + return requestOption(func(c *config) { + c.context = ctx + }) +} + +func WithHeaderParam(key string, value any) requestOption { + return requestOption(func(c *config) { + c.headerParams[key] = utils.ParameterToString(value) + }) +} + +func WithQueryParam(key string, value any) requestOption { + return requestOption(func(c *config) { + c.queryParams.Set(utils.QueryParameterToString(key), utils.QueryParameterToString(value)) + }) +} + func (r *ApiCustomDeleteRequest) UnmarshalJSON(b []byte) error { req := map[string]json.RawMessage{} err := json.Unmarshal(b, &req) @@ -68,12 +103,12 @@ CustomDelete calls the API and returns the raw response from it. Request can be constructed by NewApiCustomDeleteRequest with parameters below. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomDeleteWithHTTPInfo(r ApiCustomDeleteRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomDeleteWithHTTPInfo(r ApiCustomDeleteRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -81,26 +116,26 @@ func (c *APIClient) CustomDeleteWithHTTPInfo(r ApiCustomDeleteRequest, opts ...u return nil, nil, reportError("Parameter `path` is required when calling `CustomDelete`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodDelete, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodDelete, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -119,7 +154,7 @@ Request can be constructed by NewApiCustomDeleteRequest with parameters below. @param parameters map[string]any - Query parameters to apply to the current query. @return map[string]any */ -func (c *APIClient) CustomDelete(r ApiCustomDeleteRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomDelete(r ApiCustomDeleteRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomDeleteWithHTTPInfo(r, opts...) @@ -210,12 +245,12 @@ CustomGet calls the API and returns the raw response from it. Request can be constructed by NewApiCustomGetRequest with parameters below. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomGetWithHTTPInfo(r ApiCustomGetRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomGetWithHTTPInfo(r ApiCustomGetRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -223,26 +258,26 @@ func (c *APIClient) CustomGetWithHTTPInfo(r ApiCustomGetRequest, opts ...utils.R return nil, nil, reportError("Parameter `path` is required when calling `CustomGet`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -261,7 +296,7 @@ Request can be constructed by NewApiCustomGetRequest with parameters below. @param parameters map[string]any - Query parameters to apply to the current query. @return map[string]any */ -func (c *APIClient) CustomGet(r ApiCustomGetRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomGet(r ApiCustomGetRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomGetWithHTTPInfo(r, opts...) @@ -369,12 +404,12 @@ CustomPost calls the API and returns the raw response from it. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. @param body map[string]any - Parameters to send with the custom request. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -382,21 +417,21 @@ func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...utils return nil, nil, reportError("Parameter `path` is required when calling `CustomPost`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any @@ -407,7 +442,7 @@ func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...utils } else { postBody = r.body } - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -427,7 +462,7 @@ Request can be constructed by NewApiCustomPostRequest with parameters below. @param body map[string]any - Parameters to send with the custom request. @return map[string]any */ -func (c *APIClient) CustomPost(r ApiCustomPostRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomPost(r ApiCustomPostRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomPostWithHTTPInfo(r, opts...) @@ -535,12 +570,12 @@ CustomPut calls the API and returns the raw response from it. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. @param body map[string]any - Parameters to send with the custom request. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -548,21 +583,21 @@ func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...utils.R return nil, nil, reportError("Parameter `path` is required when calling `CustomPut`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any @@ -573,7 +608,7 @@ func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...utils.R } else { postBody = r.body } - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPut, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPut, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -593,7 +628,7 @@ Request can be constructed by NewApiCustomPutRequest with parameters below. @param body map[string]any - Parameters to send with the custom request. @return map[string]any */ -func (c *APIClient) CustomPut(r ApiCustomPutRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomPut(r ApiCustomPutRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomPutWithHTTPInfo(r, opts...) @@ -671,12 +706,12 @@ The response includes a date and time when the user profile can safely be consid Request can be constructed by NewApiDeleteUserProfileRequest with parameters below. @param userToken string - Unique identifier representing a user for which to fetch the personalization profile. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) DeleteUserProfileWithHTTPInfo(r ApiDeleteUserProfileRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) DeleteUserProfileWithHTTPInfo(r ApiDeleteUserProfileRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/profiles/{userToken}" requestPath = strings.ReplaceAll(requestPath, "{userToken}", url.PathEscape(utils.ParameterToString(r.userToken))) @@ -684,20 +719,20 @@ func (c *APIClient) DeleteUserProfileWithHTTPInfo(r ApiDeleteUserProfileRequest, return nil, nil, reportError("Parameter `userToken` is required when calling `DeleteUserProfile`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodDelete, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodDelete, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -720,7 +755,7 @@ Request can be constructed by NewApiDeleteUserProfileRequest with parameters bel @param userToken string - Unique identifier representing a user for which to fetch the personalization profile. @return DeleteUserProfileResponse */ -func (c *APIClient) DeleteUserProfile(r ApiDeleteUserProfileRequest, opts ...utils.RequestOption) (*DeleteUserProfileResponse, error) { +func (c *APIClient) DeleteUserProfile(r ApiDeleteUserProfileRequest, opts ...RequestOption) (*DeleteUserProfileResponse, error) { var returnValue *DeleteUserProfileResponse res, resBody, err := c.DeleteUserProfileWithHTTPInfo(r, opts...) @@ -764,28 +799,28 @@ GetPersonalizationStrategy calls the API and returns the raw response from it. - recommendation Request can be constructed by NewApiGetPersonalizationStrategyRequest with parameters below. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetPersonalizationStrategyWithHTTPInfo(opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetPersonalizationStrategyWithHTTPInfo(opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/strategies/personalization" - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -805,7 +840,7 @@ Request can be constructed by NewApiGetPersonalizationStrategyRequest with param @return PersonalizationStrategyParams */ -func (c *APIClient) GetPersonalizationStrategy(opts ...utils.RequestOption) (*PersonalizationStrategyParams, error) { +func (c *APIClient) GetPersonalizationStrategy(opts ...RequestOption) (*PersonalizationStrategyParams, error) { var returnValue *PersonalizationStrategyParams res, resBody, err := c.GetPersonalizationStrategyWithHTTPInfo(opts...) @@ -881,12 +916,12 @@ GetUserTokenProfile calls the API and returns the raw response from it. Request can be constructed by NewApiGetUserTokenProfileRequest with parameters below. @param userToken string - Unique identifier representing a user for which to fetch the personalization profile. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetUserTokenProfileWithHTTPInfo(r ApiGetUserTokenProfileRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetUserTokenProfileWithHTTPInfo(r ApiGetUserTokenProfileRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/profiles/personalization/{userToken}" requestPath = strings.ReplaceAll(requestPath, "{userToken}", url.PathEscape(utils.ParameterToString(r.userToken))) @@ -894,20 +929,20 @@ func (c *APIClient) GetUserTokenProfileWithHTTPInfo(r ApiGetUserTokenProfileRequ return nil, nil, reportError("Parameter `userToken` is required when calling `GetUserTokenProfile`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -928,7 +963,7 @@ Request can be constructed by NewApiGetUserTokenProfileRequest with parameters b @param userToken string - Unique identifier representing a user for which to fetch the personalization profile. @return GetUserTokenResponse */ -func (c *APIClient) GetUserTokenProfile(r ApiGetUserTokenProfileRequest, opts ...utils.RequestOption) (*GetUserTokenResponse, error) { +func (c *APIClient) GetUserTokenProfile(r ApiGetUserTokenProfileRequest, opts ...RequestOption) (*GetUserTokenResponse, error) { var returnValue *GetUserTokenResponse res, resBody, err := c.GetUserTokenProfileWithHTTPInfo(r, opts...) @@ -1009,34 +1044,34 @@ SetPersonalizationStrategy calls the API and returns the raw response from it. Request can be constructed by NewApiSetPersonalizationStrategyRequest with parameters below. @param personalizationStrategyParams PersonalizationStrategyParams - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) SetPersonalizationStrategyWithHTTPInfo(r ApiSetPersonalizationStrategyRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) SetPersonalizationStrategyWithHTTPInfo(r ApiSetPersonalizationStrategyRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/strategies/personalization" if r.personalizationStrategyParams == nil { return nil, nil, reportError("Parameter `personalizationStrategyParams` is required when calling `SetPersonalizationStrategy`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.personalizationStrategyParams - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1057,7 +1092,7 @@ Request can be constructed by NewApiSetPersonalizationStrategyRequest with param @param personalizationStrategyParams PersonalizationStrategyParams @return SetPersonalizationStrategyResponse */ -func (c *APIClient) SetPersonalizationStrategy(r ApiSetPersonalizationStrategyRequest, opts ...utils.RequestOption) (*SetPersonalizationStrategyResponse, error) { +func (c *APIClient) SetPersonalizationStrategy(r ApiSetPersonalizationStrategyRequest, opts ...RequestOption) (*SetPersonalizationStrategyResponse, error) { var returnValue *SetPersonalizationStrategyResponse res, resBody, err := c.SetPersonalizationStrategyWithHTTPInfo(r, opts...) diff --git a/clients/algoliasearch-client-go/algolia/query-suggestions/api_query_suggestions.go b/clients/algoliasearch-client-go/algolia/query-suggestions/api_query_suggestions.go index dad25bed40..f8ba3ae04a 100644 --- a/clients/algoliasearch-client-go/algolia/query-suggestions/api_query_suggestions.go +++ b/clients/algoliasearch-client-go/algolia/query-suggestions/api_query_suggestions.go @@ -12,6 +12,41 @@ import ( "github.com/algolia/algoliasearch-client-go/v4/algolia/utils" ) +type config struct { + // -- Request options for API calls + context context.Context + queryParams url.Values + headerParams map[string]string +} + +type RequestOption interface { + apply(*config) +} + +type requestOption func(*config) + +func (r requestOption) apply(c *config) { + r(c) +} + +func WithContext(ctx context.Context) requestOption { + return requestOption(func(c *config) { + c.context = ctx + }) +} + +func WithHeaderParam(key string, value any) requestOption { + return requestOption(func(c *config) { + c.headerParams[key] = utils.ParameterToString(value) + }) +} + +func WithQueryParam(key string, value any) requestOption { + return requestOption(func(c *config) { + c.queryParams.Set(utils.QueryParameterToString(key), utils.QueryParameterToString(value)) + }) +} + func (r *ApiCreateConfigRequest) UnmarshalJSON(b []byte) error { req := map[string]json.RawMessage{} err := json.Unmarshal(b, &req) @@ -60,34 +95,34 @@ You can have up to 100 configurations per Algolia application. Request can be constructed by NewApiCreateConfigRequest with parameters below. @param configurationWithIndex ConfigurationWithIndex - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CreateConfigWithHTTPInfo(r ApiCreateConfigRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CreateConfigWithHTTPInfo(r ApiCreateConfigRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/configs" if r.configurationWithIndex == nil { return nil, nil, reportError("Parameter `configurationWithIndex` is required when calling `CreateConfig`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.configurationWithIndex - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -110,7 +145,7 @@ Request can be constructed by NewApiCreateConfigRequest with parameters below. @param configurationWithIndex ConfigurationWithIndex @return BaseResponse */ -func (c *APIClient) CreateConfig(r ApiCreateConfigRequest, opts ...utils.RequestOption) (*BaseResponse, error) { +func (c *APIClient) CreateConfig(r ApiCreateConfigRequest, opts ...RequestOption) (*BaseResponse, error) { var returnValue *BaseResponse res, resBody, err := c.CreateConfigWithHTTPInfo(r, opts...) @@ -201,12 +236,12 @@ CustomDelete calls the API and returns the raw response from it. Request can be constructed by NewApiCustomDeleteRequest with parameters below. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomDeleteWithHTTPInfo(r ApiCustomDeleteRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomDeleteWithHTTPInfo(r ApiCustomDeleteRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -214,26 +249,26 @@ func (c *APIClient) CustomDeleteWithHTTPInfo(r ApiCustomDeleteRequest, opts ...u return nil, nil, reportError("Parameter `path` is required when calling `CustomDelete`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodDelete, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodDelete, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -252,7 +287,7 @@ Request can be constructed by NewApiCustomDeleteRequest with parameters below. @param parameters map[string]any - Query parameters to apply to the current query. @return map[string]any */ -func (c *APIClient) CustomDelete(r ApiCustomDeleteRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomDelete(r ApiCustomDeleteRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomDeleteWithHTTPInfo(r, opts...) @@ -343,12 +378,12 @@ CustomGet calls the API and returns the raw response from it. Request can be constructed by NewApiCustomGetRequest with parameters below. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomGetWithHTTPInfo(r ApiCustomGetRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomGetWithHTTPInfo(r ApiCustomGetRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -356,26 +391,26 @@ func (c *APIClient) CustomGetWithHTTPInfo(r ApiCustomGetRequest, opts ...utils.R return nil, nil, reportError("Parameter `path` is required when calling `CustomGet`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -394,7 +429,7 @@ Request can be constructed by NewApiCustomGetRequest with parameters below. @param parameters map[string]any - Query parameters to apply to the current query. @return map[string]any */ -func (c *APIClient) CustomGet(r ApiCustomGetRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomGet(r ApiCustomGetRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomGetWithHTTPInfo(r, opts...) @@ -502,12 +537,12 @@ CustomPost calls the API and returns the raw response from it. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. @param body map[string]any - Parameters to send with the custom request. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -515,21 +550,21 @@ func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...utils return nil, nil, reportError("Parameter `path` is required when calling `CustomPost`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any @@ -540,7 +575,7 @@ func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...utils } else { postBody = r.body } - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -560,7 +595,7 @@ Request can be constructed by NewApiCustomPostRequest with parameters below. @param body map[string]any - Parameters to send with the custom request. @return map[string]any */ -func (c *APIClient) CustomPost(r ApiCustomPostRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomPost(r ApiCustomPostRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomPostWithHTTPInfo(r, opts...) @@ -668,12 +703,12 @@ CustomPut calls the API and returns the raw response from it. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. @param body map[string]any - Parameters to send with the custom request. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -681,21 +716,21 @@ func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...utils.R return nil, nil, reportError("Parameter `path` is required when calling `CustomPut`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any @@ -706,7 +741,7 @@ func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...utils.R } else { postBody = r.body } - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPut, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPut, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -726,7 +761,7 @@ Request can be constructed by NewApiCustomPutRequest with parameters below. @param body map[string]any - Parameters to send with the custom request. @return map[string]any */ -func (c *APIClient) CustomPut(r ApiCustomPutRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomPut(r ApiCustomPutRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomPutWithHTTPInfo(r, opts...) @@ -805,12 +840,12 @@ To delete the Query Suggestions index itself, use the Search API and the [Delete Request can be constructed by NewApiDeleteConfigRequest with parameters below. @param indexName string - Query Suggestions index name. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) DeleteConfigWithHTTPInfo(r ApiDeleteConfigRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) DeleteConfigWithHTTPInfo(r ApiDeleteConfigRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/configs/{indexName}" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) @@ -818,20 +853,20 @@ func (c *APIClient) DeleteConfigWithHTTPInfo(r ApiDeleteConfigRequest, opts ...u return nil, nil, reportError("Parameter `indexName` is required when calling `DeleteConfig`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodDelete, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodDelete, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -855,7 +890,7 @@ Request can be constructed by NewApiDeleteConfigRequest with parameters below. @param indexName string - Query Suggestions index name. @return BaseResponse */ -func (c *APIClient) DeleteConfig(r ApiDeleteConfigRequest, opts ...utils.RequestOption) (*BaseResponse, error) { +func (c *APIClient) DeleteConfig(r ApiDeleteConfigRequest, opts ...RequestOption) (*BaseResponse, error) { var returnValue *BaseResponse res, resBody, err := c.DeleteConfigWithHTTPInfo(r, opts...) @@ -899,28 +934,28 @@ GetAllConfigs calls the API and returns the raw response from it. - settings Request can be constructed by NewApiGetAllConfigsRequest with parameters below. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetAllConfigsWithHTTPInfo(opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetAllConfigsWithHTTPInfo(opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/configs" - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -940,7 +975,7 @@ Request can be constructed by NewApiGetAllConfigsRequest with parameters below. @return []ConfigurationResponse */ -func (c *APIClient) GetAllConfigs(opts ...utils.RequestOption) ([]ConfigurationResponse, error) { +func (c *APIClient) GetAllConfigs(opts ...RequestOption) ([]ConfigurationResponse, error) { var returnValue []ConfigurationResponse res, resBody, err := c.GetAllConfigsWithHTTPInfo(opts...) @@ -1016,12 +1051,12 @@ GetConfig calls the API and returns the raw response from it. Request can be constructed by NewApiGetConfigRequest with parameters below. @param indexName string - Query Suggestions index name. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetConfigWithHTTPInfo(r ApiGetConfigRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetConfigWithHTTPInfo(r ApiGetConfigRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/configs/{indexName}" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) @@ -1029,20 +1064,20 @@ func (c *APIClient) GetConfigWithHTTPInfo(r ApiGetConfigRequest, opts ...utils.R return nil, nil, reportError("Parameter `indexName` is required when calling `GetConfig`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1063,7 +1098,7 @@ Request can be constructed by NewApiGetConfigRequest with parameters below. @param indexName string - Query Suggestions index name. @return ConfigurationResponse */ -func (c *APIClient) GetConfig(r ApiGetConfigRequest, opts ...utils.RequestOption) (*ConfigurationResponse, error) { +func (c *APIClient) GetConfig(r ApiGetConfigRequest, opts ...RequestOption) (*ConfigurationResponse, error) { var returnValue *ConfigurationResponse res, resBody, err := c.GetConfigWithHTTPInfo(r, opts...) @@ -1139,12 +1174,12 @@ GetConfigStatus calls the API and returns the raw response from it. Request can be constructed by NewApiGetConfigStatusRequest with parameters below. @param indexName string - Query Suggestions index name. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetConfigStatusWithHTTPInfo(r ApiGetConfigStatusRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetConfigStatusWithHTTPInfo(r ApiGetConfigStatusRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/configs/{indexName}/status" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) @@ -1152,20 +1187,20 @@ func (c *APIClient) GetConfigStatusWithHTTPInfo(r ApiGetConfigStatusRequest, opt return nil, nil, reportError("Parameter `indexName` is required when calling `GetConfigStatus`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1186,7 +1221,7 @@ Request can be constructed by NewApiGetConfigStatusRequest with parameters below @param indexName string - Query Suggestions index name. @return GetConfigStatus200Response */ -func (c *APIClient) GetConfigStatus(r ApiGetConfigStatusRequest, opts ...utils.RequestOption) (*GetConfigStatus200Response, error) { +func (c *APIClient) GetConfigStatus(r ApiGetConfigStatusRequest, opts ...RequestOption) (*GetConfigStatus200Response, error) { var returnValue *GetConfigStatus200Response res, resBody, err := c.GetConfigStatusWithHTTPInfo(r, opts...) @@ -1262,12 +1297,12 @@ GetLogFile calls the API and returns the raw response from it. Request can be constructed by NewApiGetLogFileRequest with parameters below. @param indexName string - Query Suggestions index name. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetLogFileWithHTTPInfo(r ApiGetLogFileRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetLogFileWithHTTPInfo(r ApiGetLogFileRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/logs/{indexName}" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) @@ -1275,20 +1310,20 @@ func (c *APIClient) GetLogFileWithHTTPInfo(r ApiGetLogFileRequest, opts ...utils return nil, nil, reportError("Parameter `indexName` is required when calling `GetLogFile`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1309,7 +1344,7 @@ Request can be constructed by NewApiGetLogFileRequest with parameters below. @param indexName string - Query Suggestions index name. @return GetLogFile200Response */ -func (c *APIClient) GetLogFile(r ApiGetLogFileRequest, opts ...utils.RequestOption) (*GetLogFile200Response, error) { +func (c *APIClient) GetLogFile(r ApiGetLogFileRequest, opts ...RequestOption) (*GetLogFile200Response, error) { var returnValue *GetLogFile200Response res, resBody, err := c.GetLogFileWithHTTPInfo(r, opts...) @@ -1402,12 +1437,12 @@ UpdateConfig calls the API and returns the raw response from it. Request can be constructed by NewApiUpdateConfigRequest with parameters below. @param indexName string - Query Suggestions index name. @param configuration Configuration - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) UpdateConfigWithHTTPInfo(r ApiUpdateConfigRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) UpdateConfigWithHTTPInfo(r ApiUpdateConfigRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/configs/{indexName}" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) @@ -1419,22 +1454,22 @@ func (c *APIClient) UpdateConfigWithHTTPInfo(r ApiUpdateConfigRequest, opts ...u return nil, nil, reportError("Parameter `configuration` is required when calling `UpdateConfig`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.configuration - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPut, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPut, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1456,7 +1491,7 @@ Request can be constructed by NewApiUpdateConfigRequest with parameters below. @param configuration Configuration @return BaseResponse */ -func (c *APIClient) UpdateConfig(r ApiUpdateConfigRequest, opts ...utils.RequestOption) (*BaseResponse, error) { +func (c *APIClient) UpdateConfig(r ApiUpdateConfigRequest, opts ...RequestOption) (*BaseResponse, error) { var returnValue *BaseResponse res, resBody, err := c.UpdateConfigWithHTTPInfo(r, opts...) diff --git a/clients/algoliasearch-client-go/algolia/recommend/api_recommend.go b/clients/algoliasearch-client-go/algolia/recommend/api_recommend.go index f4ce04dcbf..28134c7325 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/api_recommend.go +++ b/clients/algoliasearch-client-go/algolia/recommend/api_recommend.go @@ -12,6 +12,41 @@ import ( "github.com/algolia/algoliasearch-client-go/v4/algolia/utils" ) +type config struct { + // -- Request options for API calls + context context.Context + queryParams url.Values + headerParams map[string]string +} + +type RequestOption interface { + apply(*config) +} + +type requestOption func(*config) + +func (r requestOption) apply(c *config) { + r(c) +} + +func WithContext(ctx context.Context) requestOption { + return requestOption(func(c *config) { + c.context = ctx + }) +} + +func WithHeaderParam(key string, value any) requestOption { + return requestOption(func(c *config) { + c.headerParams[key] = utils.ParameterToString(value) + }) +} + +func WithQueryParam(key string, value any) requestOption { + return requestOption(func(c *config) { + c.queryParams.Set(utils.QueryParameterToString(key), utils.QueryParameterToString(value)) + }) +} + func (r *ApiCustomDeleteRequest) UnmarshalJSON(b []byte) error { req := map[string]json.RawMessage{} err := json.Unmarshal(b, &req) @@ -68,12 +103,12 @@ CustomDelete calls the API and returns the raw response from it. Request can be constructed by NewApiCustomDeleteRequest with parameters below. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomDeleteWithHTTPInfo(r ApiCustomDeleteRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomDeleteWithHTTPInfo(r ApiCustomDeleteRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -81,26 +116,26 @@ func (c *APIClient) CustomDeleteWithHTTPInfo(r ApiCustomDeleteRequest, opts ...u return nil, nil, reportError("Parameter `path` is required when calling `CustomDelete`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodDelete, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodDelete, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -119,7 +154,7 @@ Request can be constructed by NewApiCustomDeleteRequest with parameters below. @param parameters map[string]any - Query parameters to apply to the current query. @return map[string]any */ -func (c *APIClient) CustomDelete(r ApiCustomDeleteRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomDelete(r ApiCustomDeleteRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomDeleteWithHTTPInfo(r, opts...) @@ -210,12 +245,12 @@ CustomGet calls the API and returns the raw response from it. Request can be constructed by NewApiCustomGetRequest with parameters below. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomGetWithHTTPInfo(r ApiCustomGetRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomGetWithHTTPInfo(r ApiCustomGetRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -223,26 +258,26 @@ func (c *APIClient) CustomGetWithHTTPInfo(r ApiCustomGetRequest, opts ...utils.R return nil, nil, reportError("Parameter `path` is required when calling `CustomGet`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -261,7 +296,7 @@ Request can be constructed by NewApiCustomGetRequest with parameters below. @param parameters map[string]any - Query parameters to apply to the current query. @return map[string]any */ -func (c *APIClient) CustomGet(r ApiCustomGetRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomGet(r ApiCustomGetRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomGetWithHTTPInfo(r, opts...) @@ -369,12 +404,12 @@ CustomPost calls the API and returns the raw response from it. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. @param body map[string]any - Parameters to send with the custom request. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -382,21 +417,21 @@ func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...utils return nil, nil, reportError("Parameter `path` is required when calling `CustomPost`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any @@ -407,7 +442,7 @@ func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...utils } else { postBody = r.body } - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -427,7 +462,7 @@ Request can be constructed by NewApiCustomPostRequest with parameters below. @param body map[string]any - Parameters to send with the custom request. @return map[string]any */ -func (c *APIClient) CustomPost(r ApiCustomPostRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomPost(r ApiCustomPostRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomPostWithHTTPInfo(r, opts...) @@ -535,12 +570,12 @@ CustomPut calls the API and returns the raw response from it. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. @param body map[string]any - Parameters to send with the custom request. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -548,21 +583,21 @@ func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...utils.R return nil, nil, reportError("Parameter `path` is required when calling `CustomPut`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any @@ -573,7 +608,7 @@ func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...utils.R } else { postBody = r.body } - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPut, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPut, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -593,7 +628,7 @@ Request can be constructed by NewApiCustomPutRequest with parameters below. @param body map[string]any - Parameters to send with the custom request. @return map[string]any */ -func (c *APIClient) CustomPut(r ApiCustomPutRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomPut(r ApiCustomPutRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomPutWithHTTPInfo(r, opts...) @@ -693,12 +728,12 @@ DeleteRecommendRule calls the API and returns the raw response from it. @param indexName string - Name of the index on which to perform the operation. @param model RecommendModels - [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models). @param objectID string - Unique record identifier. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) DeleteRecommendRuleWithHTTPInfo(r ApiDeleteRecommendRuleRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) DeleteRecommendRuleWithHTTPInfo(r ApiDeleteRecommendRuleRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}/{model}/recommend/rules/{objectID}" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) requestPath = strings.ReplaceAll(requestPath, "{model}", url.PathEscape(utils.ParameterToString(r.model))) @@ -712,20 +747,20 @@ func (c *APIClient) DeleteRecommendRuleWithHTTPInfo(r ApiDeleteRecommendRuleRequ return nil, nil, reportError("Parameter `objectID` is required when calling `DeleteRecommendRule`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodDelete, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodDelete, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -748,7 +783,7 @@ Request can be constructed by NewApiDeleteRecommendRuleRequest with parameters b @param objectID string - Unique record identifier. @return DeletedAtResponse */ -func (c *APIClient) DeleteRecommendRule(r ApiDeleteRecommendRuleRequest, opts ...utils.RequestOption) (*DeletedAtResponse, error) { +func (c *APIClient) DeleteRecommendRule(r ApiDeleteRecommendRuleRequest, opts ...RequestOption) (*DeletedAtResponse, error) { var returnValue *DeletedAtResponse res, resBody, err := c.DeleteRecommendRuleWithHTTPInfo(r, opts...) @@ -848,12 +883,12 @@ GetRecommendRule calls the API and returns the raw response from it. @param indexName string - Name of the index on which to perform the operation. @param model RecommendModels - [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models). @param objectID string - Unique record identifier. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetRecommendRuleWithHTTPInfo(r ApiGetRecommendRuleRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetRecommendRuleWithHTTPInfo(r ApiGetRecommendRuleRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}/{model}/recommend/rules/{objectID}" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) requestPath = strings.ReplaceAll(requestPath, "{model}", url.PathEscape(utils.ParameterToString(r.model))) @@ -867,20 +902,20 @@ func (c *APIClient) GetRecommendRuleWithHTTPInfo(r ApiGetRecommendRuleRequest, o return nil, nil, reportError("Parameter `objectID` is required when calling `GetRecommendRule`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -903,7 +938,7 @@ Request can be constructed by NewApiGetRecommendRuleRequest with parameters belo @param objectID string - Unique record identifier. @return RecommendRule */ -func (c *APIClient) GetRecommendRule(r ApiGetRecommendRuleRequest, opts ...utils.RequestOption) (*RecommendRule, error) { +func (c *APIClient) GetRecommendRule(r ApiGetRecommendRuleRequest, opts ...RequestOption) (*RecommendRule, error) { var returnValue *RecommendRule res, resBody, err := c.GetRecommendRuleWithHTTPInfo(r, opts...) @@ -1007,12 +1042,12 @@ The API response includes a task ID that you can use to check the status. @param indexName string - Name of the index on which to perform the operation. @param model RecommendModels - [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models). @param taskID int64 - Unique task identifier. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetRecommendStatusWithHTTPInfo(r ApiGetRecommendStatusRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetRecommendStatusWithHTTPInfo(r ApiGetRecommendStatusRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}/{model}/task/{taskID}" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) requestPath = strings.ReplaceAll(requestPath, "{model}", url.PathEscape(utils.ParameterToString(r.model))) @@ -1022,20 +1057,20 @@ func (c *APIClient) GetRecommendStatusWithHTTPInfo(r ApiGetRecommendStatusReques return nil, nil, reportError("Parameter `indexName` is required when calling `GetRecommendStatus`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1062,7 +1097,7 @@ Request can be constructed by NewApiGetRecommendStatusRequest with parameters be @param taskID int64 - Unique task identifier. @return GetRecommendTaskResponse */ -func (c *APIClient) GetRecommendStatus(r ApiGetRecommendStatusRequest, opts ...utils.RequestOption) (*GetRecommendTaskResponse, error) { +func (c *APIClient) GetRecommendStatus(r ApiGetRecommendStatusRequest, opts ...RequestOption) (*GetRecommendTaskResponse, error) { var returnValue *GetRecommendTaskResponse res, resBody, err := c.GetRecommendStatusWithHTTPInfo(r, opts...) @@ -1144,34 +1179,34 @@ GetRecommendations calls the API and returns the raw response from it. Request can be constructed by NewApiGetRecommendationsRequest with parameters below. @param getRecommendationsParams GetRecommendationsParams - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetRecommendationsWithHTTPInfo(r ApiGetRecommendationsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetRecommendationsWithHTTPInfo(r ApiGetRecommendationsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/*/recommendations" if r.getRecommendationsParams == nil { return nil, nil, reportError("Parameter `getRecommendationsParams` is required when calling `GetRecommendations`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.getRecommendationsParams - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1192,7 +1227,7 @@ Request can be constructed by NewApiGetRecommendationsRequest with parameters be @param getRecommendationsParams GetRecommendationsParams @return GetRecommendationsResponse */ -func (c *APIClient) GetRecommendations(r ApiGetRecommendationsRequest, opts ...utils.RequestOption) (*GetRecommendationsResponse, error) { +func (c *APIClient) GetRecommendations(r ApiGetRecommendationsRequest, opts ...RequestOption) (*GetRecommendationsResponse, error) { var returnValue *GetRecommendationsResponse res, resBody, err := c.GetRecommendationsWithHTTPInfo(r, opts...) @@ -1299,12 +1334,12 @@ Use an empty query to list all rules for this recommendation scenario. @param indexName string - Name of the index on which to perform the operation. @param model RecommendModels - [Recommend model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models). @param searchRecommendRulesParams SearchRecommendRulesParams - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) SearchRecommendRulesWithHTTPInfo(r ApiSearchRecommendRulesRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) SearchRecommendRulesWithHTTPInfo(r ApiSearchRecommendRulesRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}/{model}/recommend/rules/search" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) requestPath = strings.ReplaceAll(requestPath, "{model}", url.PathEscape(utils.ParameterToString(r.model))) @@ -1313,15 +1348,15 @@ func (c *APIClient) SearchRecommendRulesWithHTTPInfo(r ApiSearchRecommendRulesRe return nil, nil, reportError("Parameter `indexName` is required when calling `SearchRecommendRules`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any @@ -1332,7 +1367,7 @@ func (c *APIClient) SearchRecommendRulesWithHTTPInfo(r ApiSearchRecommendRulesRe } else { postBody = r.searchRecommendRulesParams } - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1357,7 +1392,7 @@ Request can be constructed by NewApiSearchRecommendRulesRequest with parameters @param searchRecommendRulesParams SearchRecommendRulesParams @return SearchRecommendRulesResponse */ -func (c *APIClient) SearchRecommendRules(r ApiSearchRecommendRulesRequest, opts ...utils.RequestOption) (*SearchRecommendRulesResponse, error) { +func (c *APIClient) SearchRecommendRules(r ApiSearchRecommendRulesRequest, opts ...RequestOption) (*SearchRecommendRulesResponse, error) { var returnValue *SearchRecommendRulesResponse res, resBody, err := c.SearchRecommendRulesWithHTTPInfo(r, opts...) diff --git a/clients/algoliasearch-client-go/algolia/search/api_search.go b/clients/algoliasearch-client-go/algolia/search/api_search.go index 7f4c6daf36..c7147f94cd 100644 --- a/clients/algoliasearch-client-go/algolia/search/api_search.go +++ b/clients/algoliasearch-client-go/algolia/search/api_search.go @@ -2,12 +2,14 @@ package search import ( + "cmp" "context" "crypto/hmac" "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" + "errors" "fmt" "net/http" "net/url" @@ -23,6 +25,251 @@ import ( "github.com/algolia/algoliasearch-client-go/v4/algolia/utils" ) +type config struct { + // -- Request options for API calls + context context.Context + queryParams url.Values + headerParams map[string]string + + // -- ChunkedBatch options + waitForTasks bool + batchSize int + + // -- Partial update options + createIfNotExists bool + + // -- Iterable options + maxRetries int + timeout func(int) time.Duration + aggregator func(any, error) + iterableError *IterableError + + // -- WaitForApiKey options + apiKey *ApiKey +} + +type RequestOption interface { + apply(*config) +} + +type requestOption func(*config) + +func (r requestOption) apply(c *config) { + r(c) +} + +func WithContext(ctx context.Context) requestOption { + return requestOption(func(c *config) { + c.context = ctx + }) +} + +func WithHeaderParam(key string, value any) requestOption { + return requestOption(func(c *config) { + c.headerParams[key] = utils.ParameterToString(value) + }) +} + +func WithQueryParam(key string, value any) requestOption { + return requestOption(func(c *config) { + c.queryParams.Set(utils.QueryParameterToString(key), utils.QueryParameterToString(value)) + }) +} + +// --------- ChunkedBatch options --------- + +type ChunkedBatchOption interface { + RequestOption + chunkedBatch() +} + +type chunkedBatchOption func(*config) + +var ( + _ ChunkedBatchOption = (*chunkedBatchOption)(nil) + _ ChunkedBatchOption = (*requestOption)(nil) +) + +func (c chunkedBatchOption) apply(conf *config) { + c(conf) +} + +func (c chunkedBatchOption) chunkedBatch() {} + +func (r requestOption) chunkedBatch() {} + +func WithWaitForTasks(waitForTasks bool) chunkedBatchOption { + return chunkedBatchOption(func(c *config) { + c.waitForTasks = waitForTasks + }) +} + +func WithBatchSize(batchSize int) chunkedBatchOption { + return chunkedBatchOption(func(c *config) { + c.batchSize = batchSize + }) +} + +// --------- ChunkedBatch options --------- + +type PartialUpdateObjectsOption interface { + ChunkedBatchOption + partialUpdateObjects() +} + +type partialUpdateObjectsOption func(*config) + +var ( + _ PartialUpdateObjectsOption = (*partialUpdateObjectsOption)(nil) + _ PartialUpdateObjectsOption = (*chunkedBatchOption)(nil) + _ PartialUpdateObjectsOption = (*requestOption)(nil) +) + +func (p partialUpdateObjectsOption) apply(c *config) { + p(c) +} + +func (p partialUpdateObjectsOption) partialUpdateObjects() {} + +func (p partialUpdateObjectsOption) chunkedBatch() {} + +func (c chunkedBatchOption) partialUpdateObjects() {} + +func (r requestOption) partialUpdateObjects() {} + +func WithCreateIfNotExists(createIfNotExists bool) partialUpdateObjectsOption { + return partialUpdateObjectsOption(func(c *config) { + c.createIfNotExists = createIfNotExists + }) +} + +// --------- Iterable options ---------. + +type IterableOption interface { + RequestOption + iterable() +} + +type iterableOption func(*config) + +var ( + _ IterableOption = (*iterableOption)(nil) + _ IterableOption = (*requestOption)(nil) +) + +func (i iterableOption) apply(c *config) { + i(c) +} + +func (r requestOption) iterable() {} + +func (i iterableOption) iterable() {} + +func WithMaxRetries(maxRetries int) iterableOption { + return iterableOption(func(c *config) { + c.maxRetries = maxRetries + }) +} + +func WithTimeout(timeout func(int) time.Duration) iterableOption { + return iterableOption(func(c *config) { + c.timeout = timeout + }) +} + +func WithAggregator(aggregator func(any, error)) iterableOption { + return iterableOption(func(c *config) { + c.aggregator = aggregator + }) +} + +func WithIterableError(iterableError *IterableError) iterableOption { + return iterableOption(func(c *config) { + c.iterableError = iterableError + }) +} + +// --------- WaitForKey options ---------. + +type WaitForApiKeyOption interface { + IterableOption + waitForApiKey() +} + +type waitForApiKeyOption func(*config) + +var ( + _ WaitForApiKeyOption = (*waitForApiKeyOption)(nil) + _ WaitForApiKeyOption = (*iterableOption)(nil) + _ WaitForApiKeyOption = (*requestOption)(nil) +) + +func (w waitForApiKeyOption) apply(c *config) { + w(c) +} + +func (w waitForApiKeyOption) waitForApiKey() {} + +func (w waitForApiKeyOption) iterable() {} + +func (r requestOption) waitForApiKey() {} + +func (i iterableOption) waitForApiKey() {} + +func WithApiKey(apiKey *ApiKey) waitForApiKeyOption { + return waitForApiKeyOption(func(c *config) { + c.apiKey = apiKey + }) +} + +// --------- Helper to convert options --------- + +func toRequestOptions[T RequestOption](opts []T) []RequestOption { + requestOpts := make([]RequestOption, 0, len(opts)) + + for _, opt := range opts { + requestOpts = append(requestOpts, opt) + } + + return requestOpts +} + +func toIterableOptions(opts []ChunkedBatchOption) []IterableOption { + iterableOpts := make([]IterableOption, 0, len(opts)) + + for _, opt := range opts { + if opt, ok := opt.(IterableOption); ok { + iterableOpts = append(iterableOpts, opt) + } + } + + return iterableOpts +} + +func toIterableOptionsWaitFor(opts []WaitForApiKeyOption) []IterableOption { + iterableOpts := make([]IterableOption, 0, len(opts)) + + for _, opt := range opts { + if opt, ok := opt.(IterableOption); ok { + iterableOpts = append(iterableOpts, opt) + } + } + + return iterableOpts +} + +func toChunkedBatchOptions(opts []PartialUpdateObjectsOption) []ChunkedBatchOption { + chunkedBatchOpts := make([]ChunkedBatchOption, 0, len(opts)) + + for _, opt := range opts { + if opt, ok := opt.(ChunkedBatchOption); ok { + chunkedBatchOpts = append(chunkedBatchOpts, opt) + } + } + + return chunkedBatchOpts +} + func (r *ApiAddApiKeyRequest) UnmarshalJSON(b []byte) error { req := map[string]json.RawMessage{} err := json.Unmarshal(b, &req) @@ -69,34 +316,34 @@ AddApiKey calls the API and returns the raw response from it. Request can be constructed by NewApiAddApiKeyRequest with parameters below. @param apiKey ApiKey - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) AddApiKeyWithHTTPInfo(r ApiAddApiKeyRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) AddApiKeyWithHTTPInfo(r ApiAddApiKeyRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/keys" if r.apiKey == nil { return nil, nil, reportError("Parameter `apiKey` is required when calling `AddApiKey`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.apiKey - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -117,7 +364,7 @@ Request can be constructed by NewApiAddApiKeyRequest with parameters below. @param apiKey ApiKey @return AddApiKeyResponse */ -func (c *APIClient) AddApiKey(r ApiAddApiKeyRequest, opts ...utils.RequestOption) (*AddApiKeyResponse, error) { +func (c *APIClient) AddApiKey(r ApiAddApiKeyRequest, opts ...RequestOption) (*AddApiKeyResponse, error) { var returnValue *AddApiKeyResponse res, resBody, err := c.AddApiKeyWithHTTPInfo(r, opts...) @@ -227,12 +474,12 @@ To add, update, or replace multiple records, use the [`batch` operation](#tag/Re @param indexName string - Name of the index on which to perform the operation. @param objectID string - Unique record identifier. @param body map[string]any - The record, a schemaless object with attributes that are useful in the context of search and discovery. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) AddOrUpdateObjectWithHTTPInfo(r ApiAddOrUpdateObjectRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) AddOrUpdateObjectWithHTTPInfo(r ApiAddOrUpdateObjectRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}/{objectID}" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) requestPath = strings.ReplaceAll(requestPath, "{objectID}", url.PathEscape(utils.ParameterToString(r.objectID))) @@ -248,22 +495,22 @@ func (c *APIClient) AddOrUpdateObjectWithHTTPInfo(r ApiAddOrUpdateObjectRequest, return nil, nil, reportError("Parameter `body` is required when calling `AddOrUpdateObject`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.body - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPut, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPut, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -290,7 +537,7 @@ Request can be constructed by NewApiAddOrUpdateObjectRequest with parameters bel @param body map[string]any - The record, a schemaless object with attributes that are useful in the context of search and discovery. @return UpdatedAtWithObjectIdResponse */ -func (c *APIClient) AddOrUpdateObject(r ApiAddOrUpdateObjectRequest, opts ...utils.RequestOption) (*UpdatedAtWithObjectIdResponse, error) { +func (c *APIClient) AddOrUpdateObject(r ApiAddOrUpdateObjectRequest, opts ...RequestOption) (*UpdatedAtWithObjectIdResponse, error) { var returnValue *UpdatedAtWithObjectIdResponse res, resBody, err := c.AddOrUpdateObjectWithHTTPInfo(r, opts...) @@ -371,34 +618,34 @@ AppendSource calls the API and returns the raw response from it. Request can be constructed by NewApiAppendSourceRequest with parameters below. @param source Source - Source to add. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) AppendSourceWithHTTPInfo(r ApiAppendSourceRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) AppendSourceWithHTTPInfo(r ApiAppendSourceRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/security/sources/append" if r.source == nil { return nil, nil, reportError("Parameter `source` is required when calling `AppendSource`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.source - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -419,7 +666,7 @@ Request can be constructed by NewApiAppendSourceRequest with parameters below. @param source Source - Source to add. @return CreatedAtResponse */ -func (c *APIClient) AppendSource(r ApiAppendSourceRequest, opts ...utils.RequestOption) (*CreatedAtResponse, error) { +func (c *APIClient) AppendSource(r ApiAppendSourceRequest, opts ...RequestOption) (*CreatedAtResponse, error) { var returnValue *CreatedAtResponse res, resBody, err := c.AppendSourceWithHTTPInfo(r, opts...) @@ -514,12 +761,12 @@ The time it takes to move a user is proportional to the amount of data linked to Request can be constructed by NewApiAssignUserIdRequest with parameters below. @param xAlgoliaUserID string - Unique identifier of the user who makes the search request. @param assignUserIdParams AssignUserIdParams - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) AssignUserIdWithHTTPInfo(r ApiAssignUserIdRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) AssignUserIdWithHTTPInfo(r ApiAssignUserIdRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/clusters/mapping" if r.xAlgoliaUserID == "" { @@ -530,24 +777,24 @@ func (c *APIClient) AssignUserIdWithHTTPInfo(r ApiAssignUserIdRequest, opts ...u return nil, nil, reportError("Parameter `assignUserIdParams` is required when calling `AssignUserId`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } - options.HeaderParams["X-Algolia-User-ID"] = utils.ParameterToString(r.xAlgoliaUserID) + conf.headerParams["X-Algolia-User-ID"] = utils.ParameterToString(r.xAlgoliaUserID) // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.assignUserIdParams - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -571,7 +818,7 @@ Request can be constructed by NewApiAssignUserIdRequest with parameters below. @param assignUserIdParams AssignUserIdParams @return CreatedAtResponse */ -func (c *APIClient) AssignUserId(r ApiAssignUserIdRequest, opts ...utils.RequestOption) (*CreatedAtResponse, error) { +func (c *APIClient) AssignUserId(r ApiAssignUserIdRequest, opts ...RequestOption) (*CreatedAtResponse, error) { var returnValue *CreatedAtResponse res, resBody, err := c.AssignUserIdWithHTTPInfo(r, opts...) @@ -666,12 +913,12 @@ Batching index updates reduces latency and increases data integrity. Request can be constructed by NewApiBatchRequest with parameters below. @param indexName string - Name of the index on which to perform the operation. @param batchWriteParams BatchWriteParams - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) BatchWithHTTPInfo(r ApiBatchRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) BatchWithHTTPInfo(r ApiBatchRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}/batch" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) @@ -683,22 +930,22 @@ func (c *APIClient) BatchWithHTTPInfo(r ApiBatchRequest, opts ...utils.RequestOp return nil, nil, reportError("Parameter `batchWriteParams` is required when calling `Batch`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.batchWriteParams - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -722,7 +969,7 @@ Request can be constructed by NewApiBatchRequest with parameters below. @param batchWriteParams BatchWriteParams @return BatchResponse */ -func (c *APIClient) Batch(r ApiBatchRequest, opts ...utils.RequestOption) (*BatchResponse, error) { +func (c *APIClient) Batch(r ApiBatchRequest, opts ...RequestOption) (*BatchResponse, error) { var returnValue *BatchResponse res, resBody, err := c.BatchWithHTTPInfo(r, opts...) @@ -817,12 +1064,12 @@ BatchAssignUserIds calls the API and returns the raw response from it. Request can be constructed by NewApiBatchAssignUserIdsRequest with parameters below. @param xAlgoliaUserID string - Unique identifier of the user who makes the search request. @param batchAssignUserIdsParams BatchAssignUserIdsParams - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) BatchAssignUserIdsWithHTTPInfo(r ApiBatchAssignUserIdsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) BatchAssignUserIdsWithHTTPInfo(r ApiBatchAssignUserIdsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/clusters/mapping/batch" if r.xAlgoliaUserID == "" { @@ -833,24 +1080,24 @@ func (c *APIClient) BatchAssignUserIdsWithHTTPInfo(r ApiBatchAssignUserIdsReques return nil, nil, reportError("Parameter `batchAssignUserIdsParams` is required when calling `BatchAssignUserIds`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } - options.HeaderParams["X-Algolia-User-ID"] = utils.ParameterToString(r.xAlgoliaUserID) + conf.headerParams["X-Algolia-User-ID"] = utils.ParameterToString(r.xAlgoliaUserID) // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.batchAssignUserIdsParams - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -874,7 +1121,7 @@ Request can be constructed by NewApiBatchAssignUserIdsRequest with parameters be @param batchAssignUserIdsParams BatchAssignUserIdsParams @return CreatedAtResponse */ -func (c *APIClient) BatchAssignUserIds(r ApiBatchAssignUserIdsRequest, opts ...utils.RequestOption) (*CreatedAtResponse, error) { +func (c *APIClient) BatchAssignUserIds(r ApiBatchAssignUserIdsRequest, opts ...RequestOption) (*CreatedAtResponse, error) { var returnValue *CreatedAtResponse res, resBody, err := c.BatchAssignUserIdsWithHTTPInfo(r, opts...) @@ -967,12 +1214,12 @@ BatchDictionaryEntries calls the API and returns the raw response from it. Request can be constructed by NewApiBatchDictionaryEntriesRequest with parameters below. @param dictionaryName DictionaryType - Dictionary type in which to search. @param batchDictionaryEntriesParams BatchDictionaryEntriesParams - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) BatchDictionaryEntriesWithHTTPInfo(r ApiBatchDictionaryEntriesRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) BatchDictionaryEntriesWithHTTPInfo(r ApiBatchDictionaryEntriesRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/dictionaries/{dictionaryName}/batch" requestPath = strings.ReplaceAll(requestPath, "{dictionaryName}", url.PathEscape(utils.ParameterToString(r.dictionaryName))) @@ -980,22 +1227,22 @@ func (c *APIClient) BatchDictionaryEntriesWithHTTPInfo(r ApiBatchDictionaryEntri return nil, nil, reportError("Parameter `batchDictionaryEntriesParams` is required when calling `BatchDictionaryEntries`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.batchDictionaryEntriesParams - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1017,7 +1264,7 @@ Request can be constructed by NewApiBatchDictionaryEntriesRequest with parameter @param batchDictionaryEntriesParams BatchDictionaryEntriesParams @return UpdatedAtResponse */ -func (c *APIClient) BatchDictionaryEntries(r ApiBatchDictionaryEntriesRequest, opts ...utils.RequestOption) (*UpdatedAtResponse, error) { +func (c *APIClient) BatchDictionaryEntries(r ApiBatchDictionaryEntriesRequest, opts ...RequestOption) (*UpdatedAtResponse, error) { var returnValue *UpdatedAtResponse res, resBody, err := c.BatchDictionaryEntriesWithHTTPInfo(r, opts...) @@ -1134,12 +1381,12 @@ If you send these parameters with your browse requests, they'll be ignored. Request can be constructed by NewApiBrowseRequest with parameters below. @param indexName string - Name of the index on which to perform the operation. @param browseParams BrowseParams - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) BrowseWithHTTPInfo(r ApiBrowseRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) BrowseWithHTTPInfo(r ApiBrowseRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}/browse" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) @@ -1147,15 +1394,15 @@ func (c *APIClient) BrowseWithHTTPInfo(r ApiBrowseRequest, opts ...utils.Request return nil, nil, reportError("Parameter `indexName` is required when calling `Browse`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any @@ -1166,7 +1413,7 @@ func (c *APIClient) BrowseWithHTTPInfo(r ApiBrowseRequest, opts ...utils.Request } else { postBody = r.browseParams } - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1212,7 +1459,7 @@ Request can be constructed by NewApiBrowseRequest with parameters below. @param browseParams BrowseParams @return BrowseResponse */ -func (c *APIClient) Browse(r ApiBrowseRequest, opts ...utils.RequestOption) (*BrowseResponse, error) { +func (c *APIClient) Browse(r ApiBrowseRequest, opts ...RequestOption) (*BrowseResponse, error) { var returnValue *BrowseResponse res, resBody, err := c.BrowseWithHTTPInfo(r, opts...) @@ -1288,12 +1535,12 @@ ClearObjects calls the API and returns the raw response from it. Request can be constructed by NewApiClearObjectsRequest with parameters below. @param indexName string - Name of the index on which to perform the operation. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) ClearObjectsWithHTTPInfo(r ApiClearObjectsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) ClearObjectsWithHTTPInfo(r ApiClearObjectsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}/clear" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) @@ -1301,20 +1548,20 @@ func (c *APIClient) ClearObjectsWithHTTPInfo(r ApiClearObjectsRequest, opts ...u return nil, nil, reportError("Parameter `indexName` is required when calling `ClearObjects`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1335,7 +1582,7 @@ Request can be constructed by NewApiClearObjectsRequest with parameters below. @param indexName string - Name of the index on which to perform the operation. @return UpdatedAtResponse */ -func (c *APIClient) ClearObjects(r ApiClearObjectsRequest, opts ...utils.RequestOption) (*UpdatedAtResponse, error) { +func (c *APIClient) ClearObjects(r ApiClearObjectsRequest, opts ...RequestOption) (*UpdatedAtResponse, error) { var returnValue *UpdatedAtResponse res, resBody, err := c.ClearObjectsWithHTTPInfo(r, opts...) @@ -1428,12 +1675,12 @@ ClearRules calls the API and returns the raw response from it. Request can be constructed by NewApiClearRulesRequest with parameters below. @param indexName string - Name of the index on which to perform the operation. @param forwardToReplicas bool - Whether changes are applied to replica indices. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) ClearRulesWithHTTPInfo(r ApiClearRulesRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) ClearRulesWithHTTPInfo(r ApiClearRulesRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}/rules/clear" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) @@ -1441,24 +1688,24 @@ func (c *APIClient) ClearRulesWithHTTPInfo(r ApiClearRulesRequest, opts ...utils return nil, nil, reportError("Parameter `indexName` is required when calling `ClearRules`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.forwardToReplicas) { - options.QueryParams.Set("forwardToReplicas", utils.QueryParameterToString(*r.forwardToReplicas)) + conf.queryParams.Set("forwardToReplicas", utils.QueryParameterToString(*r.forwardToReplicas)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1480,7 +1727,7 @@ Request can be constructed by NewApiClearRulesRequest with parameters below. @param forwardToReplicas bool - Whether changes are applied to replica indices. @return UpdatedAtResponse */ -func (c *APIClient) ClearRules(r ApiClearRulesRequest, opts ...utils.RequestOption) (*UpdatedAtResponse, error) { +func (c *APIClient) ClearRules(r ApiClearRulesRequest, opts ...RequestOption) (*UpdatedAtResponse, error) { var returnValue *UpdatedAtResponse res, resBody, err := c.ClearRulesWithHTTPInfo(r, opts...) @@ -1573,12 +1820,12 @@ ClearSynonyms calls the API and returns the raw response from it. Request can be constructed by NewApiClearSynonymsRequest with parameters below. @param indexName string - Name of the index on which to perform the operation. @param forwardToReplicas bool - Whether changes are applied to replica indices. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) ClearSynonymsWithHTTPInfo(r ApiClearSynonymsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) ClearSynonymsWithHTTPInfo(r ApiClearSynonymsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}/synonyms/clear" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) @@ -1586,24 +1833,24 @@ func (c *APIClient) ClearSynonymsWithHTTPInfo(r ApiClearSynonymsRequest, opts .. return nil, nil, reportError("Parameter `indexName` is required when calling `ClearSynonyms`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.forwardToReplicas) { - options.QueryParams.Set("forwardToReplicas", utils.QueryParameterToString(*r.forwardToReplicas)) + conf.queryParams.Set("forwardToReplicas", utils.QueryParameterToString(*r.forwardToReplicas)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1625,7 +1872,7 @@ Request can be constructed by NewApiClearSynonymsRequest with parameters below. @param forwardToReplicas bool - Whether changes are applied to replica indices. @return UpdatedAtResponse */ -func (c *APIClient) ClearSynonyms(r ApiClearSynonymsRequest, opts ...utils.RequestOption) (*UpdatedAtResponse, error) { +func (c *APIClient) ClearSynonyms(r ApiClearSynonymsRequest, opts ...RequestOption) (*UpdatedAtResponse, error) { var returnValue *UpdatedAtResponse res, resBody, err := c.ClearSynonymsWithHTTPInfo(r, opts...) @@ -1716,12 +1963,12 @@ CustomDelete calls the API and returns the raw response from it. Request can be constructed by NewApiCustomDeleteRequest with parameters below. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomDeleteWithHTTPInfo(r ApiCustomDeleteRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomDeleteWithHTTPInfo(r ApiCustomDeleteRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -1729,26 +1976,26 @@ func (c *APIClient) CustomDeleteWithHTTPInfo(r ApiCustomDeleteRequest, opts ...u return nil, nil, reportError("Parameter `path` is required when calling `CustomDelete`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodDelete, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodDelete, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1767,7 +2014,7 @@ Request can be constructed by NewApiCustomDeleteRequest with parameters below. @param parameters map[string]any - Query parameters to apply to the current query. @return map[string]any */ -func (c *APIClient) CustomDelete(r ApiCustomDeleteRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomDelete(r ApiCustomDeleteRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomDeleteWithHTTPInfo(r, opts...) @@ -1858,12 +2105,12 @@ CustomGet calls the API and returns the raw response from it. Request can be constructed by NewApiCustomGetRequest with parameters below. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomGetWithHTTPInfo(r ApiCustomGetRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomGetWithHTTPInfo(r ApiCustomGetRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -1871,26 +2118,26 @@ func (c *APIClient) CustomGetWithHTTPInfo(r ApiCustomGetRequest, opts ...utils.R return nil, nil, reportError("Parameter `path` is required when calling `CustomGet`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -1909,7 +2156,7 @@ Request can be constructed by NewApiCustomGetRequest with parameters below. @param parameters map[string]any - Query parameters to apply to the current query. @return map[string]any */ -func (c *APIClient) CustomGet(r ApiCustomGetRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomGet(r ApiCustomGetRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomGetWithHTTPInfo(r, opts...) @@ -2017,12 +2264,12 @@ CustomPost calls the API and returns the raw response from it. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. @param body map[string]any - Parameters to send with the custom request. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -2030,21 +2277,21 @@ func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...utils return nil, nil, reportError("Parameter `path` is required when calling `CustomPost`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any @@ -2055,7 +2302,7 @@ func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...utils } else { postBody = r.body } - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -2075,7 +2322,7 @@ Request can be constructed by NewApiCustomPostRequest with parameters below. @param body map[string]any - Parameters to send with the custom request. @return map[string]any */ -func (c *APIClient) CustomPost(r ApiCustomPostRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomPost(r ApiCustomPostRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomPostWithHTTPInfo(r, opts...) @@ -2183,12 +2430,12 @@ CustomPut calls the API and returns the raw response from it. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. @param body map[string]any - Parameters to send with the custom request. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -2196,21 +2443,21 @@ func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...utils.R return nil, nil, reportError("Parameter `path` is required when calling `CustomPut`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any @@ -2221,7 +2468,7 @@ func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...utils.R } else { postBody = r.body } - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPut, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPut, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -2241,7 +2488,7 @@ Request can be constructed by NewApiCustomPutRequest with parameters below. @param body map[string]any - Parameters to send with the custom request. @return map[string]any */ -func (c *APIClient) CustomPut(r ApiCustomPutRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomPut(r ApiCustomPutRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomPutWithHTTPInfo(r, opts...) @@ -2317,12 +2564,12 @@ DeleteApiKey calls the API and returns the raw response from it. Request can be constructed by NewApiDeleteApiKeyRequest with parameters below. @param key string - API key. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) DeleteApiKeyWithHTTPInfo(r ApiDeleteApiKeyRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) DeleteApiKeyWithHTTPInfo(r ApiDeleteApiKeyRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/keys/{key}" requestPath = strings.ReplaceAll(requestPath, "{key}", url.PathEscape(utils.ParameterToString(r.key))) @@ -2330,20 +2577,20 @@ func (c *APIClient) DeleteApiKeyWithHTTPInfo(r ApiDeleteApiKeyRequest, opts ...u return nil, nil, reportError("Parameter `key` is required when calling `DeleteApiKey`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodDelete, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodDelete, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -2364,7 +2611,7 @@ Request can be constructed by NewApiDeleteApiKeyRequest with parameters below. @param key string - API key. @return DeleteApiKeyResponse */ -func (c *APIClient) DeleteApiKey(r ApiDeleteApiKeyRequest, opts ...utils.RequestOption) (*DeleteApiKeyResponse, error) { +func (c *APIClient) DeleteApiKey(r ApiDeleteApiKeyRequest, opts ...RequestOption) (*DeleteApiKeyResponse, error) { var returnValue *DeleteApiKeyResponse res, resBody, err := c.DeleteApiKeyWithHTTPInfo(r, opts...) @@ -2460,12 +2707,12 @@ and then delete the records using the [`batch` operation](tag/Records/operation/ Request can be constructed by NewApiDeleteByRequest with parameters below. @param indexName string - Name of the index on which to perform the operation. @param deleteByParams DeleteByParams - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) DeleteByWithHTTPInfo(r ApiDeleteByRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) DeleteByWithHTTPInfo(r ApiDeleteByRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}/deleteByQuery" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) @@ -2477,22 +2724,22 @@ func (c *APIClient) DeleteByWithHTTPInfo(r ApiDeleteByRequest, opts ...utils.Req return nil, nil, reportError("Parameter `deleteByParams` is required when calling `DeleteBy`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.deleteByParams - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -2517,7 +2764,7 @@ Request can be constructed by NewApiDeleteByRequest with parameters below. @param deleteByParams DeleteByParams @return DeletedAtResponse */ -func (c *APIClient) DeleteBy(r ApiDeleteByRequest, opts ...utils.RequestOption) (*DeletedAtResponse, error) { +func (c *APIClient) DeleteBy(r ApiDeleteByRequest, opts ...RequestOption) (*DeletedAtResponse, error) { var returnValue *DeletedAtResponse res, resBody, err := c.DeleteByWithHTTPInfo(r, opts...) @@ -2603,12 +2850,12 @@ DeleteIndex calls the API and returns the raw response from it. Request can be constructed by NewApiDeleteIndexRequest with parameters below. @param indexName string - Name of the index on which to perform the operation. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) DeleteIndexWithHTTPInfo(r ApiDeleteIndexRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) DeleteIndexWithHTTPInfo(r ApiDeleteIndexRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) @@ -2616,20 +2863,20 @@ func (c *APIClient) DeleteIndexWithHTTPInfo(r ApiDeleteIndexRequest, opts ...uti return nil, nil, reportError("Parameter `indexName` is required when calling `DeleteIndex`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodDelete, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodDelete, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -2656,7 +2903,7 @@ Request can be constructed by NewApiDeleteIndexRequest with parameters below. @param indexName string - Name of the index on which to perform the operation. @return DeletedAtResponse */ -func (c *APIClient) DeleteIndex(r ApiDeleteIndexRequest, opts ...utils.RequestOption) (*DeletedAtResponse, error) { +func (c *APIClient) DeleteIndex(r ApiDeleteIndexRequest, opts ...RequestOption) (*DeletedAtResponse, error) { var returnValue *DeletedAtResponse res, resBody, err := c.DeleteIndexWithHTTPInfo(r, opts...) @@ -2747,12 +2994,12 @@ To delete records matching a query, use the [`deleteByQuery` operation](#tag/Rec Request can be constructed by NewApiDeleteObjectRequest with parameters below. @param indexName string - Name of the index on which to perform the operation. @param objectID string - Unique record identifier. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) DeleteObjectWithHTTPInfo(r ApiDeleteObjectRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) DeleteObjectWithHTTPInfo(r ApiDeleteObjectRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}/{objectID}" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) requestPath = strings.ReplaceAll(requestPath, "{objectID}", url.PathEscape(utils.ParameterToString(r.objectID))) @@ -2764,20 +3011,20 @@ func (c *APIClient) DeleteObjectWithHTTPInfo(r ApiDeleteObjectRequest, opts ...u return nil, nil, reportError("Parameter `objectID` is required when calling `DeleteObject`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodDelete, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodDelete, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -2802,7 +3049,7 @@ Request can be constructed by NewApiDeleteObjectRequest with parameters below. @param objectID string - Unique record identifier. @return DeletedAtResponse */ -func (c *APIClient) DeleteObject(r ApiDeleteObjectRequest, opts ...utils.RequestOption) (*DeletedAtResponse, error) { +func (c *APIClient) DeleteObject(r ApiDeleteObjectRequest, opts ...RequestOption) (*DeletedAtResponse, error) { var returnValue *DeletedAtResponse res, resBody, err := c.DeleteObjectWithHTTPInfo(r, opts...) @@ -2910,12 +3157,12 @@ use the [`search` operation](#tag/Rules/operation/searchRules). @param indexName string - Name of the index on which to perform the operation. @param objectID string - Unique identifier of a rule object. @param forwardToReplicas bool - Whether changes are applied to replica indices. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) DeleteRuleWithHTTPInfo(r ApiDeleteRuleRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) DeleteRuleWithHTTPInfo(r ApiDeleteRuleRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}/rules/{objectID}" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) requestPath = strings.ReplaceAll(requestPath, "{objectID}", url.PathEscape(utils.ParameterToString(r.objectID))) @@ -2927,24 +3174,24 @@ func (c *APIClient) DeleteRuleWithHTTPInfo(r ApiDeleteRuleRequest, opts ...utils return nil, nil, reportError("Parameter `objectID` is required when calling `DeleteRule`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.forwardToReplicas) { - options.QueryParams.Set("forwardToReplicas", utils.QueryParameterToString(*r.forwardToReplicas)) + conf.queryParams.Set("forwardToReplicas", utils.QueryParameterToString(*r.forwardToReplicas)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodDelete, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodDelete, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -2969,7 +3216,7 @@ Request can be constructed by NewApiDeleteRuleRequest with parameters below. @param forwardToReplicas bool - Whether changes are applied to replica indices. @return UpdatedAtResponse */ -func (c *APIClient) DeleteRule(r ApiDeleteRuleRequest, opts ...utils.RequestOption) (*UpdatedAtResponse, error) { +func (c *APIClient) DeleteRule(r ApiDeleteRuleRequest, opts ...RequestOption) (*UpdatedAtResponse, error) { var returnValue *UpdatedAtResponse res, resBody, err := c.DeleteRuleWithHTTPInfo(r, opts...) @@ -3045,12 +3292,12 @@ DeleteSource calls the API and returns the raw response from it. Request can be constructed by NewApiDeleteSourceRequest with parameters below. @param source string - IP address range of the source. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) DeleteSourceWithHTTPInfo(r ApiDeleteSourceRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) DeleteSourceWithHTTPInfo(r ApiDeleteSourceRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/security/sources/{source}" requestPath = strings.ReplaceAll(requestPath, "{source}", url.PathEscape(utils.ParameterToString(r.source))) @@ -3058,20 +3305,20 @@ func (c *APIClient) DeleteSourceWithHTTPInfo(r ApiDeleteSourceRequest, opts ...u return nil, nil, reportError("Parameter `source` is required when calling `DeleteSource`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodDelete, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodDelete, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -3092,7 +3339,7 @@ Request can be constructed by NewApiDeleteSourceRequest with parameters below. @param source string - IP address range of the source. @return DeleteSourceResponse */ -func (c *APIClient) DeleteSource(r ApiDeleteSourceRequest, opts ...utils.RequestOption) (*DeleteSourceResponse, error) { +func (c *APIClient) DeleteSource(r ApiDeleteSourceRequest, opts ...RequestOption) (*DeleteSourceResponse, error) { var returnValue *DeleteSourceResponse res, resBody, err := c.DeleteSourceWithHTTPInfo(r, opts...) @@ -3199,12 +3446,12 @@ To find the object IDs of your synonyms, use the [`search` operation](#tag/Synon @param indexName string - Name of the index on which to perform the operation. @param objectID string - Unique identifier of a synonym object. @param forwardToReplicas bool - Whether changes are applied to replica indices. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) DeleteSynonymWithHTTPInfo(r ApiDeleteSynonymRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) DeleteSynonymWithHTTPInfo(r ApiDeleteSynonymRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}/synonyms/{objectID}" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) requestPath = strings.ReplaceAll(requestPath, "{objectID}", url.PathEscape(utils.ParameterToString(r.objectID))) @@ -3216,24 +3463,24 @@ func (c *APIClient) DeleteSynonymWithHTTPInfo(r ApiDeleteSynonymRequest, opts .. return nil, nil, reportError("Parameter `objectID` is required when calling `DeleteSynonym`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.forwardToReplicas) { - options.QueryParams.Set("forwardToReplicas", utils.QueryParameterToString(*r.forwardToReplicas)) + conf.queryParams.Set("forwardToReplicas", utils.QueryParameterToString(*r.forwardToReplicas)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodDelete, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodDelete, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -3257,7 +3504,7 @@ Request can be constructed by NewApiDeleteSynonymRequest with parameters below. @param forwardToReplicas bool - Whether changes are applied to replica indices. @return DeletedAtResponse */ -func (c *APIClient) DeleteSynonym(r ApiDeleteSynonymRequest, opts ...utils.RequestOption) (*DeletedAtResponse, error) { +func (c *APIClient) DeleteSynonym(r ApiDeleteSynonymRequest, opts ...RequestOption) (*DeletedAtResponse, error) { var returnValue *DeletedAtResponse res, resBody, err := c.DeleteSynonymWithHTTPInfo(r, opts...) @@ -3333,12 +3580,12 @@ When authenticating with other API keys, you can only retrieve information for t Request can be constructed by NewApiGetApiKeyRequest with parameters below. @param key string - API key. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetApiKeyWithHTTPInfo(r ApiGetApiKeyRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetApiKeyWithHTTPInfo(r ApiGetApiKeyRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/keys/{key}" requestPath = strings.ReplaceAll(requestPath, "{key}", url.PathEscape(utils.ParameterToString(r.key))) @@ -3346,20 +3593,20 @@ func (c *APIClient) GetApiKeyWithHTTPInfo(r ApiGetApiKeyRequest, opts ...utils.R return nil, nil, reportError("Parameter `key` is required when calling `GetApiKey`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -3380,7 +3627,7 @@ Request can be constructed by NewApiGetApiKeyRequest with parameters below. @param key string - API key. @return GetApiKeyResponse */ -func (c *APIClient) GetApiKey(r ApiGetApiKeyRequest, opts ...utils.RequestOption) (*GetApiKeyResponse, error) { +func (c *APIClient) GetApiKey(r ApiGetApiKeyRequest, opts ...RequestOption) (*GetApiKeyResponse, error) { var returnValue *GetApiKeyResponse res, resBody, err := c.GetApiKeyWithHTTPInfo(r, opts...) @@ -3457,29 +3704,29 @@ GetAppTask calls the API and returns the raw response from it. Request can be constructed by NewApiGetAppTaskRequest with parameters below. @param taskID int64 - Unique task identifier. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetAppTaskWithHTTPInfo(r ApiGetAppTaskRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetAppTaskWithHTTPInfo(r ApiGetAppTaskRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/task/{taskID}" requestPath = strings.ReplaceAll(requestPath, "{taskID}", url.PathEscape(utils.ParameterToString(r.taskID))) - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -3500,7 +3747,7 @@ Request can be constructed by NewApiGetAppTaskRequest with parameters below. @param taskID int64 - Unique task identifier. @return GetTaskResponse */ -func (c *APIClient) GetAppTask(r ApiGetAppTaskRequest, opts ...utils.RequestOption) (*GetTaskResponse, error) { +func (c *APIClient) GetAppTask(r ApiGetAppTaskRequest, opts ...RequestOption) (*GetTaskResponse, error) { var returnValue *GetTaskResponse res, resBody, err := c.GetAppTaskWithHTTPInfo(r, opts...) @@ -3545,28 +3792,28 @@ GetDictionaryLanguages calls the API and returns the raw response from it. - settings Request can be constructed by NewApiGetDictionaryLanguagesRequest with parameters below. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetDictionaryLanguagesWithHTTPInfo(opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetDictionaryLanguagesWithHTTPInfo(opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/dictionaries/*/languages" - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -3586,7 +3833,7 @@ Request can be constructed by NewApiGetDictionaryLanguagesRequest with parameter @return map[string]Languages */ -func (c *APIClient) GetDictionaryLanguages(opts ...utils.RequestOption) (*map[string]Languages, error) { +func (c *APIClient) GetDictionaryLanguages(opts ...RequestOption) (*map[string]Languages, error) { var returnValue *map[string]Languages res, resBody, err := c.GetDictionaryLanguagesWithHTTPInfo(opts...) @@ -3630,28 +3877,28 @@ GetDictionarySettings calls the API and returns the raw response from it. - settings Request can be constructed by NewApiGetDictionarySettingsRequest with parameters below. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetDictionarySettingsWithHTTPInfo(opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetDictionarySettingsWithHTTPInfo(opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/dictionaries/*/settings" - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -3671,7 +3918,7 @@ Request can be constructed by NewApiGetDictionarySettingsRequest with parameters @return GetDictionarySettingsResponse */ -func (c *APIClient) GetDictionarySettings(opts ...utils.RequestOption) (*GetDictionarySettingsResponse, error) { +func (c *APIClient) GetDictionarySettings(opts ...RequestOption) (*GetDictionarySettingsResponse, error) { var returnValue *GetDictionarySettingsResponse res, resBody, err := c.GetDictionarySettingsWithHTTPInfo(opts...) @@ -3806,41 +4053,41 @@ GetLogs calls the API and returns the raw response from it. @param length int32 - Maximum number of entries to retrieve. @param indexName string - Index for which to retrieve log entries. By default, log entries are retrieved for all indices. @param type_ LogType - Type of log entries to retrieve. By default, all log entries are retrieved. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetLogsWithHTTPInfo(r ApiGetLogsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetLogsWithHTTPInfo(r ApiGetLogsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/logs" - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.offset) { - options.QueryParams.Set("offset", utils.QueryParameterToString(*r.offset)) + conf.queryParams.Set("offset", utils.QueryParameterToString(*r.offset)) } if !utils.IsNilOrEmpty(r.length) { - options.QueryParams.Set("length", utils.QueryParameterToString(*r.length)) + conf.queryParams.Set("length", utils.QueryParameterToString(*r.length)) } if !utils.IsNilOrEmpty(r.indexName) { - options.QueryParams.Set("indexName", utils.QueryParameterToString(*r.indexName)) + conf.queryParams.Set("indexName", utils.QueryParameterToString(*r.indexName)) } if !utils.IsNilOrEmpty(r.type_) { - options.QueryParams.Set("type", utils.QueryParameterToString(r.type_)) + conf.queryParams.Set("type", utils.QueryParameterToString(r.type_)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -3868,7 +4115,7 @@ Request can be constructed by NewApiGetLogsRequest with parameters below. @param type_ LogType - Type of log entries to retrieve. By default, all log entries are retrieved. @return GetLogsResponse */ -func (c *APIClient) GetLogs(r ApiGetLogsRequest, opts ...utils.RequestOption) (*GetLogsResponse, error) { +func (c *APIClient) GetLogs(r ApiGetLogsRequest, opts ...RequestOption) (*GetLogsResponse, error) { var returnValue *GetLogsResponse res, resBody, err := c.GetLogsWithHTTPInfo(r, opts...) @@ -3975,12 +4222,12 @@ To retrieve more than one record, use the [`objects` operation](#tag/Records/ope @param indexName string - Name of the index on which to perform the operation. @param objectID string - Unique record identifier. @param attributesToRetrieve []string - Attributes to include with the records in the response. This is useful to reduce the size of the API response. By default, all retrievable attributes are returned. `objectID` is always retrieved. Attributes included in `unretrievableAttributes` won't be retrieved unless the request is authenticated with the admin API key. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetObjectWithHTTPInfo(r ApiGetObjectRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetObjectWithHTTPInfo(r ApiGetObjectRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}/{objectID}" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) requestPath = strings.ReplaceAll(requestPath, "{objectID}", url.PathEscape(utils.ParameterToString(r.objectID))) @@ -3992,24 +4239,24 @@ func (c *APIClient) GetObjectWithHTTPInfo(r ApiGetObjectRequest, opts ...utils.R return nil, nil, reportError("Parameter `objectID` is required when calling `GetObject`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.attributesToRetrieve) { - options.QueryParams.Set("attributesToRetrieve", utils.QueryParameterToString(r.attributesToRetrieve)) + conf.queryParams.Set("attributesToRetrieve", utils.QueryParameterToString(r.attributesToRetrieve)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -4034,7 +4281,7 @@ Request can be constructed by NewApiGetObjectRequest with parameters below. @param attributesToRetrieve []string - Attributes to include with the records in the response. This is useful to reduce the size of the API response. By default, all retrievable attributes are returned. `objectID` is always retrieved. Attributes included in `unretrievableAttributes` won't be retrieved unless the request is authenticated with the admin API key. @return map[string]string */ -func (c *APIClient) GetObject(r ApiGetObjectRequest, opts ...utils.RequestOption) (map[string]string, error) { +func (c *APIClient) GetObject(r ApiGetObjectRequest, opts ...RequestOption) (map[string]string, error) { var returnValue map[string]string res, resBody, err := c.GetObjectWithHTTPInfo(r, opts...) @@ -4117,34 +4364,34 @@ Records are returned in the same order as the requests. Request can be constructed by NewApiGetObjectsRequest with parameters below. @param getObjectsParams GetObjectsParams - Request object. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetObjectsWithHTTPInfo(r ApiGetObjectsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetObjectsWithHTTPInfo(r ApiGetObjectsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/*/objects" if r.getObjectsParams == nil { return nil, nil, reportError("Parameter `getObjectsParams` is required when calling `GetObjects`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.getObjectsParams - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -4167,7 +4414,7 @@ Request can be constructed by NewApiGetObjectsRequest with parameters below. @param getObjectsParams GetObjectsParams - Request object. @return GetObjectsResponse */ -func (c *APIClient) GetObjects(r ApiGetObjectsRequest, opts ...utils.RequestOption) (*GetObjectsResponse, error) { +func (c *APIClient) GetObjects(r ApiGetObjectsRequest, opts ...RequestOption) (*GetObjectsResponse, error) { var returnValue *GetObjectsResponse res, resBody, err := c.GetObjectsWithHTTPInfo(r, opts...) @@ -4257,12 +4504,12 @@ To find the object ID of rules, use the [`search` operation](#tag/Rules/operatio Request can be constructed by NewApiGetRuleRequest with parameters below. @param indexName string - Name of the index on which to perform the operation. @param objectID string - Unique identifier of a rule object. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetRuleWithHTTPInfo(r ApiGetRuleRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetRuleWithHTTPInfo(r ApiGetRuleRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}/rules/{objectID}" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) requestPath = strings.ReplaceAll(requestPath, "{objectID}", url.PathEscape(utils.ParameterToString(r.objectID))) @@ -4274,20 +4521,20 @@ func (c *APIClient) GetRuleWithHTTPInfo(r ApiGetRuleRequest, opts ...utils.Reque return nil, nil, reportError("Parameter `objectID` is required when calling `GetRule`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -4310,7 +4557,7 @@ Request can be constructed by NewApiGetRuleRequest with parameters below. @param objectID string - Unique identifier of a rule object. @return Rule */ -func (c *APIClient) GetRule(r ApiGetRuleRequest, opts ...utils.RequestOption) (*Rule, error) { +func (c *APIClient) GetRule(r ApiGetRuleRequest, opts ...RequestOption) (*Rule, error) { var returnValue *Rule res, resBody, err := c.GetRuleWithHTTPInfo(r, opts...) @@ -4386,12 +4633,12 @@ GetSettings calls the API and returns the raw response from it. Request can be constructed by NewApiGetSettingsRequest with parameters below. @param indexName string - Name of the index on which to perform the operation. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetSettingsWithHTTPInfo(r ApiGetSettingsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetSettingsWithHTTPInfo(r ApiGetSettingsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}/settings" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) @@ -4399,20 +4646,20 @@ func (c *APIClient) GetSettingsWithHTTPInfo(r ApiGetSettingsRequest, opts ...uti return nil, nil, reportError("Parameter `indexName` is required when calling `GetSettings`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -4433,7 +4680,7 @@ Request can be constructed by NewApiGetSettingsRequest with parameters below. @param indexName string - Name of the index on which to perform the operation. @return IndexSettings */ -func (c *APIClient) GetSettings(r ApiGetSettingsRequest, opts ...utils.RequestOption) (*IndexSettings, error) { +func (c *APIClient) GetSettings(r ApiGetSettingsRequest, opts ...RequestOption) (*IndexSettings, error) { var returnValue *IndexSettings res, resBody, err := c.GetSettingsWithHTTPInfo(r, opts...) @@ -4477,28 +4724,28 @@ GetSources calls the API and returns the raw response from it. - admin Request can be constructed by NewApiGetSourcesRequest with parameters below. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetSourcesWithHTTPInfo(opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetSourcesWithHTTPInfo(opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/security/sources" - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -4518,7 +4765,7 @@ Request can be constructed by NewApiGetSourcesRequest with parameters below. @return []Source */ -func (c *APIClient) GetSources(opts ...utils.RequestOption) ([]Source, error) { +func (c *APIClient) GetSources(opts ...RequestOption) ([]Source, error) { var returnValue []Source res, resBody, err := c.GetSourcesWithHTTPInfo(opts...) @@ -4609,12 +4856,12 @@ use the [`search` operation](#tag/Synonyms/operation/searchSynonyms). Request can be constructed by NewApiGetSynonymRequest with parameters below. @param indexName string - Name of the index on which to perform the operation. @param objectID string - Unique identifier of a synonym object. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetSynonymWithHTTPInfo(r ApiGetSynonymRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetSynonymWithHTTPInfo(r ApiGetSynonymRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}/synonyms/{objectID}" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) requestPath = strings.ReplaceAll(requestPath, "{objectID}", url.PathEscape(utils.ParameterToString(r.objectID))) @@ -4626,20 +4873,20 @@ func (c *APIClient) GetSynonymWithHTTPInfo(r ApiGetSynonymRequest, opts ...utils return nil, nil, reportError("Parameter `objectID` is required when calling `GetSynonym`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -4663,7 +4910,7 @@ Request can be constructed by NewApiGetSynonymRequest with parameters below. @param objectID string - Unique identifier of a synonym object. @return SynonymHit */ -func (c *APIClient) GetSynonym(r ApiGetSynonymRequest, opts ...utils.RequestOption) (*SynonymHit, error) { +func (c *APIClient) GetSynonym(r ApiGetSynonymRequest, opts ...RequestOption) (*SynonymHit, error) { var returnValue *SynonymHit res, resBody, err := c.GetSynonymWithHTTPInfo(r, opts...) @@ -4757,12 +5004,12 @@ The indexing tasks' responses include a task ID that you can use to check the st Request can be constructed by NewApiGetTaskRequest with parameters below. @param indexName string - Name of the index on which to perform the operation. @param taskID int64 - Unique task identifier. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetTaskWithHTTPInfo(r ApiGetTaskRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetTaskWithHTTPInfo(r ApiGetTaskRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}/task/{taskID}" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) requestPath = strings.ReplaceAll(requestPath, "{taskID}", url.PathEscape(utils.ParameterToString(r.taskID))) @@ -4771,20 +5018,20 @@ func (c *APIClient) GetTaskWithHTTPInfo(r ApiGetTaskRequest, opts ...utils.Reque return nil, nil, reportError("Parameter `indexName` is required when calling `GetTask`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -4812,7 +5059,7 @@ Request can be constructed by NewApiGetTaskRequest with parameters below. @param taskID int64 - Unique task identifier. @return GetTaskResponse */ -func (c *APIClient) GetTask(r ApiGetTaskRequest, opts ...utils.RequestOption) (*GetTaskResponse, error) { +func (c *APIClient) GetTask(r ApiGetTaskRequest, opts ...RequestOption) (*GetTaskResponse, error) { var returnValue *GetTaskResponse res, resBody, err := c.GetTaskWithHTTPInfo(r, opts...) @@ -4859,28 +5106,28 @@ the response isn't real-time. - admin Request can be constructed by NewApiGetTopUserIdsRequest with parameters below. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetTopUserIdsWithHTTPInfo(opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetTopUserIdsWithHTTPInfo(opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/clusters/mapping/top" - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -4903,7 +5150,7 @@ Request can be constructed by NewApiGetTopUserIdsRequest with parameters below. @return GetTopUserIdsResponse */ -func (c *APIClient) GetTopUserIds(opts ...utils.RequestOption) (*GetTopUserIdsResponse, error) { +func (c *APIClient) GetTopUserIds(opts ...RequestOption) (*GetTopUserIdsResponse, error) { var returnValue *GetTopUserIdsResponse res, resBody, err := c.GetTopUserIdsWithHTTPInfo(opts...) @@ -4982,12 +5229,12 @@ the response isn't real-time. Request can be constructed by NewApiGetUserIdRequest with parameters below. @param userID string - Unique identifier of the user who makes the search request. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetUserIdWithHTTPInfo(r ApiGetUserIdRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetUserIdWithHTTPInfo(r ApiGetUserIdRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/clusters/mapping/{userID}" requestPath = strings.ReplaceAll(requestPath, "{userID}", url.PathEscape(utils.ParameterToString(r.userID))) @@ -4995,20 +5242,20 @@ func (c *APIClient) GetUserIdWithHTTPInfo(r ApiGetUserIdRequest, opts ...utils.R return nil, nil, reportError("Parameter `userID` is required when calling `GetUserId`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -5032,7 +5279,7 @@ Request can be constructed by NewApiGetUserIdRequest with parameters below. @param userID string - Unique identifier of the user who makes the search request. @return UserId */ -func (c *APIClient) GetUserId(r ApiGetUserIdRequest, opts ...utils.RequestOption) (*UserId, error) { +func (c *APIClient) GetUserId(r ApiGetUserIdRequest, opts ...RequestOption) (*UserId, error) { var returnValue *UserId res, resBody, err := c.GetUserIdWithHTTPInfo(r, opts...) @@ -5113,32 +5360,32 @@ HasPendingMappings calls the API and returns the raw response from it. Request can be constructed by NewApiHasPendingMappingsRequest with parameters below. @param getClusters bool - Whether to include the cluster's pending mapping state in the response. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) HasPendingMappingsWithHTTPInfo(r ApiHasPendingMappingsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) HasPendingMappingsWithHTTPInfo(r ApiHasPendingMappingsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/clusters/mapping/pending" - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.getClusters) { - options.QueryParams.Set("getClusters", utils.QueryParameterToString(*r.getClusters)) + conf.queryParams.Set("getClusters", utils.QueryParameterToString(*r.getClusters)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -5159,7 +5406,7 @@ Request can be constructed by NewApiHasPendingMappingsRequest with parameters be @param getClusters bool - Whether to include the cluster's pending mapping state in the response. @return HasPendingMappingsResponse */ -func (c *APIClient) HasPendingMappings(r ApiHasPendingMappingsRequest, opts ...utils.RequestOption) (*HasPendingMappingsResponse, error) { +func (c *APIClient) HasPendingMappings(r ApiHasPendingMappingsRequest, opts ...RequestOption) (*HasPendingMappingsResponse, error) { var returnValue *HasPendingMappingsResponse res, resBody, err := c.HasPendingMappingsWithHTTPInfo(r, opts...) @@ -5203,28 +5450,28 @@ ListApiKeys calls the API and returns the raw response from it. - admin Request can be constructed by NewApiListApiKeysRequest with parameters below. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) ListApiKeysWithHTTPInfo(opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) ListApiKeysWithHTTPInfo(opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/keys" - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -5244,7 +5491,7 @@ Request can be constructed by NewApiListApiKeysRequest with parameters below. @return ListApiKeysResponse */ -func (c *APIClient) ListApiKeys(opts ...utils.RequestOption) (*ListApiKeysResponse, error) { +func (c *APIClient) ListApiKeys(opts ...RequestOption) (*ListApiKeysResponse, error) { var returnValue *ListApiKeysResponse res, resBody, err := c.ListApiKeysWithHTTPInfo(opts...) @@ -5288,28 +5535,28 @@ ListClusters calls the API and returns the raw response from it. - admin Request can be constructed by NewApiListClustersRequest with parameters below. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) ListClustersWithHTTPInfo(opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) ListClustersWithHTTPInfo(opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/clusters" - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -5329,7 +5576,7 @@ Request can be constructed by NewApiListClustersRequest with parameters below. @return ListClustersResponse */ -func (c *APIClient) ListClusters(opts ...utils.RequestOption) (*ListClustersResponse, error) { +func (c *APIClient) ListClusters(opts ...RequestOption) (*ListClustersResponse, error) { var returnValue *ListClustersResponse res, resBody, err := c.ListClustersWithHTTPInfo(opts...) @@ -5428,35 +5675,35 @@ The request follows any index restrictions of the API key you use to make the re Request can be constructed by NewApiListIndicesRequest with parameters below. @param page int32 - Requested page of the API response. If `null`, the API response is not paginated. @param hitsPerPage int32 - Number of hits per page. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) ListIndicesWithHTTPInfo(r ApiListIndicesRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) ListIndicesWithHTTPInfo(r ApiListIndicesRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes" - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.page) { - options.QueryParams.Set("page", utils.QueryParameterToString(*r.page)) + conf.queryParams.Set("page", utils.QueryParameterToString(*r.page)) } if !utils.IsNilOrEmpty(r.hitsPerPage) { - options.QueryParams.Set("hitsPerPage", utils.QueryParameterToString(*r.hitsPerPage)) + conf.queryParams.Set("hitsPerPage", utils.QueryParameterToString(*r.hitsPerPage)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -5480,7 +5727,7 @@ Request can be constructed by NewApiListIndicesRequest with parameters below. @param hitsPerPage int32 - Number of hits per page. @return ListIndicesResponse */ -func (c *APIClient) ListIndices(r ApiListIndicesRequest, opts ...utils.RequestOption) (*ListIndicesResponse, error) { +func (c *APIClient) ListIndices(r ApiListIndicesRequest, opts ...RequestOption) (*ListIndicesResponse, error) { var returnValue *ListIndicesResponse res, resBody, err := c.ListIndicesWithHTTPInfo(r, opts...) @@ -5580,35 +5827,35 @@ the response isn't real-time. Request can be constructed by NewApiListUserIdsRequest with parameters below. @param page int32 - Requested page of the API response. If `null`, the API response is not paginated. @param hitsPerPage int32 - Number of hits per page. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) ListUserIdsWithHTTPInfo(r ApiListUserIdsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) ListUserIdsWithHTTPInfo(r ApiListUserIdsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/clusters/mapping" - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.page) { - options.QueryParams.Set("page", utils.QueryParameterToString(*r.page)) + conf.queryParams.Set("page", utils.QueryParameterToString(*r.page)) } if !utils.IsNilOrEmpty(r.hitsPerPage) { - options.QueryParams.Set("hitsPerPage", utils.QueryParameterToString(*r.hitsPerPage)) + conf.queryParams.Set("hitsPerPage", utils.QueryParameterToString(*r.hitsPerPage)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -5633,7 +5880,7 @@ Request can be constructed by NewApiListUserIdsRequest with parameters below. @param hitsPerPage int32 - Number of hits per page. @return ListUserIdsResponse */ -func (c *APIClient) ListUserIds(r ApiListUserIdsRequest, opts ...utils.RequestOption) (*ListUserIdsResponse, error) { +func (c *APIClient) ListUserIds(r ApiListUserIdsRequest, opts ...RequestOption) (*ListUserIdsResponse, error) { var returnValue *ListUserIdsResponse res, resBody, err := c.ListUserIdsWithHTTPInfo(r, opts...) @@ -5714,34 +5961,34 @@ MultipleBatch calls the API and returns the raw response from it. Request can be constructed by NewApiMultipleBatchRequest with parameters below. @param batchParams BatchParams - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) MultipleBatchWithHTTPInfo(r ApiMultipleBatchRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) MultipleBatchWithHTTPInfo(r ApiMultipleBatchRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/*/batch" if r.batchParams == nil { return nil, nil, reportError("Parameter `batchParams` is required when calling `MultipleBatch`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.batchParams - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -5762,7 +6009,7 @@ Request can be constructed by NewApiMultipleBatchRequest with parameters below. @param batchParams BatchParams @return MultipleBatchResponse */ -func (c *APIClient) MultipleBatch(r ApiMultipleBatchRequest, opts ...utils.RequestOption) (*MultipleBatchResponse, error) { +func (c *APIClient) MultipleBatch(r ApiMultipleBatchRequest, opts ...RequestOption) (*MultipleBatchResponse, error) { var returnValue *MultipleBatchResponse res, resBody, err := c.MultipleBatchWithHTTPInfo(r, opts...) @@ -5879,12 +6126,12 @@ OperationIndex calls the API and returns the raw response from it. Request can be constructed by NewApiOperationIndexRequest with parameters below. @param indexName string - Name of the index on which to perform the operation. @param operationIndexParams OperationIndexParams - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) OperationIndexWithHTTPInfo(r ApiOperationIndexRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) OperationIndexWithHTTPInfo(r ApiOperationIndexRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}/operation" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) @@ -5896,22 +6143,22 @@ func (c *APIClient) OperationIndexWithHTTPInfo(r ApiOperationIndexRequest, opts return nil, nil, reportError("Parameter `operationIndexParams` is required when calling `OperationIndex`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.operationIndexParams - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -5953,7 +6200,7 @@ Request can be constructed by NewApiOperationIndexRequest with parameters below. @param operationIndexParams OperationIndexParams @return UpdatedAtResponse */ -func (c *APIClient) OperationIndex(r ApiOperationIndexRequest, opts ...utils.RequestOption) (*UpdatedAtResponse, error) { +func (c *APIClient) OperationIndex(r ApiOperationIndexRequest, opts ...RequestOption) (*UpdatedAtResponse, error) { var returnValue *UpdatedAtResponse res, resBody, err := c.OperationIndexWithHTTPInfo(r, opts...) @@ -6084,12 +6331,12 @@ PartialUpdateObject calls the API and returns the raw response from it. @param objectID string - Unique record identifier. @param attributesToUpdate map[string]AttributeToUpdate - Attributes with their values. @param createIfNotExists bool - Whether to create a new record if it doesn't exist. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) PartialUpdateObjectWithHTTPInfo(r ApiPartialUpdateObjectRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) PartialUpdateObjectWithHTTPInfo(r ApiPartialUpdateObjectRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}/{objectID}/partial" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) requestPath = strings.ReplaceAll(requestPath, "{objectID}", url.PathEscape(utils.ParameterToString(r.objectID))) @@ -6108,26 +6355,26 @@ func (c *APIClient) PartialUpdateObjectWithHTTPInfo(r ApiPartialUpdateObjectRequ return nil, nil, reportError("Parameter `attributesToUpdate` is required when calling `PartialUpdateObject`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.createIfNotExists) { - options.QueryParams.Set("createIfNotExists", utils.QueryParameterToString(*r.createIfNotExists)) + conf.queryParams.Set("createIfNotExists", utils.QueryParameterToString(*r.createIfNotExists)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.attributesToUpdate - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -6157,7 +6404,7 @@ Request can be constructed by NewApiPartialUpdateObjectRequest with parameters b @param createIfNotExists bool - Whether to create a new record if it doesn't exist. @return UpdatedAtWithObjectIdResponse */ -func (c *APIClient) PartialUpdateObject(r ApiPartialUpdateObjectRequest, opts ...utils.RequestOption) (*UpdatedAtWithObjectIdResponse, error) { +func (c *APIClient) PartialUpdateObject(r ApiPartialUpdateObjectRequest, opts ...RequestOption) (*UpdatedAtWithObjectIdResponse, error) { var returnValue *UpdatedAtWithObjectIdResponse res, resBody, err := c.PartialUpdateObjectWithHTTPInfo(r, opts...) @@ -6233,12 +6480,12 @@ RemoveUserId calls the API and returns the raw response from it. Request can be constructed by NewApiRemoveUserIdRequest with parameters below. @param userID string - Unique identifier of the user who makes the search request. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) RemoveUserIdWithHTTPInfo(r ApiRemoveUserIdRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) RemoveUserIdWithHTTPInfo(r ApiRemoveUserIdRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/clusters/mapping/{userID}" requestPath = strings.ReplaceAll(requestPath, "{userID}", url.PathEscape(utils.ParameterToString(r.userID))) @@ -6246,20 +6493,20 @@ func (c *APIClient) RemoveUserIdWithHTTPInfo(r ApiRemoveUserIdRequest, opts ...u return nil, nil, reportError("Parameter `userID` is required when calling `RemoveUserId`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodDelete, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodDelete, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -6280,7 +6527,7 @@ Request can be constructed by NewApiRemoveUserIdRequest with parameters below. @param userID string - Unique identifier of the user who makes the search request. @return RemoveUserIdResponse */ -func (c *APIClient) RemoveUserId(r ApiRemoveUserIdRequest, opts ...utils.RequestOption) (*RemoveUserIdResponse, error) { +func (c *APIClient) RemoveUserId(r ApiRemoveUserIdRequest, opts ...RequestOption) (*RemoveUserIdResponse, error) { var returnValue *RemoveUserIdResponse res, resBody, err := c.RemoveUserIdWithHTTPInfo(r, opts...) @@ -6361,34 +6608,34 @@ ReplaceSources calls the API and returns the raw response from it. Request can be constructed by NewApiReplaceSourcesRequest with parameters below. @param source []Source - Allowed sources. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) ReplaceSourcesWithHTTPInfo(r ApiReplaceSourcesRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) ReplaceSourcesWithHTTPInfo(r ApiReplaceSourcesRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/security/sources" if len(r.source) == 0 { return nil, nil, reportError("Parameter `source` is required when calling `ReplaceSources`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.source - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPut, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPut, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -6409,7 +6656,7 @@ Request can be constructed by NewApiReplaceSourcesRequest with parameters below. @param source []Source - Allowed sources. @return ReplaceSourceResponse */ -func (c *APIClient) ReplaceSources(r ApiReplaceSourcesRequest, opts ...utils.RequestOption) (*ReplaceSourceResponse, error) { +func (c *APIClient) ReplaceSources(r ApiReplaceSourcesRequest, opts ...RequestOption) (*ReplaceSourceResponse, error) { var returnValue *ReplaceSourceResponse res, resBody, err := c.ReplaceSourcesWithHTTPInfo(r, opts...) @@ -6490,12 +6737,12 @@ If you create more, the oldest API keys are deleted and can't be restored. Request can be constructed by NewApiRestoreApiKeyRequest with parameters below. @param key string - API key. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) RestoreApiKeyWithHTTPInfo(r ApiRestoreApiKeyRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) RestoreApiKeyWithHTTPInfo(r ApiRestoreApiKeyRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/keys/{key}/restore" requestPath = strings.ReplaceAll(requestPath, "{key}", url.PathEscape(utils.ParameterToString(r.key))) @@ -6503,20 +6750,20 @@ func (c *APIClient) RestoreApiKeyWithHTTPInfo(r ApiRestoreApiKeyRequest, opts .. return nil, nil, reportError("Parameter `key` is required when calling `RestoreApiKey`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -6542,7 +6789,7 @@ Request can be constructed by NewApiRestoreApiKeyRequest with parameters below. @param key string - API key. @return AddApiKeyResponse */ -func (c *APIClient) RestoreApiKey(r ApiRestoreApiKeyRequest, opts ...utils.RequestOption) (*AddApiKeyResponse, error) { +func (c *APIClient) RestoreApiKey(r ApiRestoreApiKeyRequest, opts ...RequestOption) (*AddApiKeyResponse, error) { var returnValue *AddApiKeyResponse res, resBody, err := c.RestoreApiKeyWithHTTPInfo(r, opts...) @@ -6643,12 +6890,12 @@ To add, update, or replace multiple records, use the [`batch` operation](#tag/Re Request can be constructed by NewApiSaveObjectRequest with parameters below. @param indexName string - Name of the index on which to perform the operation. @param body map[string]any - The record, a schemaless object with attributes that are useful in the context of search and discovery. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) SaveObjectWithHTTPInfo(r ApiSaveObjectRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) SaveObjectWithHTTPInfo(r ApiSaveObjectRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) @@ -6660,22 +6907,22 @@ func (c *APIClient) SaveObjectWithHTTPInfo(r ApiSaveObjectRequest, opts ...utils return nil, nil, reportError("Parameter `body` is required when calling `SaveObject`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.body - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -6705,7 +6952,7 @@ Request can be constructed by NewApiSaveObjectRequest with parameters below. @param body map[string]any - The record, a schemaless object with attributes that are useful in the context of search and discovery. @return SaveObjectResponse */ -func (c *APIClient) SaveObject(r ApiSaveObjectRequest, opts ...utils.RequestOption) (*SaveObjectResponse, error) { +func (c *APIClient) SaveObject(r ApiSaveObjectRequest, opts ...RequestOption) (*SaveObjectResponse, error) { var returnValue *SaveObjectResponse res, resBody, err := c.SaveObjectWithHTTPInfo(r, opts...) @@ -6831,12 +7078,12 @@ To create or update more than one rule, use the [`batch` operation](#tag/Rules/o @param objectID string - Unique identifier of a rule object. @param rule Rule @param forwardToReplicas bool - Whether changes are applied to replica indices. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) SaveRuleWithHTTPInfo(r ApiSaveRuleRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) SaveRuleWithHTTPInfo(r ApiSaveRuleRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}/rules/{objectID}" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) requestPath = strings.ReplaceAll(requestPath, "{objectID}", url.PathEscape(utils.ParameterToString(r.objectID))) @@ -6852,26 +7099,26 @@ func (c *APIClient) SaveRuleWithHTTPInfo(r ApiSaveRuleRequest, opts ...utils.Req return nil, nil, reportError("Parameter `rule` is required when calling `SaveRule`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.forwardToReplicas) { - options.QueryParams.Set("forwardToReplicas", utils.QueryParameterToString(*r.forwardToReplicas)) + conf.queryParams.Set("forwardToReplicas", utils.QueryParameterToString(*r.forwardToReplicas)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.rule - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPut, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPut, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -6898,7 +7145,7 @@ Request can be constructed by NewApiSaveRuleRequest with parameters below. @param forwardToReplicas bool - Whether changes are applied to replica indices. @return UpdatedRuleResponse */ -func (c *APIClient) SaveRule(r ApiSaveRuleRequest, opts ...utils.RequestOption) (*UpdatedRuleResponse, error) { +func (c *APIClient) SaveRule(r ApiSaveRuleRequest, opts ...RequestOption) (*UpdatedRuleResponse, error) { var returnValue *UpdatedRuleResponse res, resBody, err := c.SaveRuleWithHTTPInfo(r, opts...) @@ -7028,12 +7275,12 @@ Otherwise, existing rules are replaced. @param rules []Rule @param forwardToReplicas bool - Whether changes are applied to replica indices. @param clearExistingRules bool - Whether existing rules should be deleted before adding this batch. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) SaveRulesWithHTTPInfo(r ApiSaveRulesRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) SaveRulesWithHTTPInfo(r ApiSaveRulesRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}/rules/batch" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) @@ -7045,29 +7292,29 @@ func (c *APIClient) SaveRulesWithHTTPInfo(r ApiSaveRulesRequest, opts ...utils.R return nil, nil, reportError("Parameter `rules` is required when calling `SaveRules`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.forwardToReplicas) { - options.QueryParams.Set("forwardToReplicas", utils.QueryParameterToString(*r.forwardToReplicas)) + conf.queryParams.Set("forwardToReplicas", utils.QueryParameterToString(*r.forwardToReplicas)) } if !utils.IsNilOrEmpty(r.clearExistingRules) { - options.QueryParams.Set("clearExistingRules", utils.QueryParameterToString(*r.clearExistingRules)) + conf.queryParams.Set("clearExistingRules", utils.QueryParameterToString(*r.clearExistingRules)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.rules - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -7094,7 +7341,7 @@ Request can be constructed by NewApiSaveRulesRequest with parameters below. @param clearExistingRules bool - Whether existing rules should be deleted before adding this batch. @return UpdatedAtResponse */ -func (c *APIClient) SaveRules(r ApiSaveRulesRequest, opts ...utils.RequestOption) (*UpdatedAtResponse, error) { +func (c *APIClient) SaveRules(r ApiSaveRulesRequest, opts ...RequestOption) (*UpdatedAtResponse, error) { var returnValue *UpdatedAtResponse res, resBody, err := c.SaveRulesWithHTTPInfo(r, opts...) @@ -7219,12 +7466,12 @@ To add multiple synonyms in a single API request, use the [`batch` operation](#t @param objectID string - Unique identifier of a synonym object. @param synonymHit SynonymHit @param forwardToReplicas bool - Whether changes are applied to replica indices. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) SaveSynonymWithHTTPInfo(r ApiSaveSynonymRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) SaveSynonymWithHTTPInfo(r ApiSaveSynonymRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}/synonyms/{objectID}" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) requestPath = strings.ReplaceAll(requestPath, "{objectID}", url.PathEscape(utils.ParameterToString(r.objectID))) @@ -7240,26 +7487,26 @@ func (c *APIClient) SaveSynonymWithHTTPInfo(r ApiSaveSynonymRequest, opts ...uti return nil, nil, reportError("Parameter `synonymHit` is required when calling `SaveSynonym`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.forwardToReplicas) { - options.QueryParams.Set("forwardToReplicas", utils.QueryParameterToString(*r.forwardToReplicas)) + conf.queryParams.Set("forwardToReplicas", utils.QueryParameterToString(*r.forwardToReplicas)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.synonymHit - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPut, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPut, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -7285,7 +7532,7 @@ Request can be constructed by NewApiSaveSynonymRequest with parameters below. @param forwardToReplicas bool - Whether changes are applied to replica indices. @return SaveSynonymResponse */ -func (c *APIClient) SaveSynonym(r ApiSaveSynonymRequest, opts ...utils.RequestOption) (*SaveSynonymResponse, error) { +func (c *APIClient) SaveSynonym(r ApiSaveSynonymRequest, opts ...RequestOption) (*SaveSynonymResponse, error) { var returnValue *SaveSynonymResponse res, resBody, err := c.SaveSynonymWithHTTPInfo(r, opts...) @@ -7414,12 +7661,12 @@ Otherwise, existing synonyms are replaced. @param synonymHit []SynonymHit @param forwardToReplicas bool - Whether changes are applied to replica indices. @param replaceExistingSynonyms bool - Whether to replace all synonyms in the index with the ones sent with this request. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) SaveSynonymsWithHTTPInfo(r ApiSaveSynonymsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) SaveSynonymsWithHTTPInfo(r ApiSaveSynonymsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}/synonyms/batch" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) @@ -7431,29 +7678,29 @@ func (c *APIClient) SaveSynonymsWithHTTPInfo(r ApiSaveSynonymsRequest, opts ...u return nil, nil, reportError("Parameter `synonymHit` is required when calling `SaveSynonyms`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.forwardToReplicas) { - options.QueryParams.Set("forwardToReplicas", utils.QueryParameterToString(*r.forwardToReplicas)) + conf.queryParams.Set("forwardToReplicas", utils.QueryParameterToString(*r.forwardToReplicas)) } if !utils.IsNilOrEmpty(r.replaceExistingSynonyms) { - options.QueryParams.Set("replaceExistingSynonyms", utils.QueryParameterToString(*r.replaceExistingSynonyms)) + conf.queryParams.Set("replaceExistingSynonyms", utils.QueryParameterToString(*r.replaceExistingSynonyms)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.synonymHit - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -7478,7 +7725,7 @@ Request can be constructed by NewApiSaveSynonymsRequest with parameters below. @param replaceExistingSynonyms bool - Whether to replace all synonyms in the index with the ones sent with this request. @return UpdatedAtResponse */ -func (c *APIClient) SaveSynonyms(r ApiSaveSynonymsRequest, opts ...utils.RequestOption) (*UpdatedAtResponse, error) { +func (c *APIClient) SaveSynonyms(r ApiSaveSynonymsRequest, opts ...RequestOption) (*UpdatedAtResponse, error) { var returnValue *UpdatedAtResponse res, resBody, err := c.SaveSynonymsWithHTTPInfo(r, opts...) @@ -7564,34 +7811,34 @@ This can be useful in these cases: Request can be constructed by NewApiSearchRequest with parameters below. @param searchMethodParams SearchMethodParams - Muli-search request body. Results are returned in the same order as the requests. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) SearchWithHTTPInfo(r ApiSearchRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) SearchWithHTTPInfo(r ApiSearchRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/*/queries" if r.searchMethodParams == nil { return nil, nil, reportError("Parameter `searchMethodParams` is required when calling `Search`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.searchMethodParams - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -7617,7 +7864,7 @@ Request can be constructed by NewApiSearchRequest with parameters below. @param searchMethodParams SearchMethodParams - Muli-search request body. Results are returned in the same order as the requests. @return SearchResponses */ -func (c *APIClient) Search(r ApiSearchRequest, opts ...utils.RequestOption) (*SearchResponses, error) { +func (c *APIClient) Search(r ApiSearchRequest, opts ...RequestOption) (*SearchResponses, error) { var returnValue *SearchResponses res, resBody, err := c.SearchWithHTTPInfo(r, opts...) @@ -7710,12 +7957,12 @@ SearchDictionaryEntries calls the API and returns the raw response from it. Request can be constructed by NewApiSearchDictionaryEntriesRequest with parameters below. @param dictionaryName DictionaryType - Dictionary type in which to search. @param searchDictionaryEntriesParams SearchDictionaryEntriesParams - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) SearchDictionaryEntriesWithHTTPInfo(r ApiSearchDictionaryEntriesRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) SearchDictionaryEntriesWithHTTPInfo(r ApiSearchDictionaryEntriesRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/dictionaries/{dictionaryName}/search" requestPath = strings.ReplaceAll(requestPath, "{dictionaryName}", url.PathEscape(utils.ParameterToString(r.dictionaryName))) @@ -7723,22 +7970,22 @@ func (c *APIClient) SearchDictionaryEntriesWithHTTPInfo(r ApiSearchDictionaryEnt return nil, nil, reportError("Parameter `searchDictionaryEntriesParams` is required when calling `SearchDictionaryEntries`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.searchDictionaryEntriesParams - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -7760,7 +8007,7 @@ Request can be constructed by NewApiSearchDictionaryEntriesRequest with paramete @param searchDictionaryEntriesParams SearchDictionaryEntriesParams @return SearchDictionaryEntriesResponse */ -func (c *APIClient) SearchDictionaryEntries(r ApiSearchDictionaryEntriesRequest, opts ...utils.RequestOption) (*SearchDictionaryEntriesResponse, error) { +func (c *APIClient) SearchDictionaryEntries(r ApiSearchDictionaryEntriesRequest, opts ...RequestOption) (*SearchDictionaryEntriesResponse, error) { var returnValue *SearchDictionaryEntriesResponse res, resBody, err := c.SearchDictionaryEntriesWithHTTPInfo(r, opts...) @@ -7871,12 +8118,12 @@ SearchForFacetValues calls the API and returns the raw response from it. @param indexName string - Name of the index on which to perform the operation. @param facetName string - Facet attribute in which to search for values. This attribute must be included in the `attributesForFaceting` index setting with the `searchable()` modifier. @param searchForFacetValuesRequest SearchForFacetValuesRequest - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) SearchForFacetValuesWithHTTPInfo(r ApiSearchForFacetValuesRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) SearchForFacetValuesWithHTTPInfo(r ApiSearchForFacetValuesRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}/facets/{facetName}/query" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) requestPath = strings.ReplaceAll(requestPath, "{facetName}", url.PathEscape(utils.ParameterToString(r.facetName))) @@ -7888,15 +8135,15 @@ func (c *APIClient) SearchForFacetValuesWithHTTPInfo(r ApiSearchForFacetValuesRe return nil, nil, reportError("Parameter `facetName` is required when calling `SearchForFacetValues`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any @@ -7907,7 +8154,7 @@ func (c *APIClient) SearchForFacetValuesWithHTTPInfo(r ApiSearchForFacetValuesRe } else { postBody = r.searchForFacetValuesRequest } - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -7934,7 +8181,7 @@ Request can be constructed by NewApiSearchForFacetValuesRequest with parameters @param searchForFacetValuesRequest SearchForFacetValuesRequest @return SearchForFacetValuesResponse */ -func (c *APIClient) SearchForFacetValues(r ApiSearchForFacetValuesRequest, opts ...utils.RequestOption) (*SearchForFacetValuesResponse, error) { +func (c *APIClient) SearchForFacetValues(r ApiSearchForFacetValuesRequest, opts ...RequestOption) (*SearchForFacetValuesResponse, error) { var returnValue *SearchForFacetValuesResponse res, resBody, err := c.SearchForFacetValuesWithHTTPInfo(r, opts...) @@ -8027,12 +8274,12 @@ SearchRules calls the API and returns the raw response from it. Request can be constructed by NewApiSearchRulesRequest with parameters below. @param indexName string - Name of the index on which to perform the operation. @param searchRulesParams SearchRulesParams - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) SearchRulesWithHTTPInfo(r ApiSearchRulesRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) SearchRulesWithHTTPInfo(r ApiSearchRulesRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}/rules/search" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) @@ -8040,15 +8287,15 @@ func (c *APIClient) SearchRulesWithHTTPInfo(r ApiSearchRulesRequest, opts ...uti return nil, nil, reportError("Parameter `indexName` is required when calling `SearchRules`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any @@ -8059,7 +8306,7 @@ func (c *APIClient) SearchRulesWithHTTPInfo(r ApiSearchRulesRequest, opts ...uti } else { postBody = r.searchRulesParams } - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -8081,7 +8328,7 @@ Request can be constructed by NewApiSearchRulesRequest with parameters below. @param searchRulesParams SearchRulesParams @return SearchRulesResponse */ -func (c *APIClient) SearchRules(r ApiSearchRulesRequest, opts ...utils.RequestOption) (*SearchRulesResponse, error) { +func (c *APIClient) SearchRules(r ApiSearchRulesRequest, opts ...RequestOption) (*SearchRulesResponse, error) { var returnValue *SearchRulesResponse res, resBody, err := c.SearchRulesWithHTTPInfo(r, opts...) @@ -8177,12 +8424,12 @@ If you need more, use the [`browse` operation](#tag/Search/operation/browse) or Request can be constructed by NewApiSearchSingleIndexRequest with parameters below. @param indexName string - Name of the index on which to perform the operation. @param searchParams SearchParams - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) SearchSingleIndexWithHTTPInfo(r ApiSearchSingleIndexRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) SearchSingleIndexWithHTTPInfo(r ApiSearchSingleIndexRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}/query" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) @@ -8190,15 +8437,15 @@ func (c *APIClient) SearchSingleIndexWithHTTPInfo(r ApiSearchSingleIndexRequest, return nil, nil, reportError("Parameter `indexName` is required when calling `SearchSingleIndex`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any @@ -8209,7 +8456,7 @@ func (c *APIClient) SearchSingleIndexWithHTTPInfo(r ApiSearchSingleIndexRequest, } else { postBody = r.searchParams } - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -8234,7 +8481,7 @@ Request can be constructed by NewApiSearchSingleIndexRequest with parameters bel @param searchParams SearchParams @return SearchResponse */ -func (c *APIClient) SearchSingleIndex(r ApiSearchSingleIndexRequest, opts ...utils.RequestOption) (*SearchResponse, error) { +func (c *APIClient) SearchSingleIndex(r ApiSearchSingleIndexRequest, opts ...RequestOption) (*SearchResponse, error) { var returnValue *SearchResponse res, resBody, err := c.SearchSingleIndexWithHTTPInfo(r, opts...) @@ -8327,12 +8574,12 @@ SearchSynonyms calls the API and returns the raw response from it. Request can be constructed by NewApiSearchSynonymsRequest with parameters below. @param indexName string - Name of the index on which to perform the operation. @param searchSynonymsParams SearchSynonymsParams - Body of the `searchSynonyms` operation. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) SearchSynonymsWithHTTPInfo(r ApiSearchSynonymsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) SearchSynonymsWithHTTPInfo(r ApiSearchSynonymsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}/synonyms/search" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) @@ -8340,15 +8587,15 @@ func (c *APIClient) SearchSynonymsWithHTTPInfo(r ApiSearchSynonymsRequest, opts return nil, nil, reportError("Parameter `indexName` is required when calling `SearchSynonyms`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any @@ -8359,7 +8606,7 @@ func (c *APIClient) SearchSynonymsWithHTTPInfo(r ApiSearchSynonymsRequest, opts } else { postBody = r.searchSynonymsParams } - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -8381,7 +8628,7 @@ Request can be constructed by NewApiSearchSynonymsRequest with parameters below. @param searchSynonymsParams SearchSynonymsParams - Body of the `searchSynonyms` operation. @return SearchSynonymsResponse */ -func (c *APIClient) SearchSynonyms(r ApiSearchSynonymsRequest, opts ...utils.RequestOption) (*SearchSynonymsResponse, error) { +func (c *APIClient) SearchSynonyms(r ApiSearchSynonymsRequest, opts ...RequestOption) (*SearchSynonymsResponse, error) { var returnValue *SearchSynonymsResponse res, resBody, err := c.SearchSynonymsWithHTTPInfo(r, opts...) @@ -8466,34 +8713,34 @@ To ensure rapid updates, the user IDs index isn't built at the same time as the Request can be constructed by NewApiSearchUserIdsRequest with parameters below. @param searchUserIdsParams SearchUserIdsParams - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) SearchUserIdsWithHTTPInfo(r ApiSearchUserIdsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) SearchUserIdsWithHTTPInfo(r ApiSearchUserIdsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/clusters/mapping/search" if r.searchUserIdsParams == nil { return nil, nil, reportError("Parameter `searchUserIdsParams` is required when calling `SearchUserIds`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.searchUserIdsParams - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -8517,7 +8764,7 @@ Request can be constructed by NewApiSearchUserIdsRequest with parameters below. @param searchUserIdsParams SearchUserIdsParams @return SearchUserIdsResponse */ -func (c *APIClient) SearchUserIds(r ApiSearchUserIdsRequest, opts ...utils.RequestOption) (*SearchUserIdsResponse, error) { +func (c *APIClient) SearchUserIds(r ApiSearchUserIdsRequest, opts ...RequestOption) (*SearchUserIdsResponse, error) { var returnValue *SearchUserIdsResponse res, resBody, err := c.SearchUserIdsWithHTTPInfo(r, opts...) @@ -8598,34 +8845,34 @@ SetDictionarySettings calls the API and returns the raw response from it. Request can be constructed by NewApiSetDictionarySettingsRequest with parameters below. @param dictionarySettingsParams DictionarySettingsParams - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) SetDictionarySettingsWithHTTPInfo(r ApiSetDictionarySettingsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) SetDictionarySettingsWithHTTPInfo(r ApiSetDictionarySettingsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/dictionaries/*/settings" if r.dictionarySettingsParams == nil { return nil, nil, reportError("Parameter `dictionarySettingsParams` is required when calling `SetDictionarySettings`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.dictionarySettingsParams - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPut, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPut, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -8646,7 +8893,7 @@ Request can be constructed by NewApiSetDictionarySettingsRequest with parameters @param dictionarySettingsParams DictionarySettingsParams @return UpdatedAtResponse */ -func (c *APIClient) SetDictionarySettings(r ApiSetDictionarySettingsRequest, opts ...utils.RequestOption) (*UpdatedAtResponse, error) { +func (c *APIClient) SetDictionarySettings(r ApiSetDictionarySettingsRequest, opts ...RequestOption) (*UpdatedAtResponse, error) { var returnValue *UpdatedAtResponse res, resBody, err := c.SetDictionarySettingsWithHTTPInfo(r, opts...) @@ -8761,12 +9008,12 @@ For best performance, update the index settings before you add new records to yo @param indexName string - Name of the index on which to perform the operation. @param indexSettings IndexSettings @param forwardToReplicas bool - Whether changes are applied to replica indices. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) SetSettingsWithHTTPInfo(r ApiSetSettingsRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) SetSettingsWithHTTPInfo(r ApiSetSettingsRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/indexes/{indexName}/settings" requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) @@ -8778,26 +9025,26 @@ func (c *APIClient) SetSettingsWithHTTPInfo(r ApiSetSettingsRequest, opts ...uti return nil, nil, reportError("Parameter `indexSettings` is required when calling `SetSettings`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.forwardToReplicas) { - options.QueryParams.Set("forwardToReplicas", utils.QueryParameterToString(*r.forwardToReplicas)) + conf.queryParams.Set("forwardToReplicas", utils.QueryParameterToString(*r.forwardToReplicas)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.indexSettings - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPut, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPut, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -8825,7 +9072,7 @@ Request can be constructed by NewApiSetSettingsRequest with parameters below. @param forwardToReplicas bool - Whether changes are applied to replica indices. @return UpdatedAtResponse */ -func (c *APIClient) SetSettings(r ApiSetSettingsRequest, opts ...utils.RequestOption) (*UpdatedAtResponse, error) { +func (c *APIClient) SetSettings(r ApiSetSettingsRequest, opts ...RequestOption) (*UpdatedAtResponse, error) { var returnValue *UpdatedAtResponse res, resBody, err := c.SetSettingsWithHTTPInfo(r, opts...) @@ -8920,12 +9167,12 @@ Any unspecified attribute resets that attribute to its default value. Request can be constructed by NewApiUpdateApiKeyRequest with parameters below. @param key string - API key. @param apiKey ApiKey - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) UpdateApiKeyWithHTTPInfo(r ApiUpdateApiKeyRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) UpdateApiKeyWithHTTPInfo(r ApiUpdateApiKeyRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/keys/{key}" requestPath = strings.ReplaceAll(requestPath, "{key}", url.PathEscape(utils.ParameterToString(r.key))) @@ -8937,22 +9184,22 @@ func (c *APIClient) UpdateApiKeyWithHTTPInfo(r ApiUpdateApiKeyRequest, opts ...u return nil, nil, reportError("Parameter `apiKey` is required when calling `UpdateApiKey`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any // body params postBody = r.apiKey - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPut, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPut, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -8976,7 +9223,7 @@ Request can be constructed by NewApiUpdateApiKeyRequest with parameters below. @param apiKey ApiKey @return UpdateApiKeyResponse */ -func (c *APIClient) UpdateApiKey(r ApiUpdateApiKeyRequest, opts ...utils.RequestOption) (*UpdateApiKeyResponse, error) { +func (c *APIClient) UpdateApiKey(r ApiUpdateApiKeyRequest, opts ...RequestOption) (*UpdateApiKeyResponse, error) { var returnValue *UpdateApiKeyResponse res, resBody, err := c.UpdateApiKeyWithHTTPInfo(r, opts...) @@ -9011,16 +9258,70 @@ func (c *APIClient) UpdateApiKey(r ApiUpdateApiKeyRequest, opts ...utils.Request return returnValue, nil } +type IterableError struct { + Validate func(any, error) bool + Message func(any, error) string +} + +func CreateIterable[T any](execute func(*T, error) (*T, error), validate func(*T, error) bool, opts ...IterableOption) (*T, error) { + conf := config{ + maxRetries: 50, + timeout: func(_ int) time.Duration { + return 1 * time.Second + }, + } + + for _, opt := range opts { + opt.apply(&conf) + } + + var executor func(*T, error) (*T, error) + + retryCount := 0 + + executor = func(previousResponse *T, previousError error) (*T, error) { + response, responseErr := execute(previousResponse, previousError) + + retryCount++ + + if conf.aggregator != nil { + conf.aggregator(response, responseErr) + } + + if validate(response, responseErr) { + return response, nil + } + + if retryCount >= conf.maxRetries { + return nil, errs.NewWaitError(fmt.Sprintf("The maximum number of retries exceeded. (%d/%d)", retryCount, conf.maxRetries)) + } + + if conf.iterableError != nil && conf.iterableError.Validate(response, responseErr) { + if conf.iterableError.Message != nil { + return nil, errs.NewWaitError(conf.iterableError.Message(response, responseErr)) + } + + return nil, errs.NewWaitError("an error occurred") + } + + time.Sleep(conf.timeout(retryCount)) + + return executor(response, responseErr) + } + + return executor(nil, nil) +} + /* SearchForHits calls the `search` method but with certainty that we will only request Algolia records (hits) and not facets. Disclaimer: We don't assert that the parameters you pass to this method only contains `hits` requests to prevent impacting search performances, this helper is purely for typing purposes. @param r ApiSearchRequest - Body of the `search` operation. - @param opts ...utils.RequestOption - Optional parameters for the request. + @param opts ...RequestOption - Optional parameters for the request. @return []SearchResponse - List of hits. @return error - Error if any. */ -func (c *APIClient) SearchForHits(r ApiSearchRequest, opts ...utils.RequestOption) ([]SearchResponse, error) { +func (c *APIClient) SearchForHits(r ApiSearchRequest, opts ...RequestOption) ([]SearchResponse, error) { res, err := c.Search(r, opts...) if err != nil { return nil, err @@ -9042,11 +9343,11 @@ SearchForFacets calls the `search` method but with certainty that we will only r Disclaimer: We don't assert that the parameters you pass to this method only contains `facets` requests to prevent impacting search performances, this helper is purely for typing purposes. @param r ApiSearchRequest - Body of the `search` operation. - @param opts ...utils.RequestOption - Optional parameters for the request. + @param opts ...RequestOption - Optional parameters for the request. @return []SearchForFacetValuesResponse - List of facet hits. @return error - Error if any. */ -func (c *APIClient) SearchForFacets(r ApiSearchRequest, opts ...utils.RequestOption) ([]SearchForFacetValuesResponse, error) { +func (c *APIClient) SearchForFacets(r ApiSearchRequest, opts ...RequestOption) ([]SearchForFacetValuesResponse, error) { res, err := c.Search(r, opts...) if err != nil { return nil, err @@ -9070,23 +9371,23 @@ It returns an error if the operation failed. @param indexName string - Index name. @param taskID int64 - Task ID. - @param opts ...utils.IterableOption - Optional parameters for the request. + @param opts ...IterableOption - Optional parameters for the request. @return *GetTaskResponse - Task response. @return error - Error if any. */ func (c *APIClient) WaitForTask( indexName string, taskID int64, - opts ...utils.IterableOption, + opts ...IterableOption, ) (*GetTaskResponse, error) { // provide a defalut timeout function - opts = append([]utils.IterableOption{utils.WithTimeout(func(count int) time.Duration { + opts = append([]IterableOption{WithTimeout(func(count int) time.Duration { return time.Duration(min(200*count, 5000)) * time.Millisecond })}, opts...) - return utils.CreateIterable( //nolint:wrapcheck + return CreateIterable( func(*GetTaskResponse, error) (*GetTaskResponse, error) { - return c.GetTask(c.NewApiGetTaskRequest(indexName, taskID), utils.ToRequestOptions(opts)...) + return c.GetTask(c.NewApiGetTaskRequest(indexName, taskID), toRequestOptions(opts)...) }, func(response *GetTaskResponse, err error) bool { if err != nil || response == nil { @@ -9105,22 +9406,22 @@ It returns the task response if the operation was successful. It returns an error if the operation failed. @param taskID int64 - Task ID. - @param opts ...utils.IterableOption - Optional parameters for the request. + @param opts ...IterableOption - Optional parameters for the request. @return *GetTaskResponse - Task response. @return error - Error if any. */ func (c *APIClient) WaitForAppTask( taskID int64, - opts ...utils.IterableOption, + opts ...IterableOption, ) (*GetTaskResponse, error) { // provide a defalut timeout function - opts = append([]utils.IterableOption{utils.WithTimeout(func(count int) time.Duration { + opts = append([]IterableOption{WithTimeout(func(count int) time.Duration { return time.Duration(min(200*count, 5000)) * time.Millisecond })}, opts...) - return utils.CreateIterable( //nolint:wrapcheck + return CreateIterable( func(*GetTaskResponse, error) (*GetTaskResponse, error) { - return c.GetAppTask(c.NewApiGetAppTaskRequest(taskID), utils.ToRequestOptions(opts)...) + return c.GetAppTask(c.NewApiGetAppTaskRequest(taskID), toRequestOptions(opts)...) }, func(response *GetTaskResponse, err error) bool { if err != nil || response == nil { @@ -9133,6 +9434,24 @@ func (c *APIClient) WaitForAppTask( ) } +func slicesEqualUnordered[T cmp.Ordered](a []T, b []T) bool { + if len(a) != len(b) { + return false + } + + // make a copy and sort it to avoid modifying the original slice + aCopy := make([]T, len(a)) + copy(aCopy, a) + + bCopy := make([]T, len(b)) + copy(bCopy, b) + + slices.Sort(aCopy) + slices.Sort(bCopy) + + return slices.Equal(aCopy, bCopy) +} + /* WaitForApiKey waits for an API key to be created, deleted or updated. It returns the API key response if the operation was successful. @@ -9146,32 +9465,28 @@ The operation can be one of the following: If the operation is "update", the apiKey parameter must be set. If the operation is "delete" or "add", the apiKey parameter is not used. - @param operation ApiKeyOperation - Operation type - add, delete or update. @param key string - API key. - @param apiKey *ApiKey - API key structure - required for update operation. - @param opts ...utils.IterableOption - Optional parameters for the request. + @param operation ApiKeyOperation - Operation type - add, delete or update. + @param opts ...WaitForApiKeyOption - Optional parameters for the request, you must provide WithApiKey if the operation is "update". @return *GetApiKeyResponse - API key response. @return error - Error if any. */ func (c *APIClient) WaitForApiKey( - operation ApiKeyOperation, key string, - apiKey *ApiKey, - opts ...utils.IterableOption, + operation ApiKeyOperation, + opts ...WaitForApiKeyOption, ) (*GetApiKeyResponse, error) { - if operation != API_KEY_OPERATION_ADD && operation != API_KEY_OPERATION_DELETE && operation != API_KEY_OPERATION_UPDATE { - return nil, &errs.WaitKeyOperationError{} - } + conf := config{} - // provide a defalut timeout function - opts = append([]utils.IterableOption{utils.WithTimeout(func(count int) time.Duration { - return time.Duration(min(200*count, 5000)) * time.Millisecond - })}, opts...) + for _, opt := range opts { + opt.apply(&conf) + } var validateFunc func(*GetApiKeyResponse, error) bool - if operation == API_KEY_OPERATION_UPDATE { - if apiKey == nil { + switch operation { + case API_KEY_OPERATION_UPDATE: + if conf.apiKey == nil { return nil, &errs.WaitKeyUpdateError{} } @@ -9180,75 +9495,66 @@ func (c *APIClient) WaitForApiKey( return false } - if apiKey.GetDescription() != response.GetDescription() { + if conf.apiKey.GetDescription() != response.GetDescription() { return false } - if apiKey.GetQueryParameters() != response.GetQueryParameters() { + if conf.apiKey.GetQueryParameters() != response.GetQueryParameters() { return false } - if apiKey.GetMaxHitsPerQuery() != response.GetMaxHitsPerQuery() { + if conf.apiKey.GetMaxHitsPerQuery() != response.GetMaxHitsPerQuery() { return false } - if apiKey.GetMaxQueriesPerIPPerHour() != response.GetMaxQueriesPerIPPerHour() { + if conf.apiKey.GetMaxQueriesPerIPPerHour() != response.GetMaxQueriesPerIPPerHour() { return false } - if apiKey.GetValidity() != response.GetValidity() { + if conf.apiKey.GetValidity() != response.GetValidity() { return false } - slices.Sort(apiKey.Acl) - slices.Sort(response.Acl) - - if !slices.Equal(apiKey.Acl, response.Acl) { + if !slicesEqualUnordered(conf.apiKey.Acl, response.Acl) { return false } - slices.Sort(apiKey.Indexes) - slices.Sort(response.Indexes) - - if !slices.Equal(apiKey.Indexes, response.Indexes) { + if !slicesEqualUnordered(conf.apiKey.Indexes, response.Indexes) { return false } - slices.Sort(apiKey.Referers) - slices.Sort(response.Referers) - - return slices.Equal(apiKey.Referers, response.Referers) + return slicesEqualUnordered(conf.apiKey.Referers, response.Referers) } - } else { + case API_KEY_OPERATION_ADD: validateFunc = func(response *GetApiKeyResponse, err error) bool { - switch operation { - case API_KEY_OPERATION_ADD: - if _, ok := err.(*APIError); ok { - apiErr := err.(*APIError) - - return apiErr.Status != 404 - } - - return true - case API_KEY_OPERATION_DELETE: - if _, ok := err.(*APIError); ok { - apiErr := err.(*APIError) + var apiErr *APIError + if errors.As(err, &apiErr) { + return apiErr.Status != 404 + } - return apiErr.Status == 404 - } + return true + } + case API_KEY_OPERATION_DELETE: + validateFunc = func(response *GetApiKeyResponse, err error) bool { + var apiErr *APIError - return false - } - return false + return errors.As(err, &apiErr) && apiErr.Status == 404 } + default: + return nil, &errs.WaitKeyOperationError{} } - return utils.CreateIterable( //nolint:wrapcheck + // provide a defalut timeout function + opts = append([]WaitForApiKeyOption{WithTimeout(func(count int) time.Duration { + return time.Duration(min(200*count, 5000)) * time.Millisecond + })}, opts...) + + return CreateIterable( func(*GetApiKeyResponse, error) (*GetApiKeyResponse, error) { - return c.GetApiKey(c.NewApiGetApiKeyRequest(key), utils.ToRequestOptions(opts)...) + return c.GetApiKey(c.NewApiGetApiKeyRequest(key), toRequestOptions(opts)...) }, validateFunc, - opts..., + toIterableOptionsWaitFor(opts)..., ) } @@ -9257,16 +9563,16 @@ BrowseObjects allows to aggregate all the hits returned by the API calls. @param indexName string - Index name. @param browseParams BrowseParamsObject - Browse parameters. - @param opts ...utils.IterableOption - Optional parameters for the request. + @param opts ...IterableOption - Optional parameters for the request. @return *BrowseResponse - Browse response. @return error - Error if any. */ func (c *APIClient) BrowseObjects( indexName string, browseParams BrowseParamsObject, - opts ...utils.IterableOption, + opts ...IterableOption, ) (*BrowseResponse, error) { - return utils.CreateIterable( //nolint:wrapcheck + return CreateIterable( func(previousResponse *BrowseResponse, previousErr error) (*BrowseResponse, error) { if previousResponse != nil { browseParams.Cursor = previousResponse.Cursor @@ -9274,7 +9580,7 @@ func (c *APIClient) BrowseObjects( return c.Browse( c.NewApiBrowseRequest(indexName).WithBrowseParams(BrowseParamsObjectAsBrowseParams(&browseParams)), - utils.ToRequestOptions(opts)..., + toRequestOptions(opts)..., ) }, func(response *BrowseResponse, responseErr error) bool { @@ -9289,21 +9595,21 @@ BrowseRules allows to aggregate all the rules returned by the API calls. @param indexName string - Index name. @param searchRulesParams SearchRulesParams - Search rules parameters. - @param opts ...utils.IterableOption - Optional parameters for the request. + @param opts ...IterableOption - Optional parameters for the request. @return *SearchRulesResponse - Search rules response. @return error - Error if any. */ func (c *APIClient) BrowseRules( indexName string, searchRulesParams SearchRulesParams, - opts ...utils.IterableOption, + opts ...IterableOption, ) (*SearchRulesResponse, error) { hitsPerPage := int32(1000) if searchRulesParams.HitsPerPage != nil { hitsPerPage = *searchRulesParams.HitsPerPage } - return utils.CreateIterable( //nolint:wrapcheck + return CreateIterable( func(previousResponse *SearchRulesResponse, previousErr error) (*SearchRulesResponse, error) { searchRulesParams.HitsPerPage = &hitsPerPage @@ -9317,7 +9623,7 @@ func (c *APIClient) BrowseRules( return c.SearchRules( c.NewApiSearchRulesRequest(indexName).WithSearchRulesParams(&searchRulesParams), - utils.ToRequestOptions(opts)..., + toRequestOptions(opts)..., ) }, func(response *SearchRulesResponse, responseErr error) bool { @@ -9332,14 +9638,14 @@ BrowseSynonyms allows to aggregate all the synonyms returned by the API calls. @param indexName string - Index name. @param searchSynonymsParams SearchSynonymsParams - Search synonyms parameters. - @param opts ...utils.IterableOption - Optional parameters for the request. + @param opts ...IterableOption - Optional parameters for the request. @return *SearchSynonymsResponse - Search synonyms response. @return error - Error if any. */ func (c *APIClient) BrowseSynonyms( indexName string, searchSynonymsParams SearchSynonymsParams, - opts ...utils.IterableOption, + opts ...IterableOption, ) (*SearchSynonymsResponse, error) { hitsPerPage := int32(1000) if searchSynonymsParams.HitsPerPage != nil { @@ -9350,7 +9656,7 @@ func (c *APIClient) BrowseSynonyms( searchSynonymsParams.Page = utils.ToPtr(int32(0)) } - return utils.CreateIterable( //nolint:wrapcheck + return CreateIterable( func(previousResponse *SearchSynonymsResponse, previousErr error) (*SearchSynonymsResponse, error) { searchSynonymsParams.HitsPerPage = &hitsPerPage @@ -9360,7 +9666,7 @@ func (c *APIClient) BrowseSynonyms( return c.SearchSynonyms( c.NewApiSearchSynonymsRequest(indexName).WithSearchSynonymsParams(&searchSynonymsParams), - utils.ToRequestOptions(opts)..., + toRequestOptions(opts)..., ) }, func(response *SearchSynonymsResponse, responseErr error) bool { @@ -9465,12 +9771,12 @@ func (c *APIClient) GetSecuredApiKeyRemainingValidity(securedApiKey string) (tim } // Helper: Saves the given array of objects in the given index. The `chunkedBatch` helper is used under the hood, which creates a `batch` requests with at most 1000 objects in it. -func (c *APIClient) SaveObjects(indexName string, objects []map[string]any, opts ...utils.ChunkedBatchOption) ([]BatchResponse, error) { +func (c *APIClient) SaveObjects(indexName string, objects []map[string]any, opts ...ChunkedBatchOption) ([]BatchResponse, error) { return c.ChunkedBatch(indexName, objects, ACTION_ADD_OBJECT, opts...) } // Helper: Deletes every records for the given objectIDs. The `chunkedBatch` helper is used under the hood, which creates a `batch` requests with at most 1000 objectIDs in it. -func (c *APIClient) DeleteObjects(indexName string, objectIDs []string, opts ...utils.ChunkedBatchOption) ([]BatchResponse, error) { +func (c *APIClient) DeleteObjects(indexName string, objectIDs []string, opts ...ChunkedBatchOption) ([]BatchResponse, error) { objects := make([]map[string]any, 0, len(objectIDs)) for _, id := range objectIDs { @@ -9481,49 +9787,57 @@ func (c *APIClient) DeleteObjects(indexName string, objectIDs []string, opts ... } // Helper: Replaces object content of all the given objects according to their respective `objectID` field. The `chunkedBatch` helper is used under the hood, which creates a `batch` requests with at most 1000 objects in it. -func (c *APIClient) PartialUpdateObjects(indexName string, objects []map[string]any, createIfNotExists bool, opts ...utils.ChunkedBatchOption) ([]BatchResponse, error) { +func (c *APIClient) PartialUpdateObjects(indexName string, objects []map[string]any, opts ...PartialUpdateObjectsOption) ([]BatchResponse, error) { + conf := config{ + createIfNotExists: true, + } + + for _, opt := range opts { + opt.apply(&conf) + } + var action Action - if createIfNotExists { + if conf.createIfNotExists { action = ACTION_PARTIAL_UPDATE_OBJECT } else { action = ACTION_PARTIAL_UPDATE_OBJECT_NO_CREATE } - return c.ChunkedBatch(indexName, objects, action, opts...) + return c.ChunkedBatch(indexName, objects, action, toChunkedBatchOptions(opts)...) } // ChunkedBatch chunks the given `objects` list in subset of 1000 elements max in order to make it fit in `batch` requests. -func (c *APIClient) ChunkedBatch(indexName string, objects []map[string]any, action Action, opts ...utils.ChunkedBatchOption) ([]BatchResponse, error) { - options := utils.Options{ - WaitForTasks: false, - BatchSize: 1000, +func (c *APIClient) ChunkedBatch(indexName string, objects []map[string]any, action Action, opts ...ChunkedBatchOption) ([]BatchResponse, error) { + conf := config{ + waitForTasks: false, + batchSize: 1000, } for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } - requests := make([]BatchRequest, 0, len(objects)%options.BatchSize) - responses := make([]BatchResponse, 0, len(objects)%options.BatchSize) + requests := make([]BatchRequest, 0, len(objects)%conf.batchSize) + responses := make([]BatchResponse, 0, len(objects)%conf.batchSize) for i, obj := range objects { requests = append(requests, *NewBatchRequest(action, obj)) - if len(requests) == options.BatchSize || i == len(objects)-1 { - resp, err := c.Batch(c.NewApiBatchRequest(indexName, NewBatchWriteParams(requests)), utils.ToRequestOptions(opts)...) + if len(requests) == conf.batchSize || i == len(objects)-1 { + resp, err := c.Batch(c.NewApiBatchRequest(indexName, NewBatchWriteParams(requests)), toRequestOptions(opts)...) if err != nil { return nil, err } responses = append(responses, *resp) - requests = make([]BatchRequest, 0, len(objects)%options.BatchSize) + requests = make([]BatchRequest, 0, len(objects)%conf.batchSize) } } - if options.WaitForTasks { + if conf.waitForTasks { for _, resp := range responses { - _, err := c.WaitForTask(indexName, resp.TaskID, utils.ToIterableOptions(opts)...) + _, err := c.WaitForTask(indexName, resp.TaskID, toIterableOptions(opts)...) if err != nil { return nil, err } @@ -9535,42 +9849,42 @@ func (c *APIClient) ChunkedBatch(indexName string, objects []map[string]any, act // ReplaceAllObjects replaces all objects (records) in the given `indexName` with the given `objects`. A temporary index is created during this process in order to backup your data. // See https://api-clients-automation.netlify.app/docs/contributing/add-new-api-client#5-helpers for implementation details. -func (c *APIClient) ReplaceAllObjects(indexName string, objects []map[string]any, opts ...utils.ChunkedBatchOption) (*ReplaceAllObjectsResponse, error) { +func (c *APIClient) ReplaceAllObjects(indexName string, objects []map[string]any, opts ...ChunkedBatchOption) (*ReplaceAllObjectsResponse, error) { tmpIndexName := fmt.Sprintf("%s_tmp_%d", indexName, time.Now().UnixNano()) - copyResp, err := c.OperationIndex(c.NewApiOperationIndexRequest(indexName, NewOperationIndexParams(OPERATION_TYPE_COPY, tmpIndexName, WithOperationIndexParamsScope([]ScopeType{SCOPE_TYPE_SETTINGS, SCOPE_TYPE_RULES, SCOPE_TYPE_SYNONYMS}))), utils.ToRequestOptions(opts)...) + copyResp, err := c.OperationIndex(c.NewApiOperationIndexRequest(indexName, NewOperationIndexParams(OPERATION_TYPE_COPY, tmpIndexName, WithOperationIndexParamsScope([]ScopeType{SCOPE_TYPE_SETTINGS, SCOPE_TYPE_RULES, SCOPE_TYPE_SYNONYMS}))), toRequestOptions(opts)...) if err != nil { return nil, err } - opts = append(opts, utils.WithWaitForTasks(true)) + opts = append(opts, WithWaitForTasks(true)) batchResp, err := c.ChunkedBatch(tmpIndexName, objects, ACTION_ADD_OBJECT, opts...) if err != nil { return nil, err } - _, err = c.WaitForTask(tmpIndexName, copyResp.TaskID, utils.ToIterableOptions(opts)...) + _, err = c.WaitForTask(tmpIndexName, copyResp.TaskID, toIterableOptions(opts)...) if err != nil { return nil, err } - copyResp, err = c.OperationIndex(c.NewApiOperationIndexRequest(indexName, NewOperationIndexParams(OPERATION_TYPE_COPY, tmpIndexName, WithOperationIndexParamsScope([]ScopeType{SCOPE_TYPE_SETTINGS, SCOPE_TYPE_RULES, SCOPE_TYPE_SYNONYMS}))), utils.ToRequestOptions(opts)...) + copyResp, err = c.OperationIndex(c.NewApiOperationIndexRequest(indexName, NewOperationIndexParams(OPERATION_TYPE_COPY, tmpIndexName, WithOperationIndexParamsScope([]ScopeType{SCOPE_TYPE_SETTINGS, SCOPE_TYPE_RULES, SCOPE_TYPE_SYNONYMS}))), toRequestOptions(opts)...) if err != nil { return nil, err } - _, err = c.WaitForTask(tmpIndexName, copyResp.TaskID, utils.ToIterableOptions(opts)...) + _, err = c.WaitForTask(tmpIndexName, copyResp.TaskID, toIterableOptions(opts)...) if err != nil { return nil, err } - moveResp, err := c.OperationIndex(c.NewApiOperationIndexRequest(tmpIndexName, NewOperationIndexParams(OPERATION_TYPE_MOVE, indexName)), utils.ToRequestOptions(opts)...) + moveResp, err := c.OperationIndex(c.NewApiOperationIndexRequest(tmpIndexName, NewOperationIndexParams(OPERATION_TYPE_MOVE, indexName)), toRequestOptions(opts)...) if err != nil { return nil, err } - _, err = c.WaitForTask(tmpIndexName, moveResp.TaskID, utils.ToIterableOptions(opts)...) + _, err = c.WaitForTask(tmpIndexName, moveResp.TaskID, toIterableOptions(opts)...) if err != nil { return nil, err } diff --git a/clients/algoliasearch-client-go/algolia/usage/api_usage.go b/clients/algoliasearch-client-go/algolia/usage/api_usage.go index 7ca5e51966..60a26b163c 100644 --- a/clients/algoliasearch-client-go/algolia/usage/api_usage.go +++ b/clients/algoliasearch-client-go/algolia/usage/api_usage.go @@ -12,6 +12,41 @@ import ( "github.com/algolia/algoliasearch-client-go/v4/algolia/utils" ) +type config struct { + // -- Request options for API calls + context context.Context + queryParams url.Values + headerParams map[string]string +} + +type RequestOption interface { + apply(*config) +} + +type requestOption func(*config) + +func (r requestOption) apply(c *config) { + r(c) +} + +func WithContext(ctx context.Context) requestOption { + return requestOption(func(c *config) { + c.context = ctx + }) +} + +func WithHeaderParam(key string, value any) requestOption { + return requestOption(func(c *config) { + c.headerParams[key] = utils.ParameterToString(value) + }) +} + +func WithQueryParam(key string, value any) requestOption { + return requestOption(func(c *config) { + c.queryParams.Set(utils.QueryParameterToString(key), utils.QueryParameterToString(value)) + }) +} + func (r *ApiCustomDeleteRequest) UnmarshalJSON(b []byte) error { req := map[string]json.RawMessage{} err := json.Unmarshal(b, &req) @@ -68,12 +103,12 @@ CustomDelete calls the API and returns the raw response from it. Request can be constructed by NewApiCustomDeleteRequest with parameters below. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomDeleteWithHTTPInfo(r ApiCustomDeleteRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomDeleteWithHTTPInfo(r ApiCustomDeleteRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -81,26 +116,26 @@ func (c *APIClient) CustomDeleteWithHTTPInfo(r ApiCustomDeleteRequest, opts ...u return nil, nil, reportError("Parameter `path` is required when calling `CustomDelete`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodDelete, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodDelete, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -119,7 +154,7 @@ Request can be constructed by NewApiCustomDeleteRequest with parameters below. @param parameters map[string]any - Query parameters to apply to the current query. @return map[string]any */ -func (c *APIClient) CustomDelete(r ApiCustomDeleteRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomDelete(r ApiCustomDeleteRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomDeleteWithHTTPInfo(r, opts...) @@ -210,12 +245,12 @@ CustomGet calls the API and returns the raw response from it. Request can be constructed by NewApiCustomGetRequest with parameters below. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomGetWithHTTPInfo(r ApiCustomGetRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomGetWithHTTPInfo(r ApiCustomGetRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -223,26 +258,26 @@ func (c *APIClient) CustomGetWithHTTPInfo(r ApiCustomGetRequest, opts ...utils.R return nil, nil, reportError("Parameter `path` is required when calling `CustomGet`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -261,7 +296,7 @@ Request can be constructed by NewApiCustomGetRequest with parameters below. @param parameters map[string]any - Query parameters to apply to the current query. @return map[string]any */ -func (c *APIClient) CustomGet(r ApiCustomGetRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomGet(r ApiCustomGetRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomGetWithHTTPInfo(r, opts...) @@ -369,12 +404,12 @@ CustomPost calls the API and returns the raw response from it. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. @param body map[string]any - Parameters to send with the custom request. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -382,21 +417,21 @@ func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...utils return nil, nil, reportError("Parameter `path` is required when calling `CustomPost`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any @@ -407,7 +442,7 @@ func (c *APIClient) CustomPostWithHTTPInfo(r ApiCustomPostRequest, opts ...utils } else { postBody = r.body } - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPost, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPost, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -427,7 +462,7 @@ Request can be constructed by NewApiCustomPostRequest with parameters below. @param body map[string]any - Parameters to send with the custom request. @return map[string]any */ -func (c *APIClient) CustomPost(r ApiCustomPostRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomPost(r ApiCustomPostRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomPostWithHTTPInfo(r, opts...) @@ -535,12 +570,12 @@ CustomPut calls the API and returns the raw response from it. @param path string - Path of the endpoint, anything after \"/1\" must be specified. @param parameters map[string]any - Query parameters to apply to the current query. @param body map[string]any - Parameters to send with the custom request. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/{path}" requestPath = strings.ReplaceAll(requestPath, "{path}", utils.ParameterToString(r.path)) @@ -548,21 +583,21 @@ func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...utils.R return nil, nil, reportError("Parameter `path` is required when calling `CustomPut`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } if !utils.IsNilOrEmpty(r.parameters) { for k, v := range r.parameters { - options.QueryParams.Set(k, utils.QueryParameterToString(v)) + conf.queryParams.Set(k, utils.QueryParameterToString(v)) } } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any @@ -573,7 +608,7 @@ func (c *APIClient) CustomPutWithHTTPInfo(r ApiCustomPutRequest, opts ...utils.R } else { postBody = r.body } - req, err := c.prepareRequest(options.Context, requestPath, http.MethodPut, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodPut, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -593,7 +628,7 @@ Request can be constructed by NewApiCustomPutRequest with parameters below. @param body map[string]any - Parameters to send with the custom request. @return map[string]any */ -func (c *APIClient) CustomPut(r ApiCustomPutRequest, opts ...utils.RequestOption) (*map[string]any, error) { +func (c *APIClient) CustomPut(r ApiCustomPutRequest, opts ...RequestOption) (*map[string]any, error) { var returnValue *map[string]any res, resBody, err := c.CustomPutWithHTTPInfo(r, opts...) @@ -721,12 +756,12 @@ GetIndexUsage calls the API and returns the raw response from it. @param startDate string - Start date of the period to analyze, in `YYYY-MM-DD` format. @param endDate string - End date of the period to analyze, in `YYYY-MM-DD` format. @param granularity Granularity - Granularity of the aggregated metrics. - `hourly`: the maximum time range for hourly metrics is 7 days. - `daily`: the maximum time range for daily metrics is 365 days. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetIndexUsageWithHTTPInfo(r ApiGetIndexUsageRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetIndexUsageWithHTTPInfo(r ApiGetIndexUsageRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/usage/{statistic}/{indexName}" requestPath = strings.ReplaceAll(requestPath, "{statistic}", url.PathEscape(utils.ParameterToString(r.statistic))) requestPath = strings.ReplaceAll(requestPath, "{indexName}", url.PathEscape(utils.ParameterToString(r.indexName))) @@ -741,26 +776,26 @@ func (c *APIClient) GetIndexUsageWithHTTPInfo(r ApiGetIndexUsageRequest, opts .. return nil, nil, reportError("Parameter `endDate` is required when calling `GetIndexUsage`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } - options.QueryParams.Set("startDate", utils.QueryParameterToString(r.startDate)) - options.QueryParams.Set("endDate", utils.QueryParameterToString(r.endDate)) + conf.queryParams.Set("startDate", utils.QueryParameterToString(r.startDate)) + conf.queryParams.Set("endDate", utils.QueryParameterToString(r.endDate)) if !utils.IsNilOrEmpty(r.granularity) { - options.QueryParams.Set("granularity", utils.QueryParameterToString(r.granularity)) + conf.queryParams.Set("granularity", utils.QueryParameterToString(r.granularity)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -782,7 +817,7 @@ Request can be constructed by NewApiGetIndexUsageRequest with parameters below. @param granularity Granularity - Granularity of the aggregated metrics. - `hourly`: the maximum time range for hourly metrics is 7 days. - `daily`: the maximum time range for daily metrics is 365 days. @return GetUsage200Response */ -func (c *APIClient) GetIndexUsage(r ApiGetIndexUsageRequest, opts ...utils.RequestOption) (*GetUsage200Response, error) { +func (c *APIClient) GetIndexUsage(r ApiGetIndexUsageRequest, opts ...RequestOption) (*GetUsage200Response, error) { var returnValue *GetUsage200Response res, resBody, err := c.GetIndexUsageWithHTTPInfo(r, opts...) @@ -898,12 +933,12 @@ GetUsage calls the API and returns the raw response from it. @param startDate string - Start date of the period to analyze, in `YYYY-MM-DD` format. @param endDate string - End date of the period to analyze, in `YYYY-MM-DD` format. @param granularity Granularity - Granularity of the aggregated metrics. - `hourly`: the maximum time range for hourly metrics is 7 days. - `daily`: the maximum time range for daily metrics is 365 days. - @param opts ...Option - Optional parameters for the API call + @param opts ...RequestOption - Optional parameters for the API call @return *http.Response - The raw response from the API @return []byte - The raw response body from the API @return error - An error if the API call fails */ -func (c *APIClient) GetUsageWithHTTPInfo(r ApiGetUsageRequest, opts ...utils.RequestOption) (*http.Response, []byte, error) { +func (c *APIClient) GetUsageWithHTTPInfo(r ApiGetUsageRequest, opts ...RequestOption) (*http.Response, []byte, error) { requestPath := "/1/usage/{statistic}" requestPath = strings.ReplaceAll(requestPath, "{statistic}", url.PathEscape(utils.ParameterToString(r.statistic))) @@ -914,26 +949,26 @@ func (c *APIClient) GetUsageWithHTTPInfo(r ApiGetUsageRequest, opts ...utils.Req return nil, nil, reportError("Parameter `endDate` is required when calling `GetUsage`.") } - options := utils.Options{ - Context: context.Background(), - QueryParams: url.Values{}, - HeaderParams: map[string]string{}, + conf := config{ + context: context.Background(), + queryParams: url.Values{}, + headerParams: map[string]string{}, } - options.QueryParams.Set("startDate", utils.QueryParameterToString(r.startDate)) - options.QueryParams.Set("endDate", utils.QueryParameterToString(r.endDate)) + conf.queryParams.Set("startDate", utils.QueryParameterToString(r.startDate)) + conf.queryParams.Set("endDate", utils.QueryParameterToString(r.endDate)) if !utils.IsNilOrEmpty(r.granularity) { - options.QueryParams.Set("granularity", utils.QueryParameterToString(r.granularity)) + conf.queryParams.Set("granularity", utils.QueryParameterToString(r.granularity)) } // optional params if any for _, opt := range opts { - opt.Apply(&options) + opt.apply(&conf) } var postBody any - req, err := c.prepareRequest(options.Context, requestPath, http.MethodGet, postBody, options.HeaderParams, options.QueryParams) + req, err := c.prepareRequest(conf.context, requestPath, http.MethodGet, postBody, conf.headerParams, conf.queryParams) if err != nil { return nil, nil, err } @@ -954,7 +989,7 @@ Request can be constructed by NewApiGetUsageRequest with parameters below. @param granularity Granularity - Granularity of the aggregated metrics. - `hourly`: the maximum time range for hourly metrics is 7 days. - `daily`: the maximum time range for daily metrics is 365 days. @return GetUsage200Response */ -func (c *APIClient) GetUsage(r ApiGetUsageRequest, opts ...utils.RequestOption) (*GetUsage200Response, error) { +func (c *APIClient) GetUsage(r ApiGetUsageRequest, opts ...RequestOption) (*GetUsage200Response, error) { var returnValue *GetUsage200Response res, resBody, err := c.GetUsageWithHTTPInfo(r, opts...) diff --git a/tests/output/go/tests/client/search_test.go b/tests/output/go/tests/client/search_test.go index bd6bfb3024..51af4b51ef 100644 --- a/tests/output/go/tests/client/search_test.go +++ b/tests/output/go/tests/client/search_test.go @@ -14,7 +14,6 @@ import ( "github.com/algolia/algoliasearch-client-go/v4/algolia/compression" "github.com/algolia/algoliasearch-client-go/v4/algolia/search" "github.com/algolia/algoliasearch-client-go/v4/algolia/transport" - "github.com/algolia/algoliasearch-client-go/v4/algolia/utils" ) func createSearchClient(t *testing.T) (*search.APIClient, *tests.EchoRequester) { @@ -221,7 +220,7 @@ func TestSearchhelpers2(t *testing.T) { res, err := client.ReplaceAllObjects( "cts_e2e_replace_all_objects_Go", []map[string]any{map[string]any{"objectID": "1", "name": "Adam"}, map[string]any{"objectID": "2", "name": "Benoit"}, map[string]any{"objectID": "3", "name": "Cyril"}, map[string]any{"objectID": "4", "name": "David"}, map[string]any{"objectID": "5", "name": "Eva"}, map[string]any{"objectID": "6", "name": "Fiona"}, map[string]any{"objectID": "7", "name": "Gael"}, map[string]any{"objectID": "8", "name": "Hugo"}, map[string]any{"objectID": "9", "name": "Igor"}, map[string]any{"objectID": "10", "name": "Julia"}}, - utils.WithBatchSize(3)) + search.WithBatchSize(3)) require.NoError(t, err) rawBody, err := json.Marshal(res) require.NoError(t, err) @@ -275,7 +274,7 @@ func TestSearchhelpers4(t *testing.T) { res, err := client.PartialUpdateObjects( "cts_e2e_partialUpdateObjects_Go", []map[string]any{map[string]any{"objectID": "1", "name": "Adam"}, map[string]any{"objectID": "2", "name": "Benoit"}}, - true) + search.WithCreateIfNotExists(true)) require.NoError(t, err) rawBody, err := json.Marshal(res) require.NoError(t, err) @@ -302,7 +301,7 @@ func TestSearchhelpers5(t *testing.T) { res, err := client.PartialUpdateObjects( "cts_e2e_partialUpdateObjects_Go", []map[string]any{map[string]any{"objectID": "3", "name": "Cyril"}, map[string]any{"objectID": "4", "name": "David"}}, - false) + search.WithCreateIfNotExists(false)) require.NoError(t, err) rawBody, err := json.Marshal(res) require.NoError(t, err) diff --git a/tests/output/go/tests/requests/abtesting_test.go b/tests/output/go/tests/requests/abtesting_test.go index 91eb87ee74..95bc978b67 100644 --- a/tests/output/go/tests/requests/abtesting_test.go +++ b/tests/output/go/tests/requests/abtesting_test.go @@ -12,7 +12,6 @@ import ( "github.com/algolia/algoliasearch-client-go/v4/algolia/abtesting" "github.com/algolia/algoliasearch-client-go/v4/algolia/transport" - "github.com/algolia/algoliasearch-client-go/v4/algolia/utils" ) func createAbtestingClient(t *testing.T) (*abtesting.APIClient, *tests.EchoRequester) { @@ -125,8 +124,8 @@ func TestAbtesting_CustomGet(t *testing.T) { _, err := client.CustomGet(client.NewApiCustomGetRequest( "test/all", ).WithParameters(map[string]any{"query": "to be overriden"}), - utils.WithQueryParam("query", "parameters with space"), utils.WithQueryParam("and an array", - []string{"array", "with spaces"}), utils.WithHeaderParam("x-header-1", "spaces are left alone"), + abtesting.WithQueryParam("query", "parameters with space"), abtesting.WithQueryParam("and an array", + []string{"array", "with spaces"}), abtesting.WithHeaderParam("x-header-1", "spaces are left alone"), ) require.NoError(t, err) @@ -186,7 +185,7 @@ func TestAbtesting_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("query", "myQueryParameter"), + abtesting.WithQueryParam("query", "myQueryParameter"), ) require.NoError(t, err) @@ -206,7 +205,7 @@ func TestAbtesting_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("query2", "myQueryParameter"), + abtesting.WithQueryParam("query2", "myQueryParameter"), ) require.NoError(t, err) @@ -226,7 +225,7 @@ func TestAbtesting_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithHeaderParam("x-algolia-api-key", "myApiKey"), + abtesting.WithHeaderParam("x-algolia-api-key", "myApiKey"), ) require.NoError(t, err) @@ -251,7 +250,7 @@ func TestAbtesting_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithHeaderParam("x-algolia-api-key", "myApiKey"), + abtesting.WithHeaderParam("x-algolia-api-key", "myApiKey"), ) require.NoError(t, err) @@ -276,7 +275,7 @@ func TestAbtesting_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("isItWorking", true), + abtesting.WithQueryParam("isItWorking", true), ) require.NoError(t, err) @@ -296,7 +295,7 @@ func TestAbtesting_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", 2), + abtesting.WithQueryParam("myParam", 2), ) require.NoError(t, err) @@ -316,7 +315,7 @@ func TestAbtesting_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", + abtesting.WithQueryParam("myParam", []string{"b and c", "d"}), ) require.NoError(t, err) @@ -337,7 +336,7 @@ func TestAbtesting_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", + abtesting.WithQueryParam("myParam", []bool{true, true, false}), ) require.NoError(t, err) @@ -358,7 +357,7 @@ func TestAbtesting_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", + abtesting.WithQueryParam("myParam", []int32{1, 2}), ) require.NoError(t, err) diff --git a/tests/output/go/tests/requests/analytics_test.go b/tests/output/go/tests/requests/analytics_test.go index d1aab56872..cc87f723c5 100644 --- a/tests/output/go/tests/requests/analytics_test.go +++ b/tests/output/go/tests/requests/analytics_test.go @@ -12,7 +12,6 @@ import ( "github.com/algolia/algoliasearch-client-go/v4/algolia/analytics" "github.com/algolia/algoliasearch-client-go/v4/algolia/transport" - "github.com/algolia/algoliasearch-client-go/v4/algolia/utils" ) func createAnalyticsClient(t *testing.T) (*analytics.APIClient, *tests.EchoRequester) { @@ -103,8 +102,8 @@ func TestAnalytics_CustomGet(t *testing.T) { _, err := client.CustomGet(client.NewApiCustomGetRequest( "test/all", ).WithParameters(map[string]any{"query": "to be overriden"}), - utils.WithQueryParam("query", "parameters with space"), utils.WithQueryParam("and an array", - []string{"array", "with spaces"}), utils.WithHeaderParam("x-header-1", "spaces are left alone"), + analytics.WithQueryParam("query", "parameters with space"), analytics.WithQueryParam("and an array", + []string{"array", "with spaces"}), analytics.WithHeaderParam("x-header-1", "spaces are left alone"), ) require.NoError(t, err) @@ -164,7 +163,7 @@ func TestAnalytics_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("query", "myQueryParameter"), + analytics.WithQueryParam("query", "myQueryParameter"), ) require.NoError(t, err) @@ -184,7 +183,7 @@ func TestAnalytics_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("query2", "myQueryParameter"), + analytics.WithQueryParam("query2", "myQueryParameter"), ) require.NoError(t, err) @@ -204,7 +203,7 @@ func TestAnalytics_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithHeaderParam("x-algolia-api-key", "myApiKey"), + analytics.WithHeaderParam("x-algolia-api-key", "myApiKey"), ) require.NoError(t, err) @@ -229,7 +228,7 @@ func TestAnalytics_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithHeaderParam("x-algolia-api-key", "myApiKey"), + analytics.WithHeaderParam("x-algolia-api-key", "myApiKey"), ) require.NoError(t, err) @@ -254,7 +253,7 @@ func TestAnalytics_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("isItWorking", true), + analytics.WithQueryParam("isItWorking", true), ) require.NoError(t, err) @@ -274,7 +273,7 @@ func TestAnalytics_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", 2), + analytics.WithQueryParam("myParam", 2), ) require.NoError(t, err) @@ -294,7 +293,7 @@ func TestAnalytics_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", + analytics.WithQueryParam("myParam", []string{"b and c", "d"}), ) require.NoError(t, err) @@ -315,7 +314,7 @@ func TestAnalytics_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", + analytics.WithQueryParam("myParam", []bool{true, true, false}), ) require.NoError(t, err) @@ -336,7 +335,7 @@ func TestAnalytics_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", + analytics.WithQueryParam("myParam", []int32{1, 2}), ) require.NoError(t, err) diff --git a/tests/output/go/tests/requests/ingestion_test.go b/tests/output/go/tests/requests/ingestion_test.go index f78c1fff42..123c7cebd6 100644 --- a/tests/output/go/tests/requests/ingestion_test.go +++ b/tests/output/go/tests/requests/ingestion_test.go @@ -12,7 +12,6 @@ import ( "github.com/algolia/algoliasearch-client-go/v4/algolia/ingestion" "github.com/algolia/algoliasearch-client-go/v4/algolia/transport" - "github.com/algolia/algoliasearch-client-go/v4/algolia/utils" ) func createIngestionClient(t *testing.T) (*ingestion.APIClient, *tests.EchoRequester) { @@ -246,8 +245,8 @@ func TestIngestion_CustomGet(t *testing.T) { _, err := client.CustomGet(client.NewApiCustomGetRequest( "test/all", ).WithParameters(map[string]any{"query": "to be overriden"}), - utils.WithQueryParam("query", "parameters with space"), utils.WithQueryParam("and an array", - []string{"array", "with spaces"}), utils.WithHeaderParam("x-header-1", "spaces are left alone"), + ingestion.WithQueryParam("query", "parameters with space"), ingestion.WithQueryParam("and an array", + []string{"array", "with spaces"}), ingestion.WithHeaderParam("x-header-1", "spaces are left alone"), ) require.NoError(t, err) @@ -307,7 +306,7 @@ func TestIngestion_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("query", "myQueryParameter"), + ingestion.WithQueryParam("query", "myQueryParameter"), ) require.NoError(t, err) @@ -327,7 +326,7 @@ func TestIngestion_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("query2", "myQueryParameter"), + ingestion.WithQueryParam("query2", "myQueryParameter"), ) require.NoError(t, err) @@ -347,7 +346,7 @@ func TestIngestion_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithHeaderParam("x-algolia-api-key", "myApiKey"), + ingestion.WithHeaderParam("x-algolia-api-key", "myApiKey"), ) require.NoError(t, err) @@ -372,7 +371,7 @@ func TestIngestion_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithHeaderParam("x-algolia-api-key", "myApiKey"), + ingestion.WithHeaderParam("x-algolia-api-key", "myApiKey"), ) require.NoError(t, err) @@ -397,7 +396,7 @@ func TestIngestion_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("isItWorking", true), + ingestion.WithQueryParam("isItWorking", true), ) require.NoError(t, err) @@ -417,7 +416,7 @@ func TestIngestion_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", 2), + ingestion.WithQueryParam("myParam", 2), ) require.NoError(t, err) @@ -437,7 +436,7 @@ func TestIngestion_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", + ingestion.WithQueryParam("myParam", []string{"b and c", "d"}), ) require.NoError(t, err) @@ -458,7 +457,7 @@ func TestIngestion_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", + ingestion.WithQueryParam("myParam", []bool{true, true, false}), ) require.NoError(t, err) @@ -479,7 +478,7 @@ func TestIngestion_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", + ingestion.WithQueryParam("myParam", []int32{1, 2}), ) require.NoError(t, err) diff --git a/tests/output/go/tests/requests/insights_test.go b/tests/output/go/tests/requests/insights_test.go index a8e4f65728..1fffd40542 100644 --- a/tests/output/go/tests/requests/insights_test.go +++ b/tests/output/go/tests/requests/insights_test.go @@ -12,7 +12,6 @@ import ( "github.com/algolia/algoliasearch-client-go/v4/algolia/insights" "github.com/algolia/algoliasearch-client-go/v4/algolia/transport" - "github.com/algolia/algoliasearch-client-go/v4/algolia/utils" ) func createInsightsClient(t *testing.T) (*insights.APIClient, *tests.EchoRequester) { @@ -103,8 +102,8 @@ func TestInsights_CustomGet(t *testing.T) { _, err := client.CustomGet(client.NewApiCustomGetRequest( "test/all", ).WithParameters(map[string]any{"query": "to be overriden"}), - utils.WithQueryParam("query", "parameters with space"), utils.WithQueryParam("and an array", - []string{"array", "with spaces"}), utils.WithHeaderParam("x-header-1", "spaces are left alone"), + insights.WithQueryParam("query", "parameters with space"), insights.WithQueryParam("and an array", + []string{"array", "with spaces"}), insights.WithHeaderParam("x-header-1", "spaces are left alone"), ) require.NoError(t, err) @@ -164,7 +163,7 @@ func TestInsights_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("query", "myQueryParameter"), + insights.WithQueryParam("query", "myQueryParameter"), ) require.NoError(t, err) @@ -184,7 +183,7 @@ func TestInsights_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("query2", "myQueryParameter"), + insights.WithQueryParam("query2", "myQueryParameter"), ) require.NoError(t, err) @@ -204,7 +203,7 @@ func TestInsights_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithHeaderParam("x-algolia-api-key", "myApiKey"), + insights.WithHeaderParam("x-algolia-api-key", "myApiKey"), ) require.NoError(t, err) @@ -229,7 +228,7 @@ func TestInsights_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithHeaderParam("x-algolia-api-key", "myApiKey"), + insights.WithHeaderParam("x-algolia-api-key", "myApiKey"), ) require.NoError(t, err) @@ -254,7 +253,7 @@ func TestInsights_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("isItWorking", true), + insights.WithQueryParam("isItWorking", true), ) require.NoError(t, err) @@ -274,7 +273,7 @@ func TestInsights_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", 2), + insights.WithQueryParam("myParam", 2), ) require.NoError(t, err) @@ -294,7 +293,7 @@ func TestInsights_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", + insights.WithQueryParam("myParam", []string{"b and c", "d"}), ) require.NoError(t, err) @@ -315,7 +314,7 @@ func TestInsights_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", + insights.WithQueryParam("myParam", []bool{true, true, false}), ) require.NoError(t, err) @@ -336,7 +335,7 @@ func TestInsights_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", + insights.WithQueryParam("myParam", []int32{1, 2}), ) require.NoError(t, err) diff --git a/tests/output/go/tests/requests/monitoring_test.go b/tests/output/go/tests/requests/monitoring_test.go index 1c6baf4973..2c704e0be4 100644 --- a/tests/output/go/tests/requests/monitoring_test.go +++ b/tests/output/go/tests/requests/monitoring_test.go @@ -12,7 +12,6 @@ import ( "github.com/algolia/algoliasearch-client-go/v4/algolia/monitoring" "github.com/algolia/algoliasearch-client-go/v4/algolia/transport" - "github.com/algolia/algoliasearch-client-go/v4/algolia/utils" ) func createMonitoringClient(t *testing.T) (*monitoring.APIClient, *tests.EchoRequester) { @@ -102,8 +101,8 @@ func TestMonitoring_CustomGet(t *testing.T) { _, err := client.CustomGet(client.NewApiCustomGetRequest( "test/all", ).WithParameters(map[string]any{"query": "to be overriden"}), - utils.WithQueryParam("query", "parameters with space"), utils.WithQueryParam("and an array", - []string{"array", "with spaces"}), utils.WithHeaderParam("x-header-1", "spaces are left alone"), + monitoring.WithQueryParam("query", "parameters with space"), monitoring.WithQueryParam("and an array", + []string{"array", "with spaces"}), monitoring.WithHeaderParam("x-header-1", "spaces are left alone"), ) require.NoError(t, err) @@ -163,7 +162,7 @@ func TestMonitoring_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("query", "myQueryParameter"), + monitoring.WithQueryParam("query", "myQueryParameter"), ) require.NoError(t, err) @@ -183,7 +182,7 @@ func TestMonitoring_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("query2", "myQueryParameter"), + monitoring.WithQueryParam("query2", "myQueryParameter"), ) require.NoError(t, err) @@ -203,7 +202,7 @@ func TestMonitoring_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithHeaderParam("x-algolia-api-key", "myApiKey"), + monitoring.WithHeaderParam("x-algolia-api-key", "myApiKey"), ) require.NoError(t, err) @@ -228,7 +227,7 @@ func TestMonitoring_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithHeaderParam("x-algolia-api-key", "myApiKey"), + monitoring.WithHeaderParam("x-algolia-api-key", "myApiKey"), ) require.NoError(t, err) @@ -253,7 +252,7 @@ func TestMonitoring_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("isItWorking", true), + monitoring.WithQueryParam("isItWorking", true), ) require.NoError(t, err) @@ -273,7 +272,7 @@ func TestMonitoring_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", 2), + monitoring.WithQueryParam("myParam", 2), ) require.NoError(t, err) @@ -293,7 +292,7 @@ func TestMonitoring_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", + monitoring.WithQueryParam("myParam", []string{"b and c", "d"}), ) require.NoError(t, err) @@ -314,7 +313,7 @@ func TestMonitoring_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", + monitoring.WithQueryParam("myParam", []bool{true, true, false}), ) require.NoError(t, err) @@ -335,7 +334,7 @@ func TestMonitoring_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", + monitoring.WithQueryParam("myParam", []int32{1, 2}), ) require.NoError(t, err) diff --git a/tests/output/go/tests/requests/personalization_test.go b/tests/output/go/tests/requests/personalization_test.go index f8ae276c25..7525696b74 100644 --- a/tests/output/go/tests/requests/personalization_test.go +++ b/tests/output/go/tests/requests/personalization_test.go @@ -12,7 +12,6 @@ import ( "github.com/algolia/algoliasearch-client-go/v4/algolia/personalization" "github.com/algolia/algoliasearch-client-go/v4/algolia/transport" - "github.com/algolia/algoliasearch-client-go/v4/algolia/utils" ) func createPersonalizationClient(t *testing.T) (*personalization.APIClient, *tests.EchoRequester) { @@ -103,8 +102,8 @@ func TestPersonalization_CustomGet(t *testing.T) { _, err := client.CustomGet(client.NewApiCustomGetRequest( "test/all", ).WithParameters(map[string]any{"query": "to be overriden"}), - utils.WithQueryParam("query", "parameters with space"), utils.WithQueryParam("and an array", - []string{"array", "with spaces"}), utils.WithHeaderParam("x-header-1", "spaces are left alone"), + personalization.WithQueryParam("query", "parameters with space"), personalization.WithQueryParam("and an array", + []string{"array", "with spaces"}), personalization.WithHeaderParam("x-header-1", "spaces are left alone"), ) require.NoError(t, err) @@ -164,7 +163,7 @@ func TestPersonalization_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("query", "myQueryParameter"), + personalization.WithQueryParam("query", "myQueryParameter"), ) require.NoError(t, err) @@ -184,7 +183,7 @@ func TestPersonalization_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("query2", "myQueryParameter"), + personalization.WithQueryParam("query2", "myQueryParameter"), ) require.NoError(t, err) @@ -204,7 +203,7 @@ func TestPersonalization_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithHeaderParam("x-algolia-api-key", "myApiKey"), + personalization.WithHeaderParam("x-algolia-api-key", "myApiKey"), ) require.NoError(t, err) @@ -229,7 +228,7 @@ func TestPersonalization_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithHeaderParam("x-algolia-api-key", "myApiKey"), + personalization.WithHeaderParam("x-algolia-api-key", "myApiKey"), ) require.NoError(t, err) @@ -254,7 +253,7 @@ func TestPersonalization_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("isItWorking", true), + personalization.WithQueryParam("isItWorking", true), ) require.NoError(t, err) @@ -274,7 +273,7 @@ func TestPersonalization_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", 2), + personalization.WithQueryParam("myParam", 2), ) require.NoError(t, err) @@ -294,7 +293,7 @@ func TestPersonalization_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", + personalization.WithQueryParam("myParam", []string{"b and c", "d"}), ) require.NoError(t, err) @@ -315,7 +314,7 @@ func TestPersonalization_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", + personalization.WithQueryParam("myParam", []bool{true, true, false}), ) require.NoError(t, err) @@ -336,7 +335,7 @@ func TestPersonalization_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", + personalization.WithQueryParam("myParam", []int32{1, 2}), ) require.NoError(t, err) diff --git a/tests/output/go/tests/requests/query-suggestions_test.go b/tests/output/go/tests/requests/query-suggestions_test.go index 2f16825f92..443293e449 100644 --- a/tests/output/go/tests/requests/query-suggestions_test.go +++ b/tests/output/go/tests/requests/query-suggestions_test.go @@ -12,7 +12,6 @@ import ( suggestions "github.com/algolia/algoliasearch-client-go/v4/algolia/query-suggestions" "github.com/algolia/algoliasearch-client-go/v4/algolia/transport" - "github.com/algolia/algoliasearch-client-go/v4/algolia/utils" ) func createSuggestionsClient(t *testing.T) (*suggestions.APIClient, *tests.EchoRequester) { @@ -129,8 +128,8 @@ func TestSuggestions_CustomGet(t *testing.T) { _, err := client.CustomGet(client.NewApiCustomGetRequest( "test/all", ).WithParameters(map[string]any{"query": "to be overriden"}), - utils.WithQueryParam("query", "parameters with space"), utils.WithQueryParam("and an array", - []string{"array", "with spaces"}), utils.WithHeaderParam("x-header-1", "spaces are left alone"), + suggestions.WithQueryParam("query", "parameters with space"), suggestions.WithQueryParam("and an array", + []string{"array", "with spaces"}), suggestions.WithHeaderParam("x-header-1", "spaces are left alone"), ) require.NoError(t, err) @@ -190,7 +189,7 @@ func TestSuggestions_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("query", "myQueryParameter"), + suggestions.WithQueryParam("query", "myQueryParameter"), ) require.NoError(t, err) @@ -210,7 +209,7 @@ func TestSuggestions_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("query2", "myQueryParameter"), + suggestions.WithQueryParam("query2", "myQueryParameter"), ) require.NoError(t, err) @@ -230,7 +229,7 @@ func TestSuggestions_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithHeaderParam("x-algolia-api-key", "myApiKey"), + suggestions.WithHeaderParam("x-algolia-api-key", "myApiKey"), ) require.NoError(t, err) @@ -255,7 +254,7 @@ func TestSuggestions_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithHeaderParam("x-algolia-api-key", "myApiKey"), + suggestions.WithHeaderParam("x-algolia-api-key", "myApiKey"), ) require.NoError(t, err) @@ -280,7 +279,7 @@ func TestSuggestions_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("isItWorking", true), + suggestions.WithQueryParam("isItWorking", true), ) require.NoError(t, err) @@ -300,7 +299,7 @@ func TestSuggestions_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", 2), + suggestions.WithQueryParam("myParam", 2), ) require.NoError(t, err) @@ -320,7 +319,7 @@ func TestSuggestions_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", + suggestions.WithQueryParam("myParam", []string{"b and c", "d"}), ) require.NoError(t, err) @@ -341,7 +340,7 @@ func TestSuggestions_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", + suggestions.WithQueryParam("myParam", []bool{true, true, false}), ) require.NoError(t, err) @@ -362,7 +361,7 @@ func TestSuggestions_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", + suggestions.WithQueryParam("myParam", []int32{1, 2}), ) require.NoError(t, err) diff --git a/tests/output/go/tests/requests/recommend_test.go b/tests/output/go/tests/requests/recommend_test.go index cfcdac17a6..8371f4c7aa 100644 --- a/tests/output/go/tests/requests/recommend_test.go +++ b/tests/output/go/tests/requests/recommend_test.go @@ -12,7 +12,6 @@ import ( "github.com/algolia/algoliasearch-client-go/v4/algolia/recommend" "github.com/algolia/algoliasearch-client-go/v4/algolia/transport" - "github.com/algolia/algoliasearch-client-go/v4/algolia/utils" ) func createRecommendClient(t *testing.T) (*recommend.APIClient, *tests.EchoRequester) { @@ -102,8 +101,8 @@ func TestRecommend_CustomGet(t *testing.T) { _, err := client.CustomGet(client.NewApiCustomGetRequest( "test/all", ).WithParameters(map[string]any{"query": "to be overriden"}), - utils.WithQueryParam("query", "parameters with space"), utils.WithQueryParam("and an array", - []string{"array", "with spaces"}), utils.WithHeaderParam("x-header-1", "spaces are left alone"), + recommend.WithQueryParam("query", "parameters with space"), recommend.WithQueryParam("and an array", + []string{"array", "with spaces"}), recommend.WithHeaderParam("x-header-1", "spaces are left alone"), ) require.NoError(t, err) @@ -163,7 +162,7 @@ func TestRecommend_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("query", "myQueryParameter"), + recommend.WithQueryParam("query", "myQueryParameter"), ) require.NoError(t, err) @@ -183,7 +182,7 @@ func TestRecommend_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("query2", "myQueryParameter"), + recommend.WithQueryParam("query2", "myQueryParameter"), ) require.NoError(t, err) @@ -203,7 +202,7 @@ func TestRecommend_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithHeaderParam("x-algolia-api-key", "myApiKey"), + recommend.WithHeaderParam("x-algolia-api-key", "myApiKey"), ) require.NoError(t, err) @@ -228,7 +227,7 @@ func TestRecommend_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithHeaderParam("x-algolia-api-key", "myApiKey"), + recommend.WithHeaderParam("x-algolia-api-key", "myApiKey"), ) require.NoError(t, err) @@ -253,7 +252,7 @@ func TestRecommend_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("isItWorking", true), + recommend.WithQueryParam("isItWorking", true), ) require.NoError(t, err) @@ -273,7 +272,7 @@ func TestRecommend_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", 2), + recommend.WithQueryParam("myParam", 2), ) require.NoError(t, err) @@ -293,7 +292,7 @@ func TestRecommend_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", + recommend.WithQueryParam("myParam", []string{"b and c", "d"}), ) require.NoError(t, err) @@ -314,7 +313,7 @@ func TestRecommend_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", + recommend.WithQueryParam("myParam", []bool{true, true, false}), ) require.NoError(t, err) @@ -335,7 +334,7 @@ func TestRecommend_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", + recommend.WithQueryParam("myParam", []int32{1, 2}), ) require.NoError(t, err) diff --git a/tests/output/go/tests/requests/search_test.go b/tests/output/go/tests/requests/search_test.go index bd40fd8487..9d7cba23a0 100644 --- a/tests/output/go/tests/requests/search_test.go +++ b/tests/output/go/tests/requests/search_test.go @@ -13,7 +13,6 @@ import ( "github.com/algolia/algoliasearch-client-go/v4/algolia/search" "github.com/algolia/algoliasearch-client-go/v4/algolia/transport" - "github.com/algolia/algoliasearch-client-go/v4/algolia/utils" ) func createSearchClient(t *testing.T) (*search.APIClient, *tests.EchoRequester) { @@ -482,8 +481,8 @@ func TestSearch_CustomGet(t *testing.T) { _, err := client.CustomGet(client.NewApiCustomGetRequest( "test/all", ).WithParameters(map[string]any{"query": "to be overriden"}), - utils.WithQueryParam("query", "parameters with space"), utils.WithQueryParam("and an array", - []string{"array", "with spaces"}), utils.WithHeaderParam("x-header-1", "spaces are left alone"), + search.WithQueryParam("query", "parameters with space"), search.WithQueryParam("and an array", + []string{"array", "with spaces"}), search.WithHeaderParam("x-header-1", "spaces are left alone"), ) require.NoError(t, err) @@ -543,7 +542,7 @@ func TestSearch_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("query", "myQueryParameter"), + search.WithQueryParam("query", "myQueryParameter"), ) require.NoError(t, err) @@ -563,7 +562,7 @@ func TestSearch_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("query2", "myQueryParameter"), + search.WithQueryParam("query2", "myQueryParameter"), ) require.NoError(t, err) @@ -583,7 +582,7 @@ func TestSearch_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithHeaderParam("x-algolia-api-key", "myApiKey"), + search.WithHeaderParam("x-algolia-api-key", "myApiKey"), ) require.NoError(t, err) @@ -608,7 +607,7 @@ func TestSearch_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithHeaderParam("x-algolia-api-key", "myApiKey"), + search.WithHeaderParam("x-algolia-api-key", "myApiKey"), ) require.NoError(t, err) @@ -633,7 +632,7 @@ func TestSearch_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("isItWorking", true), + search.WithQueryParam("isItWorking", true), ) require.NoError(t, err) @@ -653,7 +652,7 @@ func TestSearch_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", 2), + search.WithQueryParam("myParam", 2), ) require.NoError(t, err) @@ -673,7 +672,7 @@ func TestSearch_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", + search.WithQueryParam("myParam", []string{"b and c", "d"}), ) require.NoError(t, err) @@ -694,7 +693,7 @@ func TestSearch_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", + search.WithQueryParam("myParam", []bool{true, true, false}), ) require.NoError(t, err) @@ -715,7 +714,7 @@ func TestSearch_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", + search.WithQueryParam("myParam", []int32{1, 2}), ) require.NoError(t, err) diff --git a/tests/output/go/tests/requests/usage_test.go b/tests/output/go/tests/requests/usage_test.go index 487845e10b..e39a2e75ee 100644 --- a/tests/output/go/tests/requests/usage_test.go +++ b/tests/output/go/tests/requests/usage_test.go @@ -12,7 +12,6 @@ import ( "github.com/algolia/algoliasearch-client-go/v4/algolia/transport" "github.com/algolia/algoliasearch-client-go/v4/algolia/usage" - "github.com/algolia/algoliasearch-client-go/v4/algolia/utils" ) func createUsageClient(t *testing.T) (*usage.APIClient, *tests.EchoRequester) { @@ -102,8 +101,8 @@ func TestUsage_CustomGet(t *testing.T) { _, err := client.CustomGet(client.NewApiCustomGetRequest( "test/all", ).WithParameters(map[string]any{"query": "to be overriden"}), - utils.WithQueryParam("query", "parameters with space"), utils.WithQueryParam("and an array", - []string{"array", "with spaces"}), utils.WithHeaderParam("x-header-1", "spaces are left alone"), + usage.WithQueryParam("query", "parameters with space"), usage.WithQueryParam("and an array", + []string{"array", "with spaces"}), usage.WithHeaderParam("x-header-1", "spaces are left alone"), ) require.NoError(t, err) @@ -163,7 +162,7 @@ func TestUsage_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("query", "myQueryParameter"), + usage.WithQueryParam("query", "myQueryParameter"), ) require.NoError(t, err) @@ -183,7 +182,7 @@ func TestUsage_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("query2", "myQueryParameter"), + usage.WithQueryParam("query2", "myQueryParameter"), ) require.NoError(t, err) @@ -203,7 +202,7 @@ func TestUsage_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithHeaderParam("x-algolia-api-key", "myApiKey"), + usage.WithHeaderParam("x-algolia-api-key", "myApiKey"), ) require.NoError(t, err) @@ -228,7 +227,7 @@ func TestUsage_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithHeaderParam("x-algolia-api-key", "myApiKey"), + usage.WithHeaderParam("x-algolia-api-key", "myApiKey"), ) require.NoError(t, err) @@ -253,7 +252,7 @@ func TestUsage_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("isItWorking", true), + usage.WithQueryParam("isItWorking", true), ) require.NoError(t, err) @@ -273,7 +272,7 @@ func TestUsage_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", 2), + usage.WithQueryParam("myParam", 2), ) require.NoError(t, err) @@ -293,7 +292,7 @@ func TestUsage_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", + usage.WithQueryParam("myParam", []string{"b and c", "d"}), ) require.NoError(t, err) @@ -314,7 +313,7 @@ func TestUsage_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", + usage.WithQueryParam("myParam", []bool{true, true, false}), ) require.NoError(t, err) @@ -335,7 +334,7 @@ func TestUsage_CustomPost(t *testing.T) { _, err := client.CustomPost(client.NewApiCustomPostRequest( "test/requestOptions", ).WithParameters(map[string]any{"query": "parameters"}).WithBody(map[string]any{"facet": "filters"}), - utils.WithQueryParam("myParam", + usage.WithQueryParam("myParam", []int32{1, 2}), ) require.NoError(t, err) From a68907d1c4e8e64dcbc770832b64ddebc8ed7931 Mon Sep 17 00:00:00 2001 From: Thomas Raffray Date: Thu, 18 Jul 2024 10:41:10 +0200 Subject: [PATCH 3/4] feat(clients): add api key helper test (#3338) Co-authored-by: Pierre Millot --- .../Utils/SearchClientExtensions.cs | 32 ++-- .../algolia/client/extensions/SearchClient.kt | 26 ++-- .../lib/Support/Helpers.php | 8 +- .../lib/algolia/transport/transport.rb | 2 +- .../cts/tests/ParametersWithDataType.java | 2 - .../codegen/cts/tests/TestsClient.java | 4 + .../swift/playground/playground/main.swift | 2 +- scripts/cts/runCts.ts | 2 + scripts/cts/testServer/index.ts | 2 + scripts/cts/testServer/waitForApiKey.ts | 120 ++++++++++++++ specs/search/helpers/waitForApiKey.yml | 12 +- templates/csharp/tests/client/suite.mustache | 7 +- templates/dart/tests/request_param.mustache | 2 +- templates/go/tests/client/suite.mustache | 5 + templates/java/api_helpers.mustache | 70 ++++----- templates/java/tests/client/suite.mustache | 14 +- .../clients/client/api/helpers.mustache | 18 ++- .../javascript/tests/client/suite.mustache | 7 +- templates/kotlin/tests/client/suite.mustache | 31 ++-- templates/kotlin/tests/request_param.mustache | 2 +- templates/php/api.mustache | 8 +- templates/php/tests/client/suite.mustache | 13 +- templates/python/search_helpers.mustache | 24 +-- templates/python/tests/client/suite.mustache | 5 + templates/ruby/search_helpers.mustache | 34 ++-- templates/ruby/tests/client/suite.mustache | 5 + templates/scala/tests/client/suite.mustache | 5 + templates/swift/tests/client/suite.mustache | 7 +- tests/CTS/client/search/helpers.json | 146 ++++++++++++++++++ .../csharp/src/ClientExtensionsTests.cs | 51 ------ .../kotlin/com/algolia/utils/Assert.kt | 2 +- 31 files changed, 481 insertions(+), 187 deletions(-) create mode 100644 scripts/cts/testServer/waitForApiKey.ts diff --git a/clients/algoliasearch-client-csharp/algoliasearch/Utils/SearchClientExtensions.cs b/clients/algoliasearch-client-csharp/algoliasearch/Utils/SearchClientExtensions.cs index 58c646d72c..a59e21966d 100644 --- a/clients/algoliasearch-client-csharp/algoliasearch/Utils/SearchClientExtensions.cs +++ b/clients/algoliasearch-client-csharp/algoliasearch/Utils/SearchClientExtensions.cs @@ -76,14 +76,15 @@ public GetTaskResponse WaitForAppTask(long taskId, int maxRetries = DefaultMaxRe /// /// Helper method that waits for an API key task to be processed. /// - /// The `operation` that was done on a `key`. /// The key that has been added, deleted or updated. + /// The `operation` that was done on a `key`. /// Necessary to know if an `update` operation has been processed, compare fields of the response with it. (optional - mandatory if operation is UPDATE) /// The maximum number of retry. 50 by default. (optional) /// The function to decide how long to wait between retries. Math.Min(retryCount * 200, 5000) by default. (optional) /// The requestOptions to send along with the query, they will be merged with the transporter requestOptions. (optional) /// Cancellation token (optional) - public async Task WaitForApiKeyAsync(ApiKeyOperation operation, string key, + public async Task WaitForApiKeyAsync(string key, + ApiKeyOperation operation, ApiKey apiKey = default, int maxRetries = DefaultMaxRetries, Func timeout = null, RequestOptions requestOptions = null, CancellationToken ct = default) { @@ -112,36 +113,35 @@ public async Task WaitForApiKeyAsync(ApiKeyOperation operatio }, maxRetries, timeout, ct).ConfigureAwait(false); } - var addedKey = new GetApiKeyResponse(); - - // check the status of the getApiKey method - await RetryUntil(async () => + return await RetryUntil(async () => { try { - addedKey = await GetApiKeyAsync(key, requestOptions, ct).ConfigureAwait(false); - // magic number to signify we found the key - return -2; + return await GetApiKeyAsync(key, requestOptions, ct).ConfigureAwait(false); } catch (AlgoliaApiException e) { - return e.HttpErrorCode; + if (e.HttpErrorCode is 404) + { + return null; + } + + throw; } - }, (status) => + }, (response) => { return operation switch { ApiKeyOperation.Add => // stop either when the key is created or when we don't receive 404 - status is -2 or not 404 and not 0, + response is not null, ApiKeyOperation.Delete => // stop when the key is not found - status == 404, + response is null, _ => false }; }, maxRetries, timeout, ct); - return addedKey; } /// @@ -154,10 +154,10 @@ await RetryUntil(async () => /// The function to decide how long to wait between retries. Math.Min(retryCount * 200, 5000) by default. (optional) /// The requestOptions to send along with the query, they will be merged with the transporter requestOptions. (optional) /// Cancellation token (optional) - public GetApiKeyResponse WaitForApiKey(ApiKeyOperation operation, string key, ApiKey apiKey = default, + public GetApiKeyResponse WaitForApiKey(string key, ApiKeyOperation operation, ApiKey apiKey = default, int maxRetries = DefaultMaxRetries, Func timeout = null, RequestOptions requestOptions = null, CancellationToken ct = default) => - AsyncHelper.RunSync(() => WaitForApiKeyAsync(operation, key, apiKey, maxRetries, timeout, requestOptions, ct)); + AsyncHelper.RunSync(() => WaitForApiKeyAsync(key, operation, apiKey, maxRetries, timeout, requestOptions, ct)); /// diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/extensions/SearchClient.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/extensions/SearchClient.kt index 71fbddc015..5daa3961b9 100644 --- a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/extensions/SearchClient.kt +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/extensions/SearchClient.kt @@ -20,8 +20,8 @@ import kotlin.time.Duration.Companion.seconds /** * Wait for an API key to be added, updated or deleted based on a given `operation`. * - * @param operation The `operation` that was done on a `key`. * @param key The `key` that has been added, deleted or updated. + * @param operation The `operation` that was done on a `key`. * @param apiKey Necessary to know if an `update` operation has been processed, compare fields of * the response with it. * @param maxRetries The maximum number of retries. 50 by default. (optional) @@ -31,16 +31,16 @@ import kotlin.time.Duration.Companion.seconds * the transporter requestOptions. (optional) */ public suspend fun SearchClient.waitForApiKey( - operation: ApiKeyOperation, key: String, + operation: ApiKeyOperation, apiKey: ApiKey? = null, maxRetries: Int = 50, timeout: Duration = Duration.INFINITE, initialDelay: Duration = 200.milliseconds, maxDelay: Duration = 5.seconds, requestOptions: RequestOptions? = null, -) { - when (operation) { +): GetApiKeyResponse? { + return when (operation) { ApiKeyOperation.Add -> waitKeyCreation( key = key, maxRetries = maxRetries, @@ -226,25 +226,25 @@ public suspend fun SearchClient.waitKeyDelete( initialDelay: Duration = 200.milliseconds, maxDelay: Duration = 5.seconds, requestOptions: RequestOptions? = null, -) { - retryUntil( +): GetApiKeyResponse? { + return retryUntil( timeout = timeout, maxRetries = maxRetries, initialDelay = initialDelay, maxDelay = maxDelay, retry = { try { - val response = getApiKey(key, requestOptions) - Result.success(response) + return@retryUntil getApiKey(key, requestOptions) } catch (e: AlgoliaApiException) { - Result.failure(e) + if (e.httpErrorCode == 404) { + return@retryUntil null + } + + throw e } }, until = { result -> - result.fold( - onSuccess = { false }, - onFailure = { (it as AlgoliaApiException).httpErrorCode == 404 }, - ) + result == null }, ) } diff --git a/clients/algoliasearch-client-php/lib/Support/Helpers.php b/clients/algoliasearch-client-php/lib/Support/Helpers.php index 41db0ca4ba..7f48f9d8ee 100644 --- a/clients/algoliasearch-client-php/lib/Support/Helpers.php +++ b/clients/algoliasearch-client-php/lib/Support/Helpers.php @@ -151,13 +151,13 @@ public static function retryForApiKeyUntil( // In case of an addition, if there was no error, the $key has been added as it should be if ('add' === $operation) { - return; + return $response; } // In case of an update, check if the key has been updated as it should be if ('update' === $operation) { if (self::isKeyUpdated($response, $apiKey)) { - return; + return $response; } } @@ -166,9 +166,9 @@ public static function retryForApiKeyUntil( // In case of a deletion, if there was an error, the $key has been deleted as it should be if ( 'delete' === $operation - && 'Key does not exist' === $e->getMessage() + && $e->getCode() === 404 ) { - return; + return null; } // Else try again ... diff --git a/clients/algoliasearch-client-ruby/lib/algolia/transport/transport.rb b/clients/algoliasearch-client-ruby/lib/algolia/transport/transport.rb index 383260ff6c..61839f0c62 100644 --- a/clients/algoliasearch-client-ruby/lib/algolia/transport/transport.rb +++ b/clients/algoliasearch-client-ruby/lib/algolia/transport/transport.rb @@ -68,7 +68,7 @@ def request(call_type, method, path, body, opts = {}) ) if outcome == FAILURE decoded_error = JSON.parse(response.error, :symbolize_names => true) - raise Algolia::AlgoliaHttpError.new(decoded_error[:status], decoded_error[:message]) + raise Algolia::AlgoliaHttpError.new(response.status, decoded_error[:message]) end return response unless outcome == RETRY diff --git a/generators/src/main/java/com/algolia/codegen/cts/tests/ParametersWithDataType.java b/generators/src/main/java/com/algolia/codegen/cts/tests/ParametersWithDataType.java index ec1909cf8f..03d4a1a5b4 100644 --- a/generators/src/main/java/com/algolia/codegen/cts/tests/ParametersWithDataType.java +++ b/generators/src/main/java/com/algolia/codegen/cts/tests/ParametersWithDataType.java @@ -10,7 +10,6 @@ import java.util.Map.Entry; import java.util.stream.Collectors; import java.util.stream.IntStream; -import org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.*; @SuppressWarnings("unchecked") @@ -128,7 +127,6 @@ private Map traverseParams( String finalParamName = getFinalParamName(paramName); testOutput.put("key", finalParamName); - testOutput.put("isKeyAllUpperCase", StringUtils.isAllUpperCase(finalParamName)); testOutput.put("useAnonymousKey", !finalParamName.matches("(.*)_[0-9]$") && depth != 0); testOutput.put("parent", parent); testOutput.put("isRoot", "".equals(parent)); diff --git a/generators/src/main/java/com/algolia/codegen/cts/tests/TestsClient.java b/generators/src/main/java/com/algolia/codegen/cts/tests/TestsClient.java index cff8fb275f..043a96494d 100644 --- a/generators/src/main/java/com/algolia/codegen/cts/tests/TestsClient.java +++ b/generators/src/main/java/com/algolia/codegen/cts/tests/TestsClient.java @@ -169,6 +169,10 @@ public void run(Map models, Map } else { stepOut.put("match", step.expected.match); } + } else if (step.expected.match == null) { + stepOut.put("match", Map.of()); + stepOut.put("matchIsJSON", false); + stepOut.put("matchIsNull", true); } } steps.add(stepOut); diff --git a/playground/swift/playground/playground/main.swift b/playground/swift/playground/playground/main.swift index c098a2fc10..40fe056a17 100644 --- a/playground/swift/playground/playground/main.swift +++ b/playground/swift/playground/playground/main.swift @@ -44,7 +44,7 @@ Task { taskIDs.append(saveObjRes.taskID) } for taskID in taskIDs { - try await client.waitForTask(with: taskID, in: indexName) + try await client.waitForTask(indexName: indexName, taskID: taskID) } let searchParams = SearchSearchParamsObject(query: "Jimmy") diff --git a/scripts/cts/runCts.ts b/scripts/cts/runCts.ts index 9f6737aa98..7e7d211493 100644 --- a/scripts/cts/runCts.ts +++ b/scripts/cts/runCts.ts @@ -9,6 +9,7 @@ import { startTestServer } from './testServer'; import { assertChunkWrapperValid } from './testServer/chunkWrapper.js'; import { assertValidReplaceAllObjects } from './testServer/replaceAllObjects.js'; import { assertValidTimeouts } from './testServer/timeout.js'; +import { assertValidWaitForApiKey } from './testServer/waitForApiKey.js'; async function runCtsOne( language: Language, @@ -152,5 +153,6 @@ export async function runCts( assertValidTimeouts(languages.length); assertChunkWrapperValid(languages.length - skip('dart') - skip('scala')); assertValidReplaceAllObjects(languages.length - skip('dart') - skip('scala')); + assertValidWaitForApiKey(languages.length - skip('dart') - skip('scala')); } } diff --git a/scripts/cts/testServer/index.ts b/scripts/cts/testServer/index.ts index 19c56f46e5..8dbf0c0b13 100644 --- a/scripts/cts/testServer/index.ts +++ b/scripts/cts/testServer/index.ts @@ -10,6 +10,7 @@ import { gzipServer } from './gzip'; import { replaceAllObjectsServer } from './replaceAllObjects'; import { timeoutServer } from './timeout'; import { timeoutServerBis } from './timeoutBis'; +import { waitForApiKeyServer } from './waitForApiKey'; export async function startTestServer(): Promise<() => Promise> { const servers = await Promise.all([ @@ -18,6 +19,7 @@ export async function startTestServer(): Promise<() => Promise> { timeoutServerBis(), replaceAllObjectsServer(), chunkWrapperServer(), + waitForApiKeyServer(), ]); return async () => { diff --git a/scripts/cts/testServer/waitForApiKey.ts b/scripts/cts/testServer/waitForApiKey.ts new file mode 100644 index 0000000000..be3f228f96 --- /dev/null +++ b/scripts/cts/testServer/waitForApiKey.ts @@ -0,0 +1,120 @@ +import type { Server } from 'http'; + +import { expect } from 'chai'; +import type { Express } from 'express'; + +import { setupServer } from '.'; + +const retryCount: Record< + string, + { + add: number; + update: number; + delete: number; + } +> = {}; + +export function assertValidWaitForApiKey(expectedCount: number): void { + expect(Object.keys(retryCount).length).to.be.equal(expectedCount); + for (const retry of Object.values(retryCount)) { + expect(retry).to.deep.equal({ + add: 0, + update: 0, + delete: 0, + }); + } +} + +function addRoutes(app: Express): void { + app.get('/1/keys/:key', (req, res) => { + const lang = req.params.key.split('-').at(-1) as string; + if (!retryCount[lang]) { + retryCount[lang] = { + add: 0, + update: 0, + delete: 0, + }; + } + const retry = retryCount[lang]; + if (req.params.key === `api-key-add-operation-test-${lang}`) { + if (retry.add < 3) { + res.status(404).json({ message: `API key doesn't exist` }); + } else if (retry.add === 3) { + res.status(200).json({ + value: req.params.key, + description: 'my new api key', + acl: ['search', 'addObject'], + validity: 300, + maxQueriesPerIPPerHour: 100, + maxHitsPerQuery: 20, + createdAt: 1720094400, + }); + + retry.add = -1; + } else { + expect(retry.add).to.be.lessThan(3); + return; + } + + retry.add += 1; + } else if (req.params.key === `api-key-update-operation-test-${lang}`) { + if (retry.update < 3) { + res.status(200).json({ + value: req.params.key, + description: 'my new api key', + acl: ['search', 'addObject'], + validity: 300, + maxQueriesPerIPPerHour: 100, + maxHitsPerQuery: 20, + createdAt: 1720094400, + }); + } else if (retry.update === 3) { + res.status(200).json({ + value: req.params.key, + description: 'my updated api key', + acl: ['search', 'addObject', 'deleteObject'], + indexes: ['Movies', 'Books'], + referers: ['*google.com', '*algolia.com'], + validity: 305, + maxQueriesPerIPPerHour: 95, + maxHitsPerQuery: 20, + createdAt: 1720094400, + }); + + retry.update = -1; + } else { + expect(retry.update).to.be.lessThan(3); + return; + } + + retry.update += 1; + } else if (req.params.key === `api-key-delete-operation-test-${lang}`) { + if (retry.delete < 3) { + res.status(200).json({ + value: req.params.key, + description: 'my updated api key', + acl: ['search', 'addObject', 'deleteObject'], + validity: 305, + maxQueriesPerIPPerHour: 95, + maxHitsPerQuery: 20, + createdAt: 1720094400, + }); + } else if (retry.delete === 3) { + res.status(404).json({ message: `API key doesn't exist` }); + + retry.delete = -1; + } else { + expect(retry.delete).to.be.lessThan(3); + return; + } + + retry.delete += 1; + } else { + throw new Error(`Invalid API key ${req.params.key}`); + } + }); +} + +export function waitForApiKeyServer(): Promise { + return setupServer('waitForApiKey', 6681, addRoutes); +} diff --git a/specs/search/helpers/waitForApiKey.yml b/specs/search/helpers/waitForApiKey.yml index 8ba9a19c95..8854fd46ac 100644 --- a/specs/search/helpers/waitForApiKey.yml +++ b/specs/search/helpers/waitForApiKey.yml @@ -7,18 +7,18 @@ method: summary: Wait for an API key operation description: Waits for an API key to be added, updated, or deleted. parameters: - - in: query - name: operation - description: Whether the API key was created, updated, or deleted. - required: true - schema: - $ref: '#/apiKeyOperation' - in: query name: key description: API key to wait for. required: true schema: type: string + - in: query + name: operation + description: Whether the API key was created, updated, or deleted. + required: true + schema: + $ref: '#/apiKeyOperation' - in: query name: apiKey description: Used to compare fields of the `getApiKey` response on an `update` operation, to check if the `key` has been updated. diff --git a/templates/csharp/tests/client/suite.mustache b/templates/csharp/tests/client/suite.mustache index 5fa54b5c5f..4aa514f146 100644 --- a/templates/csharp/tests/client/suite.mustache +++ b/templates/csharp/tests/client/suite.mustache @@ -62,7 +62,12 @@ public void Dispose() JsonAssert.EqualOverrideDefault("{{#lambda.escapeQuotes}}{{{match.parameters}}}{{/lambda.escapeQuotes}}", JsonSerializer.Serialize(res, JsonConfig.Options), new JsonDiffConfig(false)); {{/matchIsJSON}} {{^matchIsJSON}} - Assert.Equal("{{{match}}}", res); + {{#matchIsNull}} + Assert.Null(res); + {{/matchIsNull}} + {{^matchIsNull}} + Assert.Equal("{{{match}}}", res); + {{/matchIsNull}} {{/matchIsJSON}} {{/testResponse}} {{/match}} diff --git a/templates/dart/tests/request_param.mustache b/templates/dart/tests/request_param.mustache index be2a04a688..6b8f94c414 100644 --- a/templates/dart/tests/request_param.mustache +++ b/templates/dart/tests/request_param.mustache @@ -1,5 +1,5 @@ {{^isAdditionalProperty}} -{{#isKeyAllUpperCase}}{{#lambda.lowercase}}{{&key}}{{/lambda.lowercase}}{{/isKeyAllUpperCase}}{{^isKeyAllUpperCase}}{{#lambda.camelcase}}{{&key}}{{/lambda.camelcase}}{{/isKeyAllUpperCase}} : {{> tests/param_value}}, +{{#lambda.camelcase}}{{{key}}}{{/lambda.camelcase}} : {{> tests/param_value}}, {{/isAdditionalProperty}} {{#isAdditionalProperty}} additionalProperties : { '{{{key}}}' : '{{{value}}}' }, diff --git a/templates/go/tests/client/suite.mustache b/templates/go/tests/client/suite.mustache index 95e81f77e7..05d0dccffa 100644 --- a/templates/go/tests/client/suite.mustache +++ b/templates/go/tests/client/suite.mustache @@ -75,7 +75,12 @@ func Test{{#lambda.titlecase}}{{clientPrefix}}{{testType}}{{/lambda.titlecase}}{ require.JSONEq(t, `{{{match.parameters}}}`, string(rawBody)) {{/matchIsJSON}} {{^matchIsJSON}} + {{#matchIsNull}} + require.Nil(t, res) + {{/matchIsNull}} + {{^matchIsNull}} require.Equal(t, `{{{match}}}`, res) + {{/matchIsNull}} {{/matchIsJSON}} {{/testResponse}} {{/match}} diff --git a/templates/java/api_helpers.mustache b/templates/java/api_helpers.mustache index 18d06b58e9..ed65a59249 100644 --- a/templates/java/api_helpers.mustache +++ b/templates/java/api_helpers.mustache @@ -112,8 +112,8 @@ this.waitForAppTask(taskID, TaskUtils.DEFAULT_MAX_RETRIES, TaskUtils.DEFAULT_TIM * @param requestOptions The requestOptions to send along with the query, they will be merged with the transporter requestOptions. (optional) */ public GetApiKeyResponse waitForApiKey( - ApiKeyOperation operation, String key, + ApiKeyOperation operation, ApiKey apiKey, int maxRetries, IntUnaryOperator timeout, @@ -146,28 +146,26 @@ public GetApiKeyResponse waitForApiKey( ); } - // bypass lambda restriction to modify final object - final GetApiKeyResponse[] addedKey = new GetApiKeyResponse[] { null }; - - // check the status of the getApiKey method - TaskUtils.retryUntil( + return TaskUtils.retryUntil( () -> { try { - addedKey[0] = this.getApiKey(key, requestOptions); - // magic number to signify we found the key - return -2; + return this.getApiKey(key, requestOptions); } catch (AlgoliaApiException e) { - return e.getStatusCode(); + if (e.getStatusCode() == 404) { + return null; + } + + throw e; } }, - (Integer status) -> { + (GetApiKeyResponse response) -> { switch (operation) { case ADD: - // stop either when the key is created or when we don't receive 404 - return status == -2 || status != 404; + // stop when we don't receive 404 meaning the key is created + return response != null; case DELETE: // stop when the key is not found - return status == 404; + return response == null; default: // continue return false; @@ -176,84 +174,82 @@ public GetApiKeyResponse waitForApiKey( maxRetries, timeout ); - - return addedKey[0]; } /** * Helper: Wait for an API key to be added or deleted based on a given `operation`. * - * @param operation The `operation` that was done on a `key`. (ADD or DELETE only) * @param key The `key` that has been added or deleted. + * @param operation The `operation` that was done on a `key`. (ADD or DELETE only) * @param maxRetries The maximum number of retry. 50 by default. (optional) * @param timeout The function to decide how long to wait between retries. min(retries * 200, 5000) by default. (optional) * @param requestOptions The requestOptions to send along with the query, they will be merged with the transporter requestOptions. (optional) */ -public GetApiKeyResponse waitForApiKey(ApiKeyOperation operation, String key, int maxRetries, IntUnaryOperator timeout, RequestOptions requestOptions) { - return this.waitForApiKey(operation, key, null, maxRetries, timeout, requestOptions); +public GetApiKeyResponse waitForApiKey(String key, ApiKeyOperation operation, int maxRetries, IntUnaryOperator timeout, RequestOptions requestOptions) { + return this.waitForApiKey(key, operation, null, maxRetries, timeout, requestOptions); } /** * Helper: Wait for an API key to be added, updated or deleted based on a given `operation`. * - * @param operation The `operation` that was done on a `key`. * @param key The `key` that has been added, deleted or updated. + * @param operation The `operation` that was done on a `key`. * @param apiKey Necessary to know if an `update` operation has been processed, compare fields of the response with it. * @param requestOptions The requestOptions to send along with the query, they will be merged with the transporter requestOptions. (optional) */ -public GetApiKeyResponse waitForApiKey(ApiKeyOperation operation, String key, ApiKey apiKey, RequestOptions requestOptions) { - return this.waitForApiKey(operation, key, apiKey, TaskUtils.DEFAULT_MAX_RETRIES, TaskUtils.DEFAULT_TIMEOUT, requestOptions); +public GetApiKeyResponse waitForApiKey(String key, ApiKeyOperation operation, ApiKey apiKey, RequestOptions requestOptions) { + return this.waitForApiKey(key, operation, apiKey, TaskUtils.DEFAULT_MAX_RETRIES, TaskUtils.DEFAULT_TIMEOUT, requestOptions); } /** * Helper: Wait for an API key to be added or deleted based on a given `operation`. * - * @param operation The `operation` that was done on a `key`. (ADD or DELETE only) * @param key The `key` that has been added or deleted. + * @param operation The `operation` that was done on a `key`. (ADD or DELETE only) * @param requestOptions The requestOptions to send along with the query, they will be merged with the transporter requestOptions. (optional) */ -public GetApiKeyResponse waitForApiKey(ApiKeyOperation operation, String key, RequestOptions requestOptions) { - return this.waitForApiKey(operation, key, null, TaskUtils.DEFAULT_MAX_RETRIES, TaskUtils.DEFAULT_TIMEOUT, requestOptions); +public GetApiKeyResponse waitForApiKey(String key, ApiKeyOperation operation, RequestOptions requestOptions) { + return this.waitForApiKey(key, operation, null, TaskUtils.DEFAULT_MAX_RETRIES, TaskUtils.DEFAULT_TIMEOUT, requestOptions); } /** * Helper: Wait for an API key to be added, updated or deleted based on a given `operation`. * - * @param operation The `operation` that was done on a `key`. * @param key The `key` that has been added, deleted or updated. + * @param operation The `operation` that was done on a `key`. * @param apiKey Necessary to know if an `update` operation has been processed, compare fields of the response with it. * @param maxRetries The maximum number of retry. 50 by default. (optional) * @param timeout The function to decide how long to wait between retries. min(retries * 200, 5000) by default. (optional) */ -public GetApiKeyResponse waitForApiKey(ApiKeyOperation operation, String key, ApiKey apiKey, int maxRetries, IntUnaryOperator timeout) { - return this.waitForApiKey(operation, key, apiKey, maxRetries, timeout, null); +public GetApiKeyResponse waitForApiKey(String key, ApiKeyOperation operation, ApiKey apiKey, int maxRetries, IntUnaryOperator timeout) { + return this.waitForApiKey(key, operation, apiKey, maxRetries, timeout, null); } /** * Helper: Wait for an API key to be added or deleted based on a given `operation`. * - * @param operation The `operation` that was done on a `key`. (ADD or DELETE only) * @param key The `key` that has been added or deleted. + * @param operation The `operation` that was done on a `key`. (ADD or DELETE only) * @param maxRetries The maximum number of retry. 50 by default. (optional) * @param timeout The function to decide how long to wait between retries. min(retries * 200, 5000) by default. (optional) */ -public GetApiKeyResponse waitForApiKey(ApiKeyOperation operation, String key, int maxRetries, IntUnaryOperator timeout) { - return this.waitForApiKey(operation, key, null, maxRetries, timeout, null); +public GetApiKeyResponse waitForApiKey(String key, ApiKeyOperation operation, int maxRetries, IntUnaryOperator timeout) { + return this.waitForApiKey(key, operation, null, maxRetries, timeout, null); } /** * Helper: Wait for an API key to be added, updated or deleted based on a given `operation`. * - * @param operation The `operation` that was done on a `key`. * @param key The `key` that has been added, deleted or updated. + * @param operation The `operation` that was done on a `key`. * @param apiKey Necessary to know if an `update` operation has been processed, compare fields of the response with it. */ -public GetApiKeyResponse waitForApiKey(ApiKeyOperation operation, String key, ApiKey apiKey) { - return this.waitForApiKey(operation, key, apiKey, TaskUtils.DEFAULT_MAX_RETRIES, TaskUtils.DEFAULT_TIMEOUT, null); +public GetApiKeyResponse waitForApiKey(String key, ApiKeyOperation operation, ApiKey apiKey) { + return this.waitForApiKey(key, operation, apiKey, TaskUtils.DEFAULT_MAX_RETRIES, TaskUtils.DEFAULT_TIMEOUT, null); } /** * Helper: Wait for an API key to be added or deleted based on a given `operation`. * - * @param operation The `operation` that was done on a `key`. (ADD or DELETE only) * @param key The `key` that has been added or deleted. + * @param operation The `operation` that was done on a `key`. (ADD or DELETE only) */ -public GetApiKeyResponse waitForApiKey(ApiKeyOperation operation, String key) { - return this.waitForApiKey(operation, key, null, TaskUtils.DEFAULT_MAX_RETRIES, TaskUtils.DEFAULT_TIMEOUT, null); +public GetApiKeyResponse waitForApiKey(String key, ApiKeyOperation operation) { + return this.waitForApiKey(key, operation, null, TaskUtils.DEFAULT_MAX_RETRIES, TaskUtils.DEFAULT_TIMEOUT, null); } /** diff --git a/templates/java/tests/client/suite.mustache b/templates/java/tests/client/suite.mustache index bc232ec089..6d951236a2 100644 --- a/templates/java/tests/client/suite.mustache +++ b/templates/java/tests/client/suite.mustache @@ -16,6 +16,7 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.json.JsonMapper; import com.fasterxml.jackson.databind.ObjectMapper; @@ -29,7 +30,11 @@ class {{client}}ClientTests { @BeforeAll void init() { - this.json = JsonMapper.builder().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).build(); + this.json = JsonMapper. + builder(). + configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false). + serializationInclusion(JsonInclude.Include.NON_NULL). + build(); } {{client}} createClient() { @@ -82,7 +87,12 @@ class {{client}}ClientTests { assertDoesNotThrow(() -> JSONAssert.assertEquals("{{#lambda.escapeQuotes}}{{{match.parameters}}}{{/lambda.escapeQuotes}}", json.writeValueAsString(res), JSONCompareMode.STRICT)); {{/matchIsJSON}} {{^matchIsJSON}} - assertEquals("{{{match}}}", res); + {{#matchIsNull}} + assertEquals(null, res); + {{/matchIsNull}} + {{^matchIsNull}} + assertEquals("{{{match}}}", res); + {{/matchIsNull}} {{/matchIsJSON}} {{/testResponse}} {{/match}} diff --git a/templates/javascript/clients/client/api/helpers.mustache b/templates/javascript/clients/client/api/helpers.mustache index a9a6daa0ab..de9c98cbf8 100644 --- a/templates/javascript/clients/client/api/helpers.mustache +++ b/templates/javascript/clients/client/api/helpers.mustache @@ -90,9 +90,11 @@ waitForApiKey( Math.min(retryCount * 200, 5000), }: WaitForApiKeyOptions, requestOptions?: RequestOptions -): Promise { +): Promise { let retryCount = 0; - const baseIteratorOptions: IterableOptions = { + const baseIteratorOptions: IterableOptions< + GetApiKeyResponse | undefined + > = { aggregator: () => (retryCount += 1), error: { validate: () => retryCount >= maxRetries, @@ -135,9 +137,15 @@ waitForApiKey( return createIterablePromise({ ...baseIteratorOptions, func: () => - this.getApiKey({ key }, requestOptions).catch((error) => error), - validate: (error: ApiError) => - operation === 'add' ? error.status !== 404 : error.status === 404, + this.getApiKey({ key }, requestOptions).catch((error: ApiError) => { + if (error.status === 404) { + return undefined; + } + + throw error; + }), + validate: (response) => + operation === 'add' ? response !== undefined : response === undefined, }); }, diff --git a/templates/javascript/tests/client/suite.mustache b/templates/javascript/tests/client/suite.mustache index 4858481925..d1a45165c8 100644 --- a/templates/javascript/tests/client/suite.mustache +++ b/templates/javascript/tests/client/suite.mustache @@ -46,7 +46,12 @@ describe('{{testType}}', () => { expect(result).toEqual({{{match.parameters}}}); {{/matchIsJSON}} {{^matchIsJSON}} - expect(result).toEqual("{{{match}}}"); + {{#matchIsNull}} + expect(result).toBeUndefined(); + {{/matchIsNull}} + {{^matchIsNull}} + expect(result).toEqual("{{{match}}}"); + {{/matchIsNull}} {{/matchIsJSON}} {{/testResponse}} {{/isError}} diff --git a/templates/kotlin/tests/client/suite.mustache b/templates/kotlin/tests/client/suite.mustache index e747cff7cd..489230cb12 100644 --- a/templates/kotlin/tests/client/suite.mustache +++ b/templates/kotlin/tests/client/suite.mustache @@ -56,15 +56,28 @@ class {{clientPrefix}}Test { {{#testHost}} assertEquals("{{{match}}}", it.url.host); {{/testHost}} - }{{/testResponse}}{{#testResponse}}response = { - {{#matchIsJSON}} - val response = Json.encodeToString(it) - assertEquals("{{#lambda.escapeQuotes}}{{{match.parameters}}}{{/lambda.escapeQuotes}}", response) - {{/matchIsJSON}} - {{^matchIsJSON}} - assertEquals("{{{match}}}", it) - {{/matchIsJSON}} - }{{/testResponse}} + }{{/testResponse}}{{#testResponse}} + {{#isHelper}}response = { + {{#matchIsJSON}} + assertNotNull(it) + val expected = Json.parseToJsonElement("""{{{match.parameters}}}""") + val actual = Json.encodeToJsonElement(it) + areJsonElementsEqual(expected, actual) + {{/matchIsJSON}} + {{^matchIsJSON}} + {{#matchIsNull}} + assertNull(it) + {{/matchIsNull}} + {{^matchIsNull}} + assertEquals("""{{{match}}}""", it) + {{/matchIsNull}} + {{/matchIsJSON}} + }{{/isHelper}} + {{^isHelper}}response = { + val response = Json.encodeToString(it) + assertEquals("{{#lambda.escapeQuotes}}{{{match.parameters}}}{{/lambda.escapeQuotes}}", response) + }{{/isHelper}} + {{/testResponse}} {{/match}} ) {{/isMethod}} diff --git a/templates/kotlin/tests/request_param.mustache b/templates/kotlin/tests/request_param.mustache index 91f7021a46..d9017943af 100644 --- a/templates/kotlin/tests/request_param.mustache +++ b/templates/kotlin/tests/request_param.mustache @@ -1 +1 @@ -{{^isAdditionalProperty}}{{#isKeyAllUpperCase}}{{#lambda.lowercase}}{{&key}}{{/lambda.lowercase}}{{/isKeyAllUpperCase}}{{^isKeyAllUpperCase}}{{#lambda.camelcase}}{{&key}}{{/lambda.camelcase}}{{/isKeyAllUpperCase}} = {{> tests/param_value}}{{/isAdditionalProperty}}{{#isAdditionalProperty}}additionalProperties = mapOf("{{key}}" to {{> tests/param_json_element}}){{/isAdditionalProperty}} \ No newline at end of file +{{^isAdditionalProperty}}{{#lambda.camelcase}}{{{key}}}{{/lambda.camelcase}} = {{> tests/param_value}}{{/isAdditionalProperty}}{{#isAdditionalProperty}}additionalProperties = mapOf("{{key}}" to {{> tests/param_json_element}}){{/isAdditionalProperty}} \ No newline at end of file diff --git a/templates/php/api.mustache b/templates/php/api.mustache index bd776eea5d..290c6c4bdb 100644 --- a/templates/php/api.mustache +++ b/templates/php/api.mustache @@ -362,8 +362,8 @@ use {{invokerPackage}}\Support\Helpers; /** * Wait for an API key to be added, updated or deleted based on a given `operation`. * - * @param string $operation the `operation` that was done on a `key` * @param string $key the `key` that has been added, deleted or updated + * @param string $operation the `operation` that was done on a `key` * @param array $apiKey Necessary to know if an `update` operation has been processed, compare fields of the response with it. * @param int|null $maxRetries Maximum number of retries * @param int|null $timeout Timeout @@ -374,8 +374,8 @@ use {{invokerPackage}}\Support\Helpers; * @return void */ public function waitForApiKey( - $operation, $key, + $operation, $apiKey = null, $maxRetries = null, $timeout = null, @@ -389,14 +389,14 @@ use {{invokerPackage}}\Support\Helpers; $maxRetries = $this->config->getDefaultMaxRetries(); } - Helpers::retryForApiKeyUntil( + return Helpers::retryForApiKeyUntil( $operation, $this, $key, $apiKey, $maxRetries, $timeout, - null, + 'Algolia\AlgoliaSearch\Support\Helpers::linearTimeout', $requestOptions ); } diff --git a/templates/php/tests/client/suite.mustache b/templates/php/tests/client/suite.mustache index 34d118feeb..9cf9915952 100644 --- a/templates/php/tests/client/suite.mustache +++ b/templates/php/tests/client/suite.mustache @@ -102,10 +102,15 @@ class {{clientPrefix}}Test extends TestCase implements HttpClientInterface ); {{/matchIsJSON}} {{^matchIsJSON}} - $this->assertEquals( - '{{{match}}}', - $res - ); + {{#matchIsNull}} + $this->assertNull($res); + {{/matchIsNull}} + {{^matchIsNull}} + $this->assertEquals( + '{{{match}}}', + $res + ); + {{/matchIsNull}} {{/matchIsJSON}} {{/testResponse}} {{/match}} diff --git a/templates/python/search_helpers.mustache b/templates/python/search_helpers.mustache index ba3faa4614..50762b0eb4 100644 --- a/templates/python/search_helpers.mustache +++ b/templates/python/search_helpers.mustache @@ -55,13 +55,13 @@ async def wait_for_api_key( self, - operation: str, key: str, + operation: str, api_key: Optional[ApiKey] = None, max_retries: int = 50, timeout: RetryTimeout = RetryTimeout(), request_options: Optional[Union[dict, RequestOptions]] = None, - ) -> GetApiKeyResponse: + ) -> GetApiKeyResponse | None: """ Helper: Wait for an API key to be added, updated or deleted based on a given `operation`. """ @@ -72,7 +72,7 @@ "`apiKey` is required when waiting for an `update` operation." ) - async def _func(_prev: GetApiKeyResponse) -> GetApiKeyResponse: + async def _func(_prev: GetApiKeyResponse | None) -> GetApiKeyResponse | None: try: return await self.get_api_key(key=key, request_options=request_options) except RequestException as e: @@ -80,18 +80,22 @@ return None raise e - def _aggregator(_: GetApiKeyResponse) -> None: + def _aggregator(_: GetApiKeyResponse | None) -> None: self._retry_count += 1 - def _validate(_resp: GetApiKeyResponse) -> bool: + def _validate(_resp: GetApiKeyResponse | None) -> bool: if operation == "update": - for field in api_key: - if isinstance(api_key[field], list) and isinstance(_resp[field], list): - if len(api_key[field]) != len(_resp[field]) or any( - v != _resp[field][i] for i, v in enumerate(api_key[field]) + resp_dict = _resp.to_dict() + api_key_dict = api_key.to_dict() if isinstance(api_key, ApiKey) else api_key + for field in api_key_dict: + if isinstance(api_key_dict[field], list) and isinstance( + resp_dict[field], list + ): + if len(api_key_dict[field]) != len(resp_dict[field]) or any( + v != resp_dict[field][i] for i, v in enumerate(api_key_dict[field]) ): return False - elif api_key[field] != _resp[field]: + elif api_key_dict[field] != resp_dict[field]: return False return True elif operation == "add": diff --git a/templates/python/tests/client/suite.mustache b/templates/python/tests/client/suite.mustache index dbc96ded06..ba560ef411 100644 --- a/templates/python/tests/client/suite.mustache +++ b/templates/python/tests/client/suite.mustache @@ -53,7 +53,12 @@ class Test{{#lambda.pascalcase}}{{{client}}}{{/lambda.pascalcase}}: assert (_req if isinstance(_req, dict) else [elem.to_dict() for elem in _req] if isinstance(_req, list) else _req.to_dict()) == loads("""{{{match.parameters}}}""") {{/matchIsJSON}} {{^matchIsJSON}} + {{#matchIsNull}} + assert _req is None + {{/matchIsNull}} + {{^matchIsNull}} assert _req == """{{{match}}}""" + {{/matchIsNull}} {{/matchIsJSON}} {{/testResponse}} {{/match}} diff --git a/templates/ruby/search_helpers.mustache b/templates/ruby/search_helpers.mustache index 8c75feda16..e77843dfea 100644 --- a/templates/ruby/search_helpers.mustache +++ b/templates/ruby/search_helpers.mustache @@ -41,31 +41,27 @@ end # Helper: Wait for an API key to be added, updated or deleted based on a given `operation`. # -# @param operation [String] the `operation` that was done on a `key`. # @param key [String] the `key` that has been added, deleted or updated. +# @param operation [String] the `operation` that was done on a `key`. # @param api_key [Hash] necessary to know if an `update` operation has been processed, compare fields of the response with it. # @param max_retries [Integer] the maximum number of retries. # @param timeout [Proc] the function to decide how long to wait between retries. # @param request_options [Hash] the requestOptions to send along with the query, they will be forwarded to the `getApikey` method and merged with the transporter requestOptions. # @return [Http::Response] the last get_api_key response -def wait_for_api_key(operation, key, api_key = {}, max_retries = 50, timeout = -> (retry_count) { [retry_count * 200, 5000].min }, request_options = {}) +def wait_for_api_key(key, operation, api_key = {}, max_retries = 50, timeout = -> (retry_count) { [retry_count * 200, 5000].min }, request_options = {}) retries = 0 if operation == 'update' raise ArgumentError, '`api_key` is required when waiting for an `update` operation.' if api_key.nil? while retries < max_retries - begin - updatad_key = get_api_key(key, request_options) - updated_key_hash = updatad_key.to_hash - equals = true - api_key.to_hash.each do |k, v| - equals &&= updated_key_hash[k] == v - end - - return updatad_key if equals - rescue AlgoliaError => e - raise e unless e.code == 404 + updated_key = get_api_key(key, request_options) + updated_key_hash = updated_key.to_hash + equals = true + api_key.to_hash.each do |k, v| + equals &&= updated_key_hash[k] == v end + return updated_key if equals + retries += 1 sleep(timeout.call(retries) / 1000.0) end @@ -76,13 +72,19 @@ def wait_for_api_key(operation, key, api_key = {}, max_retries = 50, timeout = - while retries < max_retries begin res = get_api_key(key, request_options) - return res if operation == 'add' - rescue AlgoliaError => e - return res if operation == 'delete' && e.code == 404 + return res if operation == "add" + rescue AlgoliaHttpError => e + if e.code == 404 + return nil if operation == "delete" + else + raise e + end end + retries += 1 sleep(timeout.call(retries) / 1000.0) end + raise ApiError, "The maximum number of retries exceeded. (#{max_retries})" end diff --git a/templates/ruby/tests/client/suite.mustache b/templates/ruby/tests/client/suite.mustache index c06500e1aa..7577b2168f 100644 --- a/templates/ruby/tests/client/suite.mustache +++ b/templates/ruby/tests/client/suite.mustache @@ -43,7 +43,12 @@ class TestClient{{#lambda.pascalcase}}{{{client}}}{{/lambda.pascalcase}} < Test: assert_equal({{{match.parameters}}}, req.is_a?(Array) ? req.map(&:to_hash) : req.to_hash) {{/matchIsJSON}} {{^matchIsJSON}} + {{#matchIsNull}} + assert_nil(req) + {{/matchIsNull}} + {{^matchIsNull}} assert_equal('{{{match}}}', req) + {{/matchIsNull}} {{/matchIsJSON}} {{/testResponse}} {{/match}} diff --git a/templates/scala/tests/client/suite.mustache b/templates/scala/tests/client/suite.mustache index 55321e458f..5a52986840 100644 --- a/templates/scala/tests/client/suite.mustache +++ b/templates/scala/tests/client/suite.mustache @@ -73,7 +73,12 @@ class {{clientPrefix}}Test extends AnyFunSuite { assert(write(res) == "{{#lambda.escapeQuotes}}{{{match.parameters}}}{{/lambda.escapeQuotes}}") {{/matchIsJSON}} {{^matchIsJSON}} + {{#matchIsNull}} + assert(res == null) + {{/matchIsNull}} + {{^matchIsNull}} assert(res == "{{{match}}}") + {{/matchIsNull}} {{/matchIsJSON}} {{/testResponse}} {{/match}} diff --git a/templates/swift/tests/client/suite.mustache b/templates/swift/tests/client/suite.mustache index 67a2e6965c..196a02f22f 100644 --- a/templates/swift/tests/client/suite.mustache +++ b/templates/swift/tests/client/suite.mustache @@ -63,7 +63,12 @@ final class {{client}}ClientTests: XCTestCase { try XCTLenientAssertEqual(received: CodableHelper.jsonEncoder.encode(response), expected: comparableData) {{/matchIsJSON}} {{^matchIsJSON}} - XCTAssertEqual("{{#lambda.escapeQuotes}}{{{match}}}{{/lambda.escapeQuotes}}", response) + {{#matchIsNull}} + XCTAssertNil(response) + {{/matchIsNull}} + {{^matchIsNull}} + XCTAssertEqual("{{#lambda.escapeQuotes}}{{{match}}}{{/lambda.escapeQuotes}}", response) + {{/matchIsNull}} {{/matchIsJSON}} {{/isHelper}} {{^isHelper}} diff --git a/tests/CTS/client/search/helpers.json b/tests/CTS/client/search/helpers.json index 825ae6cd8d..f50c26719b 100644 --- a/tests/CTS/client/search/helpers.json +++ b/tests/CTS/client/search/helpers.json @@ -366,5 +366,151 @@ } } ] + }, + { + "testName": "wait for api key helper - add", + "autoCreateClient": false, + "steps": [ + { + "type": "createClient", + "parameters": { + "appId": "test-app-id", + "apiKey": "test-api-key", + "customHosts": [ + { + "host": "${{localhost}}", + "port": 6681 + } + ] + } + }, + { + "type": "method", + "object": "$client", + "path": "waitForApiKey", + "parameters": { + "key": "api-key-add-operation-test-${{languageCased}}", + "operation": "add" + }, + "expected": { + "type": "response", + "match": { + "value": "api-key-add-operation-test-${{languageCased}}", + "description": "my new api key", + "acl": [ + "search", + "addObject" + ], + "validity": 300, + "maxQueriesPerIPPerHour": 100, + "maxHitsPerQuery": 20, + "createdAt": 1720094400 + } + } + } + ] + }, + { + "testName": "wait for api key - update", + "autoCreateClient": false, + "steps": [ + { + "type": "createClient", + "parameters": { + "appId": "test-app-id", + "apiKey": "test-api-key", + "customHosts": [ + { + "host": "${{localhost}}", + "port": 6681 + } + ] + } + }, + { + "type": "method", + "object": "$client", + "path": "waitForApiKey", + "parameters": { + "key": "api-key-update-operation-test-${{languageCased}}", + "operation": "update", + "apiKey": { + "description": "my updated api key", + "acl": [ + "search", + "addObject", + "deleteObject" + ], + "indexes": [ + "Movies", + "Books" + ], + "referers": [ + "*google.com", + "*algolia.com" + ], + "validity": 305, + "maxQueriesPerIPPerHour": 95, + "maxHitsPerQuery": 20 + } + }, + "expected": { + "type": "response", + "match": { + "value": "api-key-update-operation-test-${{languageCased}}", + "description": "my updated api key", + "acl": [ + "search", + "addObject", + "deleteObject" + ], + "indexes": [ + "Movies", + "Books" + ], + "referers": [ + "*google.com", + "*algolia.com" + ], + "validity": 305, + "maxQueriesPerIPPerHour": 95, + "maxHitsPerQuery": 20, + "createdAt": 1720094400 + } + } + } + ] + }, + { + "testName": "wait for api key - delete", + "autoCreateClient": false, + "steps": [ + { + "type": "createClient", + "parameters": { + "appId": "test-app-id", + "apiKey": "test-api-key", + "customHosts": [ + { + "host": "${{localhost}}", + "port": 6681 + } + ] + } + }, + { + "type": "method", + "object": "$client", + "path": "waitForApiKey", + "parameters": { + "key": "api-key-delete-operation-test-${{languageCased}}", + "operation": "delete" + }, + "expected": { + "type": "response", + "match": null + } + } + ] } ] diff --git a/tests/output/csharp/src/ClientExtensionsTests.cs b/tests/output/csharp/src/ClientExtensionsTests.cs index 5363d4b3b0..9bc90732a8 100644 --- a/tests/output/csharp/src/ClientExtensionsTests.cs +++ b/tests/output/csharp/src/ClientExtensionsTests.cs @@ -79,57 +79,6 @@ public async Task ShouldWaitForTask() ); } - [Fact] - public async Task ShouldWaitForApiKey() - { - var httpMock = new Mock(); - var client = new SearchClient(new SearchConfig("test-app-id", "test-api-key"), httpMock.Object); - - httpMock - .SetupSequence(c => - c.SendRequestAsync( - It.Is(r => r.Uri.AbsolutePath.EndsWith("/1/keys/my-key")), - It.IsAny(), - It.IsAny(), - It.IsAny() - ) - ) - // First call throw an exception - .Throws(new AlgoliaApiException("Oupss", 0)) - // Next call return a 404 - .Returns(Task.FromResult(new AlgoliaHttpResponse { HttpStatusCode = 404 })) - // Third call return a Http 200 - .Returns( - Task.FromResult( - new AlgoliaHttpResponse - { - HttpStatusCode = 200, - Body = new MemoryStream( - Encoding.UTF8.GetBytes( - serializer.Serialize( - new GetApiKeyResponse() { CreatedAt = 12, Acl = new List() } - ) - ) - ) - } - ) - ); - - await client.WaitForApiKeyAsync(ApiKeyOperation.Add, "my-key"); - - // Verify that the request has been called three times - httpMock.Verify( - m => - m.SendRequestAsync( - It.Is(r => r.Uri.AbsolutePath.EndsWith("/1/keys/my-key")), - It.IsAny(), - It.IsAny(), - It.IsAny() - ), - Times.Exactly(3) - ); - } - [Fact] public async Task ShouldBrowseObjects() { diff --git a/tests/output/kotlin/src/commonTest/kotlin/com/algolia/utils/Assert.kt b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/utils/Assert.kt index b5c4c939b5..52116f1777 100644 --- a/tests/output/kotlin/src/commonTest/kotlin/com/algolia/utils/Assert.kt +++ b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/utils/Assert.kt @@ -59,7 +59,7 @@ fun assertJsonBody(json: String, body: Any) { /** * Compares two [JsonElement] instances for structural equality without considering the order of elements. */ -private fun areJsonElementsEqual(elem1: JsonElement?, elem2: JsonElement?): Boolean { +public fun areJsonElementsEqual(elem1: JsonElement?, elem2: JsonElement?): Boolean { return when { elem1 == null && elem2 == null -> true elem1 is JsonObject && elem2 is JsonObject -> { From 53be992657c4a63f9fbcc49504c2c9e272cfe578 Mon Sep 17 00:00:00 2001 From: algolia-bot Date: Thu, 18 Jul 2024 08:53:33 +0000 Subject: [PATCH 4/4] chore: generated code for commit a68907d1c4e8e64dcbc770832b64ddebc8ed7931. [skip ci] Co-authored-by: Thomas Raffray Co-authored-by: Pierre Millot --- .../java/com/algolia/api/SearchClient.java | 70 +++++------ .../client-search/src/searchClient.ts | 35 +++--- .../lib/Api/SearchClient.php | 8 +- .../lib/Support/Helpers.php | 2 +- .../algoliasearch/search/client.py | 27 ++-- .../lib/algolia/api/search_client.rb | 30 ++--- specs/bundled/search.yml | 12 +- .../src/generated/client/Search.test.cs | 107 ++++++++++++++++ tests/output/go/tests/client/search_test.go | 80 ++++++++++++ .../com/algolia/client/Abtesting.test.java | 6 +- .../com/algolia/client/Analytics.test.java | 6 +- .../com/algolia/client/Ingestion.test.java | 6 +- .../com/algolia/client/Insights.test.java | 6 +- .../com/algolia/client/Monitoring.test.java | 6 +- .../algolia/client/Personalization.test.java | 6 +- .../algolia/client/QuerySuggestions.test.java | 6 +- .../com/algolia/client/Recommend.test.java | 6 +- .../java/com/algolia/client/Search.test.java | 77 +++++++++++- .../java/com/algolia/client/Usage.test.java | 6 +- .../javascript/src/client/search.test.ts | 72 +++++++++++ .../kotlin/com/algolia/client/SearchTest.kt | 119 ++++++++++++++++-- tests/output/php/src/client/SearchTest.php | 64 ++++++++++ .../output/python/tests/client/search_test.py | 83 ++++++++++++ tests/output/ruby/test/client/search_test.rb | 99 +++++++++++++++ .../swift/Tests/client/SearchTests.swift | 76 +++++++++++ 25 files changed, 905 insertions(+), 110 deletions(-) diff --git a/clients/algoliasearch-client-java/algoliasearch/src/main/java/com/algolia/api/SearchClient.java b/clients/algoliasearch-client-java/algoliasearch/src/main/java/com/algolia/api/SearchClient.java index bf2bf9f922..8e4dfed1a0 100644 --- a/clients/algoliasearch-client-java/algoliasearch/src/main/java/com/algolia/api/SearchClient.java +++ b/clients/algoliasearch-client-java/algoliasearch/src/main/java/com/algolia/api/SearchClient.java @@ -5801,8 +5801,8 @@ public void waitForAppTask(Long taskID) { * the transporter requestOptions. (optional) */ public GetApiKeyResponse waitForApiKey( - ApiKeyOperation operation, String key, + ApiKeyOperation operation, ApiKey apiKey, int maxRetries, IntUnaryOperator timeout, @@ -5835,28 +5835,26 @@ public GetApiKeyResponse waitForApiKey( ); } - // bypass lambda restriction to modify final object - final GetApiKeyResponse[] addedKey = new GetApiKeyResponse[] { null }; - - // check the status of the getApiKey method - TaskUtils.retryUntil( + return TaskUtils.retryUntil( () -> { try { - addedKey[0] = this.getApiKey(key, requestOptions); - // magic number to signify we found the key - return -2; + return this.getApiKey(key, requestOptions); } catch (AlgoliaApiException e) { - return e.getStatusCode(); + if (e.getStatusCode() == 404) { + return null; + } + + throw e; } }, - (Integer status) -> { + (GetApiKeyResponse response) -> { switch (operation) { case ADD: - // stop either when the key is created or when we don't receive 404 - return status == -2 || status != 404; + // stop when we don't receive 404 meaning the key is created + return response != null; case DELETE: // stop when the key is not found - return status == 404; + return response == null; default: // continue return false; @@ -5865,15 +5863,13 @@ public GetApiKeyResponse waitForApiKey( maxRetries, timeout ); - - return addedKey[0]; } /** * Helper: Wait for an API key to be added or deleted based on a given `operation`. * - * @param operation The `operation` that was done on a `key`. (ADD or DELETE only) * @param key The `key` that has been added or deleted. + * @param operation The `operation` that was done on a `key`. (ADD or DELETE only) * @param maxRetries The maximum number of retry. 50 by default. (optional) * @param timeout The function to decide how long to wait between retries. min(retries * 200, * 5000) by default. (optional) @@ -5881,89 +5877,89 @@ public GetApiKeyResponse waitForApiKey( * the transporter requestOptions. (optional) */ public GetApiKeyResponse waitForApiKey( - ApiKeyOperation operation, String key, + ApiKeyOperation operation, int maxRetries, IntUnaryOperator timeout, RequestOptions requestOptions ) { - return this.waitForApiKey(operation, key, null, maxRetries, timeout, requestOptions); + return this.waitForApiKey(key, operation, null, maxRetries, timeout, requestOptions); } /** * Helper: Wait for an API key to be added, updated or deleted based on a given `operation`. * - * @param operation The `operation` that was done on a `key`. * @param key The `key` that has been added, deleted or updated. + * @param operation The `operation` that was done on a `key`. * @param apiKey Necessary to know if an `update` operation has been processed, compare fields of * the response with it. * @param requestOptions The requestOptions to send along with the query, they will be merged with * the transporter requestOptions. (optional) */ - public GetApiKeyResponse waitForApiKey(ApiKeyOperation operation, String key, ApiKey apiKey, RequestOptions requestOptions) { - return this.waitForApiKey(operation, key, apiKey, TaskUtils.DEFAULT_MAX_RETRIES, TaskUtils.DEFAULT_TIMEOUT, requestOptions); + public GetApiKeyResponse waitForApiKey(String key, ApiKeyOperation operation, ApiKey apiKey, RequestOptions requestOptions) { + return this.waitForApiKey(key, operation, apiKey, TaskUtils.DEFAULT_MAX_RETRIES, TaskUtils.DEFAULT_TIMEOUT, requestOptions); } /** * Helper: Wait for an API key to be added or deleted based on a given `operation`. * - * @param operation The `operation` that was done on a `key`. (ADD or DELETE only) * @param key The `key` that has been added or deleted. + * @param operation The `operation` that was done on a `key`. (ADD or DELETE only) * @param requestOptions The requestOptions to send along with the query, they will be merged with * the transporter requestOptions. (optional) */ - public GetApiKeyResponse waitForApiKey(ApiKeyOperation operation, String key, RequestOptions requestOptions) { - return this.waitForApiKey(operation, key, null, TaskUtils.DEFAULT_MAX_RETRIES, TaskUtils.DEFAULT_TIMEOUT, requestOptions); + public GetApiKeyResponse waitForApiKey(String key, ApiKeyOperation operation, RequestOptions requestOptions) { + return this.waitForApiKey(key, operation, null, TaskUtils.DEFAULT_MAX_RETRIES, TaskUtils.DEFAULT_TIMEOUT, requestOptions); } /** * Helper: Wait for an API key to be added, updated or deleted based on a given `operation`. * - * @param operation The `operation` that was done on a `key`. * @param key The `key` that has been added, deleted or updated. + * @param operation The `operation` that was done on a `key`. * @param apiKey Necessary to know if an `update` operation has been processed, compare fields of * the response with it. * @param maxRetries The maximum number of retry. 50 by default. (optional) * @param timeout The function to decide how long to wait between retries. min(retries * 200, * 5000) by default. (optional) */ - public GetApiKeyResponse waitForApiKey(ApiKeyOperation operation, String key, ApiKey apiKey, int maxRetries, IntUnaryOperator timeout) { - return this.waitForApiKey(operation, key, apiKey, maxRetries, timeout, null); + public GetApiKeyResponse waitForApiKey(String key, ApiKeyOperation operation, ApiKey apiKey, int maxRetries, IntUnaryOperator timeout) { + return this.waitForApiKey(key, operation, apiKey, maxRetries, timeout, null); } /** * Helper: Wait for an API key to be added or deleted based on a given `operation`. * - * @param operation The `operation` that was done on a `key`. (ADD or DELETE only) * @param key The `key` that has been added or deleted. + * @param operation The `operation` that was done on a `key`. (ADD or DELETE only) * @param maxRetries The maximum number of retry. 50 by default. (optional) * @param timeout The function to decide how long to wait between retries. min(retries * 200, * 5000) by default. (optional) */ - public GetApiKeyResponse waitForApiKey(ApiKeyOperation operation, String key, int maxRetries, IntUnaryOperator timeout) { - return this.waitForApiKey(operation, key, null, maxRetries, timeout, null); + public GetApiKeyResponse waitForApiKey(String key, ApiKeyOperation operation, int maxRetries, IntUnaryOperator timeout) { + return this.waitForApiKey(key, operation, null, maxRetries, timeout, null); } /** * Helper: Wait for an API key to be added, updated or deleted based on a given `operation`. * - * @param operation The `operation` that was done on a `key`. * @param key The `key` that has been added, deleted or updated. + * @param operation The `operation` that was done on a `key`. * @param apiKey Necessary to know if an `update` operation has been processed, compare fields of * the response with it. */ - public GetApiKeyResponse waitForApiKey(ApiKeyOperation operation, String key, ApiKey apiKey) { - return this.waitForApiKey(operation, key, apiKey, TaskUtils.DEFAULT_MAX_RETRIES, TaskUtils.DEFAULT_TIMEOUT, null); + public GetApiKeyResponse waitForApiKey(String key, ApiKeyOperation operation, ApiKey apiKey) { + return this.waitForApiKey(key, operation, apiKey, TaskUtils.DEFAULT_MAX_RETRIES, TaskUtils.DEFAULT_TIMEOUT, null); } /** * Helper: Wait for an API key to be added or deleted based on a given `operation`. * - * @param operation The `operation` that was done on a `key`. (ADD or DELETE only) * @param key The `key` that has been added or deleted. + * @param operation The `operation` that was done on a `key`. (ADD or DELETE only) */ - public GetApiKeyResponse waitForApiKey(ApiKeyOperation operation, String key) { - return this.waitForApiKey(operation, key, null, TaskUtils.DEFAULT_MAX_RETRIES, TaskUtils.DEFAULT_TIMEOUT, null); + public GetApiKeyResponse waitForApiKey(String key, ApiKeyOperation operation) { + return this.waitForApiKey(key, operation, null, TaskUtils.DEFAULT_MAX_RETRIES, TaskUtils.DEFAULT_TIMEOUT, null); } /** diff --git a/clients/algoliasearch-client-javascript/packages/client-search/src/searchClient.ts b/clients/algoliasearch-client-javascript/packages/client-search/src/searchClient.ts index 8396c23a4a..1210f50512 100644 --- a/clients/algoliasearch-client-javascript/packages/client-search/src/searchClient.ts +++ b/clients/algoliasearch-client-javascript/packages/client-search/src/searchClient.ts @@ -320,18 +320,19 @@ export function createSearchClient({ Math.min(retryCount * 200, 5000), }: WaitForApiKeyOptions, requestOptions?: RequestOptions - ): Promise { + ): Promise { let retryCount = 0; - const baseIteratorOptions: IterableOptions = - { - aggregator: () => (retryCount += 1), - error: { - validate: () => retryCount >= maxRetries, - message: () => - `The maximum number of retries exceeded. (${retryCount}/${maxRetries})`, - }, - timeout: () => timeout(retryCount), - }; + const baseIteratorOptions: IterableOptions< + GetApiKeyResponse | undefined + > = { + aggregator: () => (retryCount += 1), + error: { + validate: () => retryCount >= maxRetries, + message: () => + `The maximum number of retries exceeded. (${retryCount}/${maxRetries})`, + }, + timeout: () => timeout(retryCount), + }; if (operation === 'update') { if (!apiKey) { @@ -366,9 +367,15 @@ export function createSearchClient({ return createIterablePromise({ ...baseIteratorOptions, func: () => - this.getApiKey({ key }, requestOptions).catch((error) => error), - validate: (error: ApiError) => - operation === 'add' ? error.status !== 404 : error.status === 404, + this.getApiKey({ key }, requestOptions).catch((error: ApiError) => { + if (error.status === 404) { + return undefined; + } + + throw error; + }), + validate: (response) => + operation === 'add' ? response !== undefined : response === undefined, }); }, diff --git a/clients/algoliasearch-client-php/lib/Api/SearchClient.php b/clients/algoliasearch-client-php/lib/Api/SearchClient.php index c649bdd6c9..9d52b25d27 100644 --- a/clients/algoliasearch-client-php/lib/Api/SearchClient.php +++ b/clients/algoliasearch-client-php/lib/Api/SearchClient.php @@ -2817,8 +2817,8 @@ function ($res) {return 'published' === $res['status']; }, /** * Wait for an API key to be added, updated or deleted based on a given `operation`. * - * @param string $operation the `operation` that was done on a `key` * @param string $key the `key` that has been added, deleted or updated + * @param string $operation the `operation` that was done on a `key` * @param array $apiKey necessary to know if an `update` operation has been processed, compare fields of the response with it * @param null|int $maxRetries Maximum number of retries * @param null|int $timeout Timeout @@ -2827,8 +2827,8 @@ function ($res) {return 'published' === $res['status']; }, * @throws ExceededRetriesException */ public function waitForApiKey( - $operation, $key, + $operation, $apiKey = null, $maxRetries = null, $timeout = null, @@ -2842,14 +2842,14 @@ public function waitForApiKey( $maxRetries = $this->config->getDefaultMaxRetries(); } - Helpers::retryForApiKeyUntil( + return Helpers::retryForApiKeyUntil( $operation, $this, $key, $apiKey, $maxRetries, $timeout, - null, + 'Algolia\AlgoliaSearch\Support\Helpers::linearTimeout', $requestOptions ); } diff --git a/clients/algoliasearch-client-php/lib/Support/Helpers.php b/clients/algoliasearch-client-php/lib/Support/Helpers.php index 7f48f9d8ee..7b0b22f065 100644 --- a/clients/algoliasearch-client-php/lib/Support/Helpers.php +++ b/clients/algoliasearch-client-php/lib/Support/Helpers.php @@ -166,7 +166,7 @@ public static function retryForApiKeyUntil( // In case of a deletion, if there was an error, the $key has been deleted as it should be if ( 'delete' === $operation - && $e->getCode() === 404 + && 404 === $e->getCode() ) { return null; } diff --git a/clients/algoliasearch-client-python/algoliasearch/search/client.py b/clients/algoliasearch-client-python/algoliasearch/search/client.py index 3babe725a3..26e10858d9 100644 --- a/clients/algoliasearch-client-python/algoliasearch/search/client.py +++ b/clients/algoliasearch-client-python/algoliasearch/search/client.py @@ -254,13 +254,13 @@ def _aggregator(_: GetTaskResponse) -> None: async def wait_for_api_key( self, - operation: str, key: str, + operation: str, api_key: Optional[ApiKey] = None, max_retries: int = 50, timeout: RetryTimeout = RetryTimeout(), request_options: Optional[Union[dict, RequestOptions]] = None, - ) -> GetApiKeyResponse: + ) -> GetApiKeyResponse | None: """ Helper: Wait for an API key to be added, updated or deleted based on a given `operation`. """ @@ -271,7 +271,7 @@ async def wait_for_api_key( "`apiKey` is required when waiting for an `update` operation." ) - async def _func(_prev: GetApiKeyResponse) -> GetApiKeyResponse: + async def _func(_prev: GetApiKeyResponse | None) -> GetApiKeyResponse | None: try: return await self.get_api_key(key=key, request_options=request_options) except RequestException as e: @@ -281,20 +281,25 @@ async def _func(_prev: GetApiKeyResponse) -> GetApiKeyResponse: return None raise e - def _aggregator(_: GetApiKeyResponse) -> None: + def _aggregator(_: GetApiKeyResponse | None) -> None: self._retry_count += 1 - def _validate(_resp: GetApiKeyResponse) -> bool: + def _validate(_resp: GetApiKeyResponse | None) -> bool: if operation == "update": - for field in api_key: - if isinstance(api_key[field], list) and isinstance( - _resp[field], list + resp_dict = _resp.to_dict() + api_key_dict = ( + api_key.to_dict() if isinstance(api_key, ApiKey) else api_key + ) + for field in api_key_dict: + if isinstance(api_key_dict[field], list) and isinstance( + resp_dict[field], list ): - if len(api_key[field]) != len(_resp[field]) or any( - v != _resp[field][i] for i, v in enumerate(api_key[field]) + if len(api_key_dict[field]) != len(resp_dict[field]) or any( + v != resp_dict[field][i] + for i, v in enumerate(api_key_dict[field]) ): return False - elif api_key[field] != _resp[field]: + elif api_key_dict[field] != resp_dict[field]: return False return True elif operation == "add": diff --git a/clients/algoliasearch-client-ruby/lib/algolia/api/search_client.rb b/clients/algoliasearch-client-ruby/lib/algolia/api/search_client.rb index 3b9a2e95d5..145f9eb559 100644 --- a/clients/algoliasearch-client-ruby/lib/algolia/api/search_client.rb +++ b/clients/algoliasearch-client-ruby/lib/algolia/api/search_client.rb @@ -3179,16 +3179,16 @@ def wait_for_app_task( # Helper: Wait for an API key to be added, updated or deleted based on a given `operation`. # - # @param operation [String] the `operation` that was done on a `key`. # @param key [String] the `key` that has been added, deleted or updated. + # @param operation [String] the `operation` that was done on a `key`. # @param api_key [Hash] necessary to know if an `update` operation has been processed, compare fields of the response with it. # @param max_retries [Integer] the maximum number of retries. # @param timeout [Proc] the function to decide how long to wait between retries. # @param request_options [Hash] the requestOptions to send along with the query, they will be forwarded to the `getApikey` method and merged with the transporter requestOptions. # @return [Http::Response] the last get_api_key response def wait_for_api_key( - operation, key, + operation, api_key = {}, max_retries = 50, timeout = -> (retry_count) { [retry_count * 200, 5000].min }, @@ -3198,19 +3198,15 @@ def wait_for_api_key( if operation == "update" raise ArgumentError, "`api_key` is required when waiting for an `update` operation." if api_key.nil? while retries < max_retries - begin - updatad_key = get_api_key(key, request_options) - updated_key_hash = updatad_key.to_hash - equals = true - api_key.to_hash.each do |k, v| - equals &&= updated_key_hash[k] == v - end - - return updatad_key if equals - rescue AlgoliaError => e - raise e unless e.code == 404 + updated_key = get_api_key(key, request_options) + updated_key_hash = updated_key.to_hash + equals = true + api_key.to_hash.each do |k, v| + equals &&= updated_key_hash[k] == v end + return updated_key if equals + retries += 1 sleep(timeout.call(retries) / 1000.0) end @@ -3222,8 +3218,12 @@ def wait_for_api_key( begin res = get_api_key(key, request_options) return res if operation == "add" - rescue AlgoliaError => e - return res if operation == "delete" && e.code == 404 + rescue AlgoliaHttpError => e + if e.code == 404 + return nil if operation == "delete" + else + raise e + end end retries += 1 diff --git a/specs/bundled/search.yml b/specs/bundled/search.yml index 00414d1235..38a0e38236 100644 --- a/specs/bundled/search.yml +++ b/specs/bundled/search.yml @@ -3174,18 +3174,18 @@ paths: summary: Wait for an API key operation description: Waits for an API key to be added, updated, or deleted. parameters: - - in: query - name: operation - description: Whether the API key was created, updated, or deleted. - required: true - schema: - $ref: '#/components/schemas/apiKeyOperation' - in: query name: key description: API key to wait for. required: true schema: type: string + - in: query + name: operation + description: Whether the API key was created, updated, or deleted. + required: true + schema: + $ref: '#/components/schemas/apiKeyOperation' - in: query name: apiKey description: >- diff --git a/tests/output/csharp/src/generated/client/Search.test.cs b/tests/output/csharp/src/generated/client/Search.test.cs index 6ad805a2a7..ac7075b053 100644 --- a/tests/output/csharp/src/generated/client/Search.test.cs +++ b/tests/output/csharp/src/generated/client/Search.test.cs @@ -400,6 +400,113 @@ public async Task HelpersTest6() ); } + [Fact(DisplayName = "wait for api key helper - add")] + public async Task HelpersTest7() + { + SearchConfig _config = new SearchConfig("test-app-id", "test-api-key") + { + CustomHosts = new List + { + new() + { + Scheme = HttpScheme.Http, + Url = "localhost", + Port = 6681, + Up = true, + LastUse = DateTime.UtcNow, + Accept = CallType.Read | CallType.Write, + } + } + }; + var client = new SearchClient(_config); + + var res = await client.WaitForApiKeyAsync( + "api-key-add-operation-test-Csharp", + Enum.Parse("Add") + ); + + JsonAssert.EqualOverrideDefault( + "{\"value\":\"api-key-add-operation-test-Csharp\",\"description\":\"my new api key\",\"acl\":[\"search\",\"addObject\"],\"validity\":300,\"maxQueriesPerIPPerHour\":100,\"maxHitsPerQuery\":20,\"createdAt\":1720094400}", + JsonSerializer.Serialize(res, JsonConfig.Options), + new JsonDiffConfig(false) + ); + } + + [Fact(DisplayName = "wait for api key - update")] + public async Task HelpersTest8() + { + SearchConfig _config = new SearchConfig("test-app-id", "test-api-key") + { + CustomHosts = new List + { + new() + { + Scheme = HttpScheme.Http, + Url = "localhost", + Port = 6681, + Up = true, + LastUse = DateTime.UtcNow, + Accept = CallType.Read | CallType.Write, + } + } + }; + var client = new SearchClient(_config); + + var res = await client.WaitForApiKeyAsync( + "api-key-update-operation-test-Csharp", + Enum.Parse("Update"), + new ApiKey + { + Description = "my updated api key", + Acl = new List + { + Enum.Parse("Search"), + Enum.Parse("AddObject"), + Enum.Parse("DeleteObject") + }, + Indexes = new List { "Movies", "Books" }, + Referers = new List { "*google.com", "*algolia.com" }, + Validity = 305, + MaxQueriesPerIPPerHour = 95, + MaxHitsPerQuery = 20, + } + ); + + JsonAssert.EqualOverrideDefault( + "{\"value\":\"api-key-update-operation-test-Csharp\",\"description\":\"my updated api key\",\"acl\":[\"search\",\"addObject\",\"deleteObject\"],\"indexes\":[\"Movies\",\"Books\"],\"referers\":[\"*google.com\",\"*algolia.com\"],\"validity\":305,\"maxQueriesPerIPPerHour\":95,\"maxHitsPerQuery\":20,\"createdAt\":1720094400}", + JsonSerializer.Serialize(res, JsonConfig.Options), + new JsonDiffConfig(false) + ); + } + + [Fact(DisplayName = "wait for api key - delete")] + public async Task HelpersTest9() + { + SearchConfig _config = new SearchConfig("test-app-id", "test-api-key") + { + CustomHosts = new List + { + new() + { + Scheme = HttpScheme.Http, + Url = "localhost", + Port = 6681, + Up = true, + LastUse = DateTime.UtcNow, + Accept = CallType.Read | CallType.Write, + } + } + }; + var client = new SearchClient(_config); + + var res = await client.WaitForApiKeyAsync( + "api-key-delete-operation-test-Csharp", + Enum.Parse("Delete") + ); + + Assert.Null(res); + } + [Fact(DisplayName = "client throws with invalid parameters")] public async Task ParametersTest0() { diff --git a/tests/output/go/tests/client/search_test.go b/tests/output/go/tests/client/search_test.go index 51af4b51ef..79589f5b41 100644 --- a/tests/output/go/tests/client/search_test.go +++ b/tests/output/go/tests/client/search_test.go @@ -335,6 +335,86 @@ func TestSearchhelpers6(t *testing.T) { require.JSONEq(t, `[{"taskID":666,"objectIDs":["1","2"]}]`, string(rawBody)) } +// wait for api key helper - add +func TestSearchhelpers7(t *testing.T) { + var err error + echo := &tests.EchoRequester{} + var client *search.APIClient + var cfg search.SearchConfiguration + _ = client + _ = echo + cfg = search.SearchConfiguration{ + Configuration: transport.Configuration{ + AppID: "test-app-id", + ApiKey: "test-api-key", + Hosts: []transport.StatefulHost{transport.NewStatefulHost("http", "localhost:6681", call.IsReadWrite)}, + }, + } + client, err = search.NewClientWithConfig(cfg) + require.NoError(t, err) + res, err := client.WaitForApiKey( + "api-key-add-operation-test-Go", search.ApiKeyOperation("add"), + ) + require.NoError(t, err) + rawBody, err := json.Marshal(res) + require.NoError(t, err) + require.JSONEq(t, `{"value":"api-key-add-operation-test-Go","description":"my new api key","acl":["search","addObject"],"validity":300,"maxQueriesPerIPPerHour":100,"maxHitsPerQuery":20,"createdAt":1720094400}`, string(rawBody)) +} + +// wait for api key - update +func TestSearchhelpers8(t *testing.T) { + var err error + echo := &tests.EchoRequester{} + var client *search.APIClient + var cfg search.SearchConfiguration + _ = client + _ = echo + cfg = search.SearchConfiguration{ + Configuration: transport.Configuration{ + AppID: "test-app-id", + ApiKey: "test-api-key", + Hosts: []transport.StatefulHost{transport.NewStatefulHost("http", "localhost:6681", call.IsReadWrite)}, + }, + } + client, err = search.NewClientWithConfig(cfg) + require.NoError(t, err) + res, err := client.WaitForApiKey( + "api-key-update-operation-test-Go", search.ApiKeyOperation("update"), + search.WithApiKey( + search.NewEmptyApiKey().SetDescription("my updated api key").SetAcl( + []search.Acl{search.Acl("search"), search.Acl("addObject"), search.Acl("deleteObject")}).SetIndexes( + []string{"Movies", "Books"}).SetReferers( + []string{"*google.com", "*algolia.com"}).SetValidity(305).SetMaxQueriesPerIPPerHour(95).SetMaxHitsPerQuery(20))) + require.NoError(t, err) + rawBody, err := json.Marshal(res) + require.NoError(t, err) + require.JSONEq(t, `{"value":"api-key-update-operation-test-Go","description":"my updated api key","acl":["search","addObject","deleteObject"],"indexes":["Movies","Books"],"referers":["*google.com","*algolia.com"],"validity":305,"maxQueriesPerIPPerHour":95,"maxHitsPerQuery":20,"createdAt":1720094400}`, string(rawBody)) +} + +// wait for api key - delete +func TestSearchhelpers9(t *testing.T) { + var err error + echo := &tests.EchoRequester{} + var client *search.APIClient + var cfg search.SearchConfiguration + _ = client + _ = echo + cfg = search.SearchConfiguration{ + Configuration: transport.Configuration{ + AppID: "test-app-id", + ApiKey: "test-api-key", + Hosts: []transport.StatefulHost{transport.NewStatefulHost("http", "localhost:6681", call.IsReadWrite)}, + }, + } + client, err = search.NewClientWithConfig(cfg) + require.NoError(t, err) + res, err := client.WaitForApiKey( + "api-key-delete-operation-test-Go", search.ApiKeyOperation("delete"), + ) + require.NoError(t, err) + require.Nil(t, res) +} + // client throws with invalid parameters func TestSearchparameters0(t *testing.T) { var err error diff --git a/tests/output/java/src/test/java/com/algolia/client/Abtesting.test.java b/tests/output/java/src/test/java/com/algolia/client/Abtesting.test.java index 7e9bba122a..d00feb78aa 100644 --- a/tests/output/java/src/test/java/com/algolia/client/Abtesting.test.java +++ b/tests/output/java/src/test/java/com/algolia/client/Abtesting.test.java @@ -9,6 +9,7 @@ import com.algolia.api.AbtestingClient; import com.algolia.config.*; import com.algolia.model.abtesting.*; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.json.JsonMapper; @@ -26,7 +27,10 @@ class AbtestingClientClientTests { @BeforeAll void init() { - this.json = JsonMapper.builder().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).build(); + this.json = JsonMapper.builder() + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .serializationInclusion(JsonInclude.Include.NON_NULL) + .build(); } AbtestingClient createClient() { diff --git a/tests/output/java/src/test/java/com/algolia/client/Analytics.test.java b/tests/output/java/src/test/java/com/algolia/client/Analytics.test.java index 022ba3b81d..110274a234 100644 --- a/tests/output/java/src/test/java/com/algolia/client/Analytics.test.java +++ b/tests/output/java/src/test/java/com/algolia/client/Analytics.test.java @@ -9,6 +9,7 @@ import com.algolia.api.AnalyticsClient; import com.algolia.config.*; import com.algolia.model.analytics.*; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.json.JsonMapper; @@ -26,7 +27,10 @@ class AnalyticsClientClientTests { @BeforeAll void init() { - this.json = JsonMapper.builder().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).build(); + this.json = JsonMapper.builder() + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .serializationInclusion(JsonInclude.Include.NON_NULL) + .build(); } AnalyticsClient createClient() { diff --git a/tests/output/java/src/test/java/com/algolia/client/Ingestion.test.java b/tests/output/java/src/test/java/com/algolia/client/Ingestion.test.java index e86b4fbcec..c422b0672e 100644 --- a/tests/output/java/src/test/java/com/algolia/client/Ingestion.test.java +++ b/tests/output/java/src/test/java/com/algolia/client/Ingestion.test.java @@ -9,6 +9,7 @@ import com.algolia.api.IngestionClient; import com.algolia.config.*; import com.algolia.model.ingestion.*; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.json.JsonMapper; @@ -26,7 +27,10 @@ class IngestionClientClientTests { @BeforeAll void init() { - this.json = JsonMapper.builder().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).build(); + this.json = JsonMapper.builder() + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .serializationInclusion(JsonInclude.Include.NON_NULL) + .build(); } IngestionClient createClient() { diff --git a/tests/output/java/src/test/java/com/algolia/client/Insights.test.java b/tests/output/java/src/test/java/com/algolia/client/Insights.test.java index fe14520d3a..c8668eeabf 100644 --- a/tests/output/java/src/test/java/com/algolia/client/Insights.test.java +++ b/tests/output/java/src/test/java/com/algolia/client/Insights.test.java @@ -9,6 +9,7 @@ import com.algolia.api.InsightsClient; import com.algolia.config.*; import com.algolia.model.insights.*; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.json.JsonMapper; @@ -26,7 +27,10 @@ class InsightsClientClientTests { @BeforeAll void init() { - this.json = JsonMapper.builder().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).build(); + this.json = JsonMapper.builder() + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .serializationInclusion(JsonInclude.Include.NON_NULL) + .build(); } InsightsClient createClient() { diff --git a/tests/output/java/src/test/java/com/algolia/client/Monitoring.test.java b/tests/output/java/src/test/java/com/algolia/client/Monitoring.test.java index 9fa57b4e88..226c79a3a1 100644 --- a/tests/output/java/src/test/java/com/algolia/client/Monitoring.test.java +++ b/tests/output/java/src/test/java/com/algolia/client/Monitoring.test.java @@ -8,6 +8,7 @@ import com.algolia.api.MonitoringClient; import com.algolia.config.*; import com.algolia.model.monitoring.*; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.json.JsonMapper; @@ -25,7 +26,10 @@ class MonitoringClientClientTests { @BeforeAll void init() { - this.json = JsonMapper.builder().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).build(); + this.json = JsonMapper.builder() + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .serializationInclusion(JsonInclude.Include.NON_NULL) + .build(); } MonitoringClient createClient() { diff --git a/tests/output/java/src/test/java/com/algolia/client/Personalization.test.java b/tests/output/java/src/test/java/com/algolia/client/Personalization.test.java index e75c28339f..9bfe4711f1 100644 --- a/tests/output/java/src/test/java/com/algolia/client/Personalization.test.java +++ b/tests/output/java/src/test/java/com/algolia/client/Personalization.test.java @@ -9,6 +9,7 @@ import com.algolia.api.PersonalizationClient; import com.algolia.config.*; import com.algolia.model.personalization.*; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.json.JsonMapper; @@ -26,7 +27,10 @@ class PersonalizationClientClientTests { @BeforeAll void init() { - this.json = JsonMapper.builder().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).build(); + this.json = JsonMapper.builder() + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .serializationInclusion(JsonInclude.Include.NON_NULL) + .build(); } PersonalizationClient createClient() { diff --git a/tests/output/java/src/test/java/com/algolia/client/QuerySuggestions.test.java b/tests/output/java/src/test/java/com/algolia/client/QuerySuggestions.test.java index 3b1a5cd165..920d1eb26b 100644 --- a/tests/output/java/src/test/java/com/algolia/client/QuerySuggestions.test.java +++ b/tests/output/java/src/test/java/com/algolia/client/QuerySuggestions.test.java @@ -9,6 +9,7 @@ import com.algolia.api.QuerySuggestionsClient; import com.algolia.config.*; import com.algolia.model.querysuggestions.*; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.json.JsonMapper; @@ -26,7 +27,10 @@ class QuerySuggestionsClientClientTests { @BeforeAll void init() { - this.json = JsonMapper.builder().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).build(); + this.json = JsonMapper.builder() + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .serializationInclusion(JsonInclude.Include.NON_NULL) + .build(); } QuerySuggestionsClient createClient() { diff --git a/tests/output/java/src/test/java/com/algolia/client/Recommend.test.java b/tests/output/java/src/test/java/com/algolia/client/Recommend.test.java index 0b5000ec3e..77f6f437f8 100644 --- a/tests/output/java/src/test/java/com/algolia/client/Recommend.test.java +++ b/tests/output/java/src/test/java/com/algolia/client/Recommend.test.java @@ -8,6 +8,7 @@ import com.algolia.api.RecommendClient; import com.algolia.config.*; import com.algolia.model.recommend.*; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.json.JsonMapper; @@ -25,7 +26,10 @@ class RecommendClientClientTests { @BeforeAll void init() { - this.json = JsonMapper.builder().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).build(); + this.json = JsonMapper.builder() + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .serializationInclusion(JsonInclude.Include.NON_NULL) + .build(); } RecommendClient createClient() { diff --git a/tests/output/java/src/test/java/com/algolia/client/Search.test.java b/tests/output/java/src/test/java/com/algolia/client/Search.test.java index a5519b85e0..0ed9093629 100644 --- a/tests/output/java/src/test/java/com/algolia/client/Search.test.java +++ b/tests/output/java/src/test/java/com/algolia/client/Search.test.java @@ -10,6 +10,7 @@ import com.algolia.api.SearchClient; import com.algolia.config.*; import com.algolia.model.search.*; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.json.JsonMapper; @@ -29,7 +30,10 @@ class SearchClientClientTests { @BeforeAll void init() { - this.json = JsonMapper.builder().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).build(); + this.json = JsonMapper.builder() + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .serializationInclusion(JsonInclude.Include.NON_NULL) + .build(); } SearchClient createClient() { @@ -314,6 +318,77 @@ void helpersTest6() { }); } + @Test + @DisplayName("wait for api key helper - add") + void helpersTest7() { + assertDoesNotThrow(() -> { + SearchClient client = new SearchClient( + "test-app-id", + "test-api-key", + withCustomHosts(Arrays.asList(new Host("localhost", EnumSet.of(CallType.READ, CallType.WRITE), "http", 6681)), false) + ); + var res = client.waitForApiKey("api-key-add-operation-test-Java", ApiKeyOperation.ADD); + + assertDoesNotThrow(() -> + JSONAssert.assertEquals( + "{\"value\":\"api-key-add-operation-test-Java\",\"description\":\"my new api" + + " key\",\"acl\":[\"search\",\"addObject\"],\"validity\":300,\"maxQueriesPerIPPerHour\":100,\"maxHitsPerQuery\":20,\"createdAt\":1720094400}", + json.writeValueAsString(res), + JSONCompareMode.STRICT + ) + ); + }); + } + + @Test + @DisplayName("wait for api key - update") + void helpersTest8() { + assertDoesNotThrow(() -> { + SearchClient client = new SearchClient( + "test-app-id", + "test-api-key", + withCustomHosts(Arrays.asList(new Host("localhost", EnumSet.of(CallType.READ, CallType.WRITE), "http", 6681)), false) + ); + var res = client.waitForApiKey( + "api-key-update-operation-test-Java", + ApiKeyOperation.UPDATE, + new ApiKey() + .setDescription("my updated api key") + .setAcl(List.of(Acl.SEARCH, Acl.ADD_OBJECT, Acl.DELETE_OBJECT)) + .setIndexes(List.of("Movies", "Books")) + .setReferers(List.of("*google.com", "*algolia.com")) + .setValidity(305) + .setMaxQueriesPerIPPerHour(95) + .setMaxHitsPerQuery(20) + ); + + assertDoesNotThrow(() -> + JSONAssert.assertEquals( + "{\"value\":\"api-key-update-operation-test-Java\",\"description\":\"my" + + " updated api" + + " key\",\"acl\":[\"search\",\"addObject\",\"deleteObject\"],\"indexes\":[\"Movies\",\"Books\"],\"referers\":[\"*google.com\",\"*algolia.com\"],\"validity\":305,\"maxQueriesPerIPPerHour\":95,\"maxHitsPerQuery\":20,\"createdAt\":1720094400}", + json.writeValueAsString(res), + JSONCompareMode.STRICT + ) + ); + }); + } + + @Test + @DisplayName("wait for api key - delete") + void helpersTest9() { + assertDoesNotThrow(() -> { + SearchClient client = new SearchClient( + "test-app-id", + "test-api-key", + withCustomHosts(Arrays.asList(new Host("localhost", EnumSet.of(CallType.READ, CallType.WRITE), "http", 6681)), false) + ); + var res = client.waitForApiKey("api-key-delete-operation-test-Java", ApiKeyOperation.DELETE); + + assertEquals(null, res); + }); + } + @Test @DisplayName("client throws with invalid parameters") void parametersTest0() { diff --git a/tests/output/java/src/test/java/com/algolia/client/Usage.test.java b/tests/output/java/src/test/java/com/algolia/client/Usage.test.java index ade38bd8ce..09783648d6 100644 --- a/tests/output/java/src/test/java/com/algolia/client/Usage.test.java +++ b/tests/output/java/src/test/java/com/algolia/client/Usage.test.java @@ -9,6 +9,7 @@ import com.algolia.api.UsageClient; import com.algolia.config.*; import com.algolia.model.usage.*; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.json.JsonMapper; @@ -26,7 +27,10 @@ class UsageClientClientTests { @BeforeAll void init() { - this.json = JsonMapper.builder().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).build(); + this.json = JsonMapper.builder() + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .serializationInclusion(JsonInclude.Include.NON_NULL) + .build(); } UsageClient createClient() { diff --git a/tests/output/javascript/src/client/search.test.ts b/tests/output/javascript/src/client/search.test.ts index 3a263c549b..2b487983a8 100644 --- a/tests/output/javascript/src/client/search.test.ts +++ b/tests/output/javascript/src/client/search.test.ts @@ -244,6 +244,78 @@ describe('helpers', () => { expect(result).toEqual([{ taskID: 666, objectIDs: ['1', '2'] }]); }, 15000); + + test('wait for api key helper - add', async () => { + const $client = searchClient('test-app-id', 'test-api-key', { + hosts: [ + { url: 'localhost', port: 6681, accept: 'readWrite', protocol: 'http' }, + ], + }); + + const result = await $client.waitForApiKey({ + key: 'api-key-add-operation-test-JavaScript', + operation: 'add', + }); + + expect(result).toEqual({ + value: 'api-key-add-operation-test-JavaScript', + description: 'my new api key', + acl: ['search', 'addObject'], + validity: 300, + maxQueriesPerIPPerHour: 100, + maxHitsPerQuery: 20, + createdAt: 1720094400, + }); + }, 15000); + + test('wait for api key - update', async () => { + const $client = searchClient('test-app-id', 'test-api-key', { + hosts: [ + { url: 'localhost', port: 6681, accept: 'readWrite', protocol: 'http' }, + ], + }); + + const result = await $client.waitForApiKey({ + key: 'api-key-update-operation-test-JavaScript', + operation: 'update', + apiKey: { + description: 'my updated api key', + acl: ['search', 'addObject', 'deleteObject'], + indexes: ['Movies', 'Books'], + referers: ['*google.com', '*algolia.com'], + validity: 305, + maxQueriesPerIPPerHour: 95, + maxHitsPerQuery: 20, + }, + }); + + expect(result).toEqual({ + value: 'api-key-update-operation-test-JavaScript', + description: 'my updated api key', + acl: ['search', 'addObject', 'deleteObject'], + indexes: ['Movies', 'Books'], + referers: ['*google.com', '*algolia.com'], + validity: 305, + maxQueriesPerIPPerHour: 95, + maxHitsPerQuery: 20, + createdAt: 1720094400, + }); + }, 15000); + + test('wait for api key - delete', async () => { + const $client = searchClient('test-app-id', 'test-api-key', { + hosts: [ + { url: 'localhost', port: 6681, accept: 'readWrite', protocol: 'http' }, + ], + }); + + const result = await $client.waitForApiKey({ + key: 'api-key-delete-operation-test-JavaScript', + operation: 'delete', + }); + + expect(result).toBeUndefined(); + }, 15000); }); describe('parameters', () => { diff --git a/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/SearchTest.kt b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/SearchTest.kt index 4cdd4a3892..384f024342 100644 --- a/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/SearchTest.kt +++ b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/SearchTest.kt @@ -54,6 +54,7 @@ class SearchTest { path = "1/test/retry/Kotlin", ) }, + response = { val response = Json.encodeToString(it) assertEquals("{\"message\":\"ok test server response\"}", response) @@ -77,6 +78,7 @@ class SearchTest { }, ) }, + response = { val response = Json.encodeToString(it) assertEquals("{\"message\":\"ok compression test server response\",\"body\":{\"message\":\"this is a compressed body\"}}", response) @@ -146,9 +148,11 @@ class SearchTest { ), ) }, + response = { - assertEquals("NjFhZmE0OGEyMTI3OThiODc0OTlkOGM0YjcxYzljY2M2NmU2NDE5ZWY0NDZjMWJhNjA2NzBkMjAwOTI2YWQyZnJlc3RyaWN0SW5kaWNlcz1Nb3ZpZXMmdmFsaWRVbnRpbD0yNTI0NjA0NDAw", it) + assertEquals("""NjFhZmE0OGEyMTI3OThiODc0OTlkOGM0YjcxYzljY2M2NmU2NDE5ZWY0NDZjMWJhNjA2NzBkMjAwOTI2YWQyZnJlc3RyaWN0SW5kaWNlcz1Nb3ZpZXMmdmFsaWRVbnRpbD0yNTI0NjA0NDAw""", it) }, + ) } @@ -176,9 +180,11 @@ class SearchTest { ), ) }, + response = { - assertEquals("MzAxMDUwYjYyODMxODQ3ZWM1ZDYzNTkxZmNjNDg2OGZjMjAzYjQyOTZhMGQ1NDJhMDFiNGMzYTYzODRhNmMxZWFyb3VuZFJhZGl1cz1hbGwmZmlsdGVycz1jYXRlZ29yeSUzQUJvb2slMjBPUiUyMGNhdGVnb3J5JTNBRWJvb2slMjBBTkQlMjBfdGFncyUzQXB1Ymxpc2hlZCZoaXRzUGVyUGFnZT0xMCZtb2RlPW5ldXJhbFNlYXJjaCZvcHRpb25hbFdvcmRzPW9uZSUyQ3R3byZxdWVyeT1iYXRtYW4mcmVzdHJpY3RJbmRpY2VzPU1vdmllcyUyQ2N0c19lMmVfc2V0dGluZ3MmcmVzdHJpY3RTb3VyY2VzPTE5Mi4xNjguMS4wJTJGMjQmdHlwb1RvbGVyYW5jZT1zdHJpY3QmdXNlclRva2VuPXVzZXIxMjMmdmFsaWRVbnRpbD0yNTI0NjA0NDAw", it) + assertEquals("""MzAxMDUwYjYyODMxODQ3ZWM1ZDYzNTkxZmNjNDg2OGZjMjAzYjQyOTZhMGQ1NDJhMDFiNGMzYTYzODRhNmMxZWFyb3VuZFJhZGl1cz1hbGwmZmlsdGVycz1jYXRlZ29yeSUzQUJvb2slMjBPUiUyMGNhdGVnb3J5JTNBRWJvb2slMjBBTkQlMjBfdGFncyUzQXB1Ymxpc2hlZCZoaXRzUGVyUGFnZT0xMCZtb2RlPW5ldXJhbFNlYXJjaCZvcHRpb25hbFdvcmRzPW9uZSUyQ3R3byZxdWVyeT1iYXRtYW4mcmVzdHJpY3RJbmRpY2VzPU1vdmllcyUyQ2N0c19lMmVfc2V0dGluZ3MmcmVzdHJpY3RTb3VyY2VzPTE5Mi4xNjguMS4wJTJGMjQmdHlwb1RvbGVyYW5jZT1zdHJpY3QmdXNlclRva2VuPXVzZXIxMjMmdmFsaWRVbnRpbD0yNTI0NjA0NDAw""", it) }, + ) } @@ -294,10 +300,14 @@ class SearchTest { batchSize = 3, ) }, + response = { - val response = Json.encodeToString(it) - assertEquals("{\"copyOperationResponse\":{\"taskID\":125,\"updatedAt\":\"2021-01-01T00:00:00.000Z\"},\"batchResponses\":[{\"taskID\":127,\"objectIDs\":[\"1\",\"2\",\"3\"]},{\"taskID\":130,\"objectIDs\":[\"4\",\"5\",\"6\"]},{\"taskID\":133,\"objectIDs\":[\"7\",\"8\",\"9\"]},{\"taskID\":134,\"objectIDs\":[\"10\"]}],\"moveOperationResponse\":{\"taskID\":777,\"updatedAt\":\"2021-01-01T00:00:00.000Z\"}}", response) + assertNotNull(it) + val expected = Json.parseToJsonElement("""{"copyOperationResponse":{"taskID":125,"updatedAt":"2021-01-01T00:00:00.000Z"},"batchResponses":[{"taskID":127,"objectIDs":["1","2","3"]},{"taskID":130,"objectIDs":["4","5","6"]},{"taskID":133,"objectIDs":["7","8","9"]},{"taskID":134,"objectIDs":["10"]}],"moveOperationResponse":{"taskID":777,"updatedAt":"2021-01-01T00:00:00.000Z"}}""") + val actual = Json.encodeToJsonElement(it) + areJsonElementsEqual(expected, actual) }, + ) } @@ -332,10 +342,14 @@ class SearchTest { ), ) }, + response = { - val response = Json.encodeToString(it) - assertEquals("[{\"taskID\":333,\"objectIDs\":[\"1\",\"2\"]}]", response) + assertNotNull(it) + val expected = Json.parseToJsonElement("""[{"taskID":333,"objectIDs":["1","2"]}]""") + val actual = Json.encodeToJsonElement(it) + areJsonElementsEqual(expected, actual) }, + ) } @@ -371,10 +385,14 @@ class SearchTest { createIfNotExists = true, ) }, + response = { - val response = Json.encodeToString(it) - assertEquals("[{\"taskID\":444,\"objectIDs\":[\"1\",\"2\"]}]", response) + assertNotNull(it) + val expected = Json.parseToJsonElement("""[{"taskID":444,"objectIDs":["1","2"]}]""") + val actual = Json.encodeToJsonElement(it) + areJsonElementsEqual(expected, actual) }, + ) } @@ -410,10 +428,14 @@ class SearchTest { createIfNotExists = false, ) }, + response = { - val response = Json.encodeToString(it) - assertEquals("[{\"taskID\":555,\"objectIDs\":[\"3\",\"4\"]}]", response) + assertNotNull(it) + val expected = Json.parseToJsonElement("""[{"taskID":555,"objectIDs":["3","4"]}]""") + val actual = Json.encodeToJsonElement(it) + areJsonElementsEqual(expected, actual) }, + ) } @@ -427,10 +449,83 @@ class SearchTest { objectIDs = listOf("1", "2"), ) }, + response = { - val response = Json.encodeToString(it) - assertEquals("[{\"taskID\":666,\"objectIDs\":[\"1\",\"2\"]}]", response) + assertNotNull(it) + val expected = Json.parseToJsonElement("""[{"taskID":666,"objectIDs":["1","2"]}]""") + val actual = Json.encodeToJsonElement(it) + areJsonElementsEqual(expected, actual) + }, + + ) + } + + @Test + fun `wait for api key helper - add`() = runTest { + val client = SearchClient(appId = "test-app-id", apiKey = "test-api-key", options = ClientOptions(hosts = listOf(Host(url = "localhost", protocol = "http", port = 6681)))) + client.runTest( + call = { + waitForApiKey( + key = "api-key-add-operation-test-Kotlin", + operation = ApiKeyOperation.entries.first { it.value == "add" }, + ) }, + + response = { + assertNotNull(it) + val expected = Json.parseToJsonElement("""{"value":"api-key-add-operation-test-Kotlin","description":"my new api key","acl":["search","addObject"],"validity":300,"maxQueriesPerIPPerHour":100,"maxHitsPerQuery":20,"createdAt":1720094400}""") + val actual = Json.encodeToJsonElement(it) + areJsonElementsEqual(expected, actual) + }, + + ) + } + + @Test + fun `wait for api key - update`() = runTest { + val client = SearchClient(appId = "test-app-id", apiKey = "test-api-key", options = ClientOptions(hosts = listOf(Host(url = "localhost", protocol = "http", port = 6681)))) + client.runTest( + call = { + waitForApiKey( + key = "api-key-update-operation-test-Kotlin", + operation = ApiKeyOperation.entries.first { it.value == "update" }, + apiKey = ApiKey( + description = "my updated api key", + acl = listOf(Acl.entries.first { it.value == "search" }, Acl.entries.first { it.value == "addObject" }, Acl.entries.first { it.value == "deleteObject" }), + indexes = listOf("Movies", "Books"), + referers = listOf("*google.com", "*algolia.com"), + validity = 305, + maxQueriesPerIPPerHour = 95, + maxHitsPerQuery = 20, + ), + ) + }, + + response = { + assertNotNull(it) + val expected = Json.parseToJsonElement("""{"value":"api-key-update-operation-test-Kotlin","description":"my updated api key","acl":["search","addObject","deleteObject"],"indexes":["Movies","Books"],"referers":["*google.com","*algolia.com"],"validity":305,"maxQueriesPerIPPerHour":95,"maxHitsPerQuery":20,"createdAt":1720094400}""") + val actual = Json.encodeToJsonElement(it) + areJsonElementsEqual(expected, actual) + }, + + ) + } + + @Test + fun `wait for api key - delete`() = runTest { + val client = SearchClient(appId = "test-app-id", apiKey = "test-api-key", options = ClientOptions(hosts = listOf(Host(url = "localhost", protocol = "http", port = 6681)))) + client.runTest( + call = { + waitForApiKey( + key = "api-key-delete-operation-test-Kotlin", + operation = ApiKeyOperation.entries.first { it.value == "delete" }, + ) + }, + + response = { + assertNull(it) + }, + ) } diff --git a/tests/output/php/src/client/SearchTest.php b/tests/output/php/src/client/SearchTest.php index 04762fbcd7..539d5074d3 100644 --- a/tests/output/php/src/client/SearchTest.php +++ b/tests/output/php/src/client/SearchTest.php @@ -337,6 +337,70 @@ public function test6helpers() ); } + #[TestDox('wait for api key helper - add')] + public function test7helpers() + { + $client = SearchClient::createWithConfig(SearchConfig::create('test-app-id', 'test-api-key')->setFullHosts(['http://localhost:6681'])); + + $res = $client->waitForApiKey( + 'api-key-add-operation-test-PHP', + 'add', + ); + $this->assertEquals( + '{"value":"api-key-add-operation-test-PHP","description":"my new api key","acl":["search","addObject"],"validity":300,"maxQueriesPerIPPerHour":100,"maxHitsPerQuery":20,"createdAt":1720094400}', + json_encode($res) + ); + } + + #[TestDox('wait for api key - update')] + public function test8helpers() + { + $client = SearchClient::createWithConfig(SearchConfig::create('test-app-id', 'test-api-key')->setFullHosts(['http://localhost:6681'])); + + $res = $client->waitForApiKey( + 'api-key-update-operation-test-PHP', + 'update', + ['description' => 'my updated api key', + 'acl' => [ + 'search', + + 'addObject', + + 'deleteObject', + ], + 'indexes' => [ + 'Movies', + + 'Books', + ], + 'referers' => [ + '*google.com', + + '*algolia.com', + ], + 'validity' => 305, + 'maxQueriesPerIPPerHour' => 95, + 'maxHitsPerQuery' => 20, + ], + ); + $this->assertEquals( + '{"value":"api-key-update-operation-test-PHP","description":"my updated api key","acl":["search","addObject","deleteObject"],"indexes":["Movies","Books"],"referers":["*google.com","*algolia.com"],"validity":305,"maxQueriesPerIPPerHour":95,"maxHitsPerQuery":20,"createdAt":1720094400}', + json_encode($res) + ); + } + + #[TestDox('wait for api key - delete')] + public function test9helpers() + { + $client = SearchClient::createWithConfig(SearchConfig::create('test-app-id', 'test-api-key')->setFullHosts(['http://localhost:6681'])); + + $res = $client->waitForApiKey( + 'api-key-delete-operation-test-PHP', + 'delete', + ); + $this->assertNull($res); + } + #[TestDox('client throws with invalid parameters')] public function test0parameters() { diff --git a/tests/output/python/tests/client/search_test.py b/tests/output/python/tests/client/search_test.py index 2f82b1c809..c6cc634b9c 100644 --- a/tests/output/python/tests/client/search_test.py +++ b/tests/output/python/tests/client/search_test.py @@ -349,6 +349,89 @@ async def test_helpers_6(self): else _req.to_dict() ) == loads("""[{"taskID":666,"objectIDs":["1","2"]}]""") + async def test_helpers_7(self): + """ + wait for api key helper - add + """ + + _config = SearchConfig("test-app-id", "test-api-key") + _config.hosts = HostsCollection( + [Host(url="localhost", scheme="http", port=6681)] + ) + self._client = SearchClient.create_with_config(config=_config) + _req = await self._client.wait_for_api_key( + key="api-key-add-operation-test-Python", + operation="add", + ) + assert ( + _req + if isinstance(_req, dict) + else [elem.to_dict() for elem in _req] + if isinstance(_req, list) + else _req.to_dict() + ) == loads( + """{"value":"api-key-add-operation-test-Python","description":"my new api key","acl":["search","addObject"],"validity":300,"maxQueriesPerIPPerHour":100,"maxHitsPerQuery":20,"createdAt":1720094400}""" + ) + + async def test_helpers_8(self): + """ + wait for api key - update + """ + + _config = SearchConfig("test-app-id", "test-api-key") + _config.hosts = HostsCollection( + [Host(url="localhost", scheme="http", port=6681)] + ) + self._client = SearchClient.create_with_config(config=_config) + _req = await self._client.wait_for_api_key( + key="api-key-update-operation-test-Python", + operation="update", + api_key={ + "description": "my updated api key", + "acl": [ + "search", + "addObject", + "deleteObject", + ], + "indexes": [ + "Movies", + "Books", + ], + "referers": [ + "*google.com", + "*algolia.com", + ], + "validity": 305, + "maxQueriesPerIPPerHour": 95, + "maxHitsPerQuery": 20, + }, + ) + assert ( + _req + if isinstance(_req, dict) + else [elem.to_dict() for elem in _req] + if isinstance(_req, list) + else _req.to_dict() + ) == loads( + """{"value":"api-key-update-operation-test-Python","description":"my updated api key","acl":["search","addObject","deleteObject"],"indexes":["Movies","Books"],"referers":["*google.com","*algolia.com"],"validity":305,"maxQueriesPerIPPerHour":95,"maxHitsPerQuery":20,"createdAt":1720094400}""" + ) + + async def test_helpers_9(self): + """ + wait for api key - delete + """ + + _config = SearchConfig("test-app-id", "test-api-key") + _config.hosts = HostsCollection( + [Host(url="localhost", scheme="http", port=6681)] + ) + self._client = SearchClient.create_with_config(config=_config) + _req = await self._client.wait_for_api_key( + key="api-key-delete-operation-test-Python", + operation="delete", + ) + assert _req is None + async def test_parameters_0(self): """ client throws with invalid parameters diff --git a/tests/output/ruby/test/client/search_test.rb b/tests/output/ruby/test/client/search_test.rb index 6d6b257a96..d7d3808287 100644 --- a/tests/output/ruby/test/client/search_test.rb +++ b/tests/output/ruby/test/client/search_test.rb @@ -323,6 +323,105 @@ def test_helpers6 assert_equal([{:"taskID" => 666, :"objectIDs" => ["1", "2"]}], req.is_a?(Array) ? req.map(&:to_hash) : req.to_hash) end + # wait for api key helper - add + def test_helpers7 + client = Algolia::SearchClient.create_with_config( + Algolia::Configuration.new( + "test-app-id", + "test-api-key", + [ + Algolia::Transport::StatefulHost.new( + "localhost", + protocol: "http://", + port: 6681, + accept: CallType::READ | CallType::WRITE + ) + ], + "searchClient" + ) + ) + req = client.wait_for_api_key("api-key-add-operation-test-Ruby", "add") + assert_equal( + { + :"value" => "api-key-add-operation-test-Ruby", + :"description" => "my new api key", + :"acl" => ["search", "addObject"], + :"validity" => 300, + :"maxQueriesPerIPPerHour" => 100, + :"maxHitsPerQuery" => 20, + :"createdAt" => 1720094400 + }, + req.is_a?(Array) ? req.map(&:to_hash) : req.to_hash + ) + end + + # wait for api key - update + def test_helpers8 + client = Algolia::SearchClient.create_with_config( + Algolia::Configuration.new( + "test-app-id", + "test-api-key", + [ + Algolia::Transport::StatefulHost.new( + "localhost", + protocol: "http://", + port: 6681, + accept: CallType::READ | CallType::WRITE + ) + ], + "searchClient" + ) + ) + req = client.wait_for_api_key( + "api-key-update-operation-test-Ruby", + "update", + ApiKey.new( + description: "my updated api key", + acl: ["search", "addObject", "deleteObject"], + indexes: ["Movies", "Books"], + referers: ["*google.com", "*algolia.com"], + validity: 305, + max_queries_per_ip_per_hour: 95, + max_hits_per_query: 20 + ) + ) + assert_equal( + { + :"value" => "api-key-update-operation-test-Ruby", + :"description" => "my updated api key", + :"acl" => ["search", "addObject", "deleteObject"], + :"indexes" => ["Movies", "Books"], + :"referers" => ["*google.com", "*algolia.com"], + :"validity" => 305, + :"maxQueriesPerIPPerHour" => 95, + :"maxHitsPerQuery" => 20, + :"createdAt" => 1720094400 + }, + req.is_a?(Array) ? req.map(&:to_hash) : req.to_hash + ) + end + + # wait for api key - delete + def test_helpers9 + client = Algolia::SearchClient.create_with_config( + Algolia::Configuration.new( + "test-app-id", + "test-api-key", + [ + Algolia::Transport::StatefulHost.new( + "localhost", + protocol: "http://", + port: 6681, + accept: CallType::READ | CallType::WRITE + ) + ], + "searchClient" + ) + ) + req = client.wait_for_api_key("api-key-delete-operation-test-Ruby", "delete") + assert_nil(req) + end + # client throws with invalid parameters def test_parameters0 begin diff --git a/tests/output/swift/Tests/client/SearchTests.swift b/tests/output/swift/Tests/client/SearchTests.swift index fa7b63ff3a..c8f9e456fc 100644 --- a/tests/output/swift/Tests/client/SearchTests.swift +++ b/tests/output/swift/Tests/client/SearchTests.swift @@ -328,6 +328,82 @@ final class SearchClientClientTests: XCTestCase { ) } + /// wait for api key helper - add + func testHelpersTest7() async throws { + let configuration = try SearchClientConfiguration( + appID: "test-app-id", + apiKey: "test-api-key", + hosts: [RetryableHost(url: URL(string: "http://localhost:6681")!)] + ) + let transporter = Transporter(configuration: configuration) + let client = SearchClient(configuration: configuration, transporter: transporter) + let response = try await client.waitForApiKey( + key: "api-key-add-operation-test-Swift", + operation: ApiKeyOperation.add + ) + + let comparableData = + try XCTUnwrap( + "{\"value\":\"api-key-add-operation-test-Swift\",\"description\":\"my new api key\",\"acl\":[\"search\",\"addObject\"],\"validity\":300,\"maxQueriesPerIPPerHour\":100,\"maxHitsPerQuery\":20,\"createdAt\":1720094400}" + .data(using: .utf8) + ) + try XCTLenientAssertEqual( + received: CodableHelper.jsonEncoder.encode(response), + expected: comparableData + ) + } + + /// wait for api key - update + func testHelpersTest8() async throws { + let configuration = try SearchClientConfiguration( + appID: "test-app-id", + apiKey: "test-api-key", + hosts: [RetryableHost(url: URL(string: "http://localhost:6681")!)] + ) + let transporter = Transporter(configuration: configuration) + let client = SearchClient(configuration: configuration, transporter: transporter) + let response = try await client.waitForApiKey( + key: "api-key-update-operation-test-Swift", + operation: ApiKeyOperation.update, + apiKey: ApiKey( + acl: [Acl.search, Acl.addObject, Acl.deleteObject], + description: "my updated api key", + indexes: ["Movies", "Books"], + maxHitsPerQuery: 20, + maxQueriesPerIPPerHour: 95, + referers: ["*google.com", "*algolia.com"], + validity: 305 + ) + ) + + let comparableData = + try XCTUnwrap( + "{\"value\":\"api-key-update-operation-test-Swift\",\"description\":\"my updated api key\",\"acl\":[\"search\",\"addObject\",\"deleteObject\"],\"indexes\":[\"Movies\",\"Books\"],\"referers\":[\"*google.com\",\"*algolia.com\"],\"validity\":305,\"maxQueriesPerIPPerHour\":95,\"maxHitsPerQuery\":20,\"createdAt\":1720094400}" + .data(using: .utf8) + ) + try XCTLenientAssertEqual( + received: CodableHelper.jsonEncoder.encode(response), + expected: comparableData + ) + } + + /// wait for api key - delete + func testHelpersTest9() async throws { + let configuration = try SearchClientConfiguration( + appID: "test-app-id", + apiKey: "test-api-key", + hosts: [RetryableHost(url: URL(string: "http://localhost:6681")!)] + ) + let transporter = Transporter(configuration: configuration) + let client = SearchClient(configuration: configuration, transporter: transporter) + let response = try await client.waitForApiKey( + key: "api-key-delete-operation-test-Swift", + operation: ApiKeyOperation.delete + ) + + XCTAssertNil(response) + } + /// client throws with invalid parameters func testParametersTest0() async throws { do {