From dd795d2a912892831e140373060f41543b51f706 Mon Sep 17 00:00:00 2001 From: algolia-bot Date: Tue, 9 May 2023 09:00:17 +0000 Subject: [PATCH] chore: generated code for commit 4fb9def543c0f7c0719cbe7e9e704ab93d467376. [skip ci] Co-authored-by: Mehmet Ali Gok <33124154+mehmetaligok@users.noreply.github.com> --- .../algolia/analytics/api_analytics.go | 1369 ++++++- .../algolia/analytics/client.go | 19 +- .../analytics/model_average_click_event.go | 6 +- .../algolia/analytics/model_click_position.go | 4 +- .../model_click_through_rate_event.go | 8 +- .../analytics/model_conversion_rate_event.go | 8 +- ...del_get_average_click_position_response.go | 6 +- .../model_get_click_positions_response.go | 2 +- .../model_get_click_through_rate_response.go | 8 +- .../model_get_conversation_rate_response.go | 8 +- .../model_get_no_click_rate_response.go | 8 +- .../model_get_no_results_rate_response.go | 8 +- .../model_get_searches_count_response.go | 4 +- .../model_get_searches_no_clicks_response.go | 2 +- .../model_get_searches_no_results_response.go | 2 +- .../analytics/model_get_status_response.go | 2 +- .../model_get_top_countries_response.go | 2 +- .../model_get_top_filter_attribute.go | 4 +- ...odel_get_top_filter_attributes_response.go | 2 +- .../model_get_top_filter_for_attribute.go | 8 +- ...l_get_top_filter_for_attribute_response.go | 2 +- ...del_get_top_filters_no_results_response.go | 2 +- .../model_get_top_filters_no_results_value.go | 6 +- ...model_get_top_filters_no_results_values.go | 4 +- .../analytics/model_get_top_hits_response.go | 21 +- .../model_get_top_searches_response.go | 21 +- .../model_get_users_count_response.go | 4 +- .../analytics/model_no_click_rate_event.go | 8 +- .../analytics/model_no_results_rate_event.go | 8 +- .../algolia/analytics/model_search_event.go | 4 +- .../analytics/model_search_no_click_event.go | 6 +- .../analytics/model_search_no_result_event.go | 6 +- .../algolia/analytics/model_top_country.go | 4 +- .../algolia/analytics/model_top_hit.go | 4 +- .../analytics/model_top_hit_with_analytics.go | 14 +- .../analytics/model_top_hits_response.go | 2 +- .../model_top_hits_response_with_analytics.go | 2 +- .../algolia/analytics/model_top_search.go | 6 +- .../model_top_search_with_analytics.go | 18 +- .../analytics/model_top_searches_response.go | 2 +- ...el_top_searches_response_with_analytics.go | 2 +- .../algolia/analytics/model_user_with_date.go | 4 +- .../algolia/analytics/utils.go | 2 + .../algolia/ingestion/api_ingestion.go | 1461 +++++++- .../algolia/ingestion/client.go | 19 +- .../algolia/ingestion/model_auth_algolia.go | 4 +- .../algolia/ingestion/model_auth_api_key.go | 2 +- .../algolia/ingestion/model_auth_basic.go | 4 +- .../model_auth_google_service_account.go | 4 +- .../algolia/ingestion/model_auth_input.go | 36 +- .../algolia/ingestion/model_auth_o_auth.go | 6 +- .../algolia/ingestion/model_authentication.go | 8 +- .../ingestion/model_authentication_create.go | 6 +- .../model_authentication_create_response.go | 6 +- .../ingestion/model_authentication_input.go | 2 +- .../ingestion/model_authentication_search.go | 2 +- .../model_authentication_update_response.go | 6 +- .../model_authentication_with_input.go | 10 +- .../ingestion/model_big_commerce_channel.go | 2 +- .../ingestion/model_delete_response.go | 2 +- .../algolia/ingestion/model_destination.go | 10 +- .../ingestion/model_destination_create.go | 6 +- .../model_destination_create_response.go | 6 +- .../ingestion/model_destination_index_name.go | 2 +- .../model_destination_index_prefix.go | 2 +- .../ingestion/model_destination_input.go | 21 +- .../ingestion/model_destination_search.go | 2 +- .../model_destination_update_response.go | 6 +- .../algolia/ingestion/model_event.go | 10 +- .../model_list_authentications_response.go | 4 +- .../model_list_destinations_response.go | 4 +- .../ingestion/model_list_events_response.go | 4 +- .../ingestion/model_list_sources_response.go | 4 +- .../ingestion/model_list_tasks_response.go | 4 +- .../ingestion/model_on_demand_trigger.go | 2 +- .../model_on_demand_trigger_input.go | 2 +- .../algolia/ingestion/model_pagination.go | 8 +- .../ingestion/model_platform_with_none.go | 21 +- .../algolia/ingestion/model_run.go | 14 +- .../ingestion/model_run_list_response.go | 4 +- .../algolia/ingestion/model_run_response.go | 4 +- .../ingestion/model_schedule_trigger.go | 6 +- .../ingestion/model_schedule_trigger_input.go | 4 +- .../algolia/ingestion/model_source.go | 10 +- .../ingestion/model_source_big_query.go | 4 +- .../ingestion/model_source_commercetools.go | 4 +- .../algolia/ingestion/model_source_create.go | 6 +- .../ingestion/model_source_create_response.go | 6 +- .../algolia/ingestion/model_source_csv.go | 2 +- .../algolia/ingestion/model_source_input.go | 36 +- .../algolia/ingestion/model_source_json.go | 2 +- .../algolia/ingestion/model_source_search.go | 2 +- .../ingestion/model_source_update_input.go | 31 +- .../ingestion/model_source_update_response.go | 6 +- .../ingestion/model_subscription_trigger.go | 2 +- .../algolia/ingestion/model_task.go | 14 +- .../algolia/ingestion/model_task_create.go | 8 +- .../ingestion/model_task_create_response.go | 4 +- .../ingestion/model_task_create_trigger.go | 26 +- .../algolia/ingestion/model_task_search.go | 2 +- .../ingestion/model_task_update_response.go | 4 +- .../algolia/ingestion/model_trigger.go | 26 +- .../algolia/ingestion/model_trigger_input.go | 2 +- .../algolia/ingestion/utils.go | 2 + .../algolia/insights/api_insights.go | 199 +- .../algolia/insights/client.go | 19 +- .../algolia/insights/model_insight_event.go | 8 +- .../algolia/insights/model_insight_events.go | 2 +- .../insights/model_push_events_response.go | 2 +- .../algolia/insights/utils.go | 2 + .../personalization/api_personalization.go | 253 +- .../algolia/personalization/client.go | 19 +- .../model_delete_user_profile_response.go | 4 +- .../personalization/model_event_scoring.go | 6 +- .../personalization/model_facet_scoring.go | 4 +- .../model_get_user_token_response.go | 6 +- .../model_personalization_strategy_params.go | 6 +- ...l_set_personalization_strategy_response.go | 2 +- .../algolia/personalization/utils.go | 2 + .../algolia/predict/api_predict.go | 592 ++- .../algolia/predict/client.go | 19 +- .../model_activate_model_instance_response.go | 4 +- .../predict/model_activate_model_params.go | 8 +- .../algolia/predict/model_affinity.go | 6 +- .../predict/model_create_segment_params.go | 4 +- .../predict/model_create_segment_response.go | 4 +- .../model_delete_model_instance_response.go | 4 +- .../predict/model_delete_segment_response.go | 4 +- .../model_delete_user_profile_response.go | 4 +- .../algolia/predict/model_error.go | 2 +- .../model_fetch_all_user_profiles_params.go | 36 +- .../model_fetch_all_user_profiles_response.go | 2 +- .../algolia/predict/model_funnel_stage.go | 4 +- ...et_available_model_types_response_inner.go | 8 +- ..._types_response_inner_data_requirements.go | 4 +- .../model_get_model_metrics_response.go | 4 +- .../model_get_segment_users_response.go | 4 +- .../algolia/predict/model_model_attributes.go | 2 +- .../algolia/predict/model_model_instance.go | 16 +- .../algolia/predict/model_params.go | 26 +- .../model_prediction_affinity_value.go | 26 +- .../predict/model_predictions_affinities.go | 21 +- .../model_predictions_affinities_success.go | 4 +- .../predict/model_predictions_funnel_stage.go | 21 +- .../model_predictions_funnel_stage_success.go | 4 +- .../predict/model_predictions_order_value.go | 21 +- .../model_predictions_order_value_success.go | 4 +- .../algolia/predict/model_segment.go | 14 +- .../predict/model_segment_affinity_filter.go | 4 +- .../model_segment_affinity_filter_value.go | 31 +- .../model_segment_child_condition_operands.go | 31 +- .../predict/model_segment_child_conditions.go | 4 +- .../model_segment_funnel_stage_filter.go | 4 +- .../predict/model_segment_operand_affinity.go | 4 +- .../model_segment_operand_funnel_stage.go | 4 +- .../model_segment_operand_order_value.go | 4 +- .../predict/model_segment_operand_property.go | 4 +- .../model_segment_order_value_filter.go | 2 +- ...model_segment_parent_condition_operands.go | 36 +- .../model_segment_parent_conditions.go | 4 +- .../predict/model_segment_property_filter.go | 2 +- .../algolia/predict/model_segments.go | 4 +- .../model_update_model_instance_response.go | 4 +- .../predict/model_update_segment_params.go | 26 +- .../predict/model_update_segment_response.go | 4 +- .../algolia/predict/model_user_profile.go | 2 +- .../algolia/predict/utils.go | 2 + .../api_query_suggestions.go | 334 +- .../algolia/query-suggestions/client.go | 19 +- .../query-suggestions/model_index_name.go | 2 +- .../query-suggestions/model_log_file.go | 8 +- .../model_query_suggestions_index.go | 8 +- .../model_query_suggestions_index_param.go | 2 +- ...uery_suggestions_index_with_index_param.go | 4 +- .../query-suggestions/model_source_index.go | 2 +- .../model_source_index_external.go | 4 +- .../model_source_index_with_replicas.go | 16 +- .../algolia/query-suggestions/model_status.go | 6 +- .../model_success_response.go | 4 +- .../algolia/query-suggestions/utils.go | 2 + .../algolia/recommend/api_recommend.go | 199 +- .../algolia/recommend/client.go | 19 +- .../algolia/recommend/model_around_radius.go | 21 +- .../recommend/model_base_recommend_request.go | 4 +- .../model_base_recommendation_request.go | 4 +- .../recommend/model_base_search_response.go | 16 +- .../recommend/model_base_trending_request.go | 2 +- .../algolia/recommend/model_distinct.go | 21 +- .../algolia/recommend/model_facet_filters.go | 21 +- .../model_get_recommendations_params.go | 2 +- .../recommend/model_highlight_result.go | 21 +- .../model_highlight_result_option.go | 6 +- .../algolia/recommend/model_ignore_plurals.go | 21 +- .../recommend/model_mixed_search_filters.go | 21 +- .../recommend/model_numeric_filters.go | 21 +- .../recommend/model_optional_filters.go | 21 +- .../algolia/recommend/model_ranking_info.go | 16 +- .../model_re_ranking_apply_filter.go | 21 +- .../algolia/recommend/model_recommend_hit.go | 4 +- .../algolia/recommend/model_recommend_hits.go | 2 +- .../recommend/model_recommendation_request.go | 8 +- .../model_recommendations_request.go | 21 +- .../model_recommendations_response.go | 18 +- .../model_redirect_rule_index_metadata.go | 10 +- ...model_redirect_rule_index_metadata_data.go | 2 +- .../recommend/model_remove_stop_words.go | 21 +- .../algolia/recommend/model_snippet_result.go | 21 +- .../recommend/model_snippet_result_option.go | 4 +- .../algolia/recommend/model_tag_filters.go | 21 +- .../recommend/model_trending_request.go | 6 +- .../algolia/recommend/model_typo_tolerance.go | 21 +- .../algolia/recommend/utils.go | 2 + .../algolia/search/api_search.go | 2149 ++++++++++- .../algolia/search/client.go | 19 +- .../search/model_add_api_key_response.go | 4 +- .../algolia/search/model_api_key.go | 2 +- .../algolia/search/model_around_radius.go | 21 +- .../search/model_assign_user_id_params.go | 2 +- .../search/model_attribute_to_update.go | 21 +- .../search/model_automatic_facet_filter.go | 2 +- .../search/model_automatic_facet_filters.go | 21 +- .../search/model_base_get_api_key_response.go | 2 +- .../search/model_base_search_response.go | 16 +- .../model_batch_assign_user_ids_params.go | 4 +- .../model_batch_dictionary_entries_params.go | 2 +- .../model_batch_dictionary_entries_request.go | 4 +- .../algolia/search/model_batch_params.go | 2 +- .../algolia/search/model_batch_request.go | 4 +- .../algolia/search/model_batch_response.go | 4 +- .../search/model_batch_write_params.go | 2 +- .../algolia/search/model_browse_params.go | 21 +- .../algolia/search/model_browse_response.go | 18 +- .../search/model_built_in_operation.go | 4 +- .../algolia/search/model_consequence_hide.go | 2 +- .../algolia/search/model_consequence_query.go | 21 +- .../search/model_created_at_response.go | 2 +- .../search/model_delete_api_key_response.go | 2 +- .../search/model_delete_source_response.go | 2 +- .../search/model_deleted_at_response.go | 4 +- .../algolia/search/model_dictionary_entry.go | 4 +- .../model_dictionary_settings_params.go | 2 +- .../algolia/search/model_distinct.go | 21 +- .../algolia/search/model_facet_filters.go | 21 +- .../algolia/search/model_facet_hits.go | 6 +- .../algolia/search/model_fetched_index.go | 18 +- .../search/model_get_api_key_response.go | 4 +- .../model_get_dictionary_settings_response.go | 2 +- .../algolia/search/model_get_logs_response.go | 2 +- .../search/model_get_objects_params.go | 2 +- .../search/model_get_objects_request.go | 4 +- .../search/model_get_objects_response.go | 2 +- .../algolia/search/model_get_task_response.go | 2 +- .../search/model_get_top_user_ids_response.go | 2 +- .../model_has_pending_mappings_response.go | 2 +- .../algolia/search/model_highlight_result.go | 21 +- .../search/model_highlight_result_option.go | 6 +- .../algolia/search/model_hit.go | 2 +- .../algolia/search/model_ignore_plurals.go | 21 +- .../algolia/search/model_languages.go | 6 +- .../search/model_list_api_keys_response.go | 2 +- .../search/model_list_clusters_response.go | 2 +- .../search/model_list_indices_response.go | 2 +- .../search/model_list_user_ids_response.go | 2 +- .../algolia/search/model_log.go | 22 +- .../search/model_mixed_search_filters.go | 21 +- .../search/model_multiple_batch_request.go | 6 +- .../search/model_multiple_batch_response.go | 4 +- .../algolia/search/model_numeric_filters.go | 21 +- .../search/model_operation_index_params.go | 4 +- .../algolia/search/model_optional_filters.go | 21 +- .../algolia/search/model_promote.go | 21 +- .../algolia/search/model_promote_object_id.go | 4 +- .../search/model_promote_object_ids.go | 4 +- .../algolia/search/model_ranking_info.go | 16 +- .../search/model_re_ranking_apply_filter.go | 21 +- .../model_redirect_rule_index_metadata.go | 10 +- ...model_redirect_rule_index_metadata_data.go | 2 +- .../algolia/search/model_remove_stop_words.go | 21 +- .../search/model_remove_user_id_response.go | 2 +- .../search/model_replace_source_response.go | 2 +- .../algolia/search/model_rule.go | 2 +- .../search/model_save_object_response.go | 4 +- .../search/model_save_synonym_response.go | 6 +- .../model_search_dictionary_entries_params.go | 2 +- .../model_search_for_facet_values_response.go | 2 +- .../algolia/search/model_search_for_facets.go | 6 +- .../search/model_search_for_facets_options.go | 6 +- .../algolia/search/model_search_for_hits.go | 2 +- .../search/model_search_for_hits_options.go | 2 +- .../algolia/search/model_search_hits.go | 2 +- .../search/model_search_method_params.go | 2 +- .../algolia/search/model_search_params.go | 21 +- .../algolia/search/model_search_query.go | 21 +- .../algolia/search/model_search_response.go | 18 +- .../algolia/search/model_search_responses.go | 2 +- .../search/model_search_rules_response.go | 8 +- .../search/model_search_synonyms_response.go | 4 +- .../search/model_search_user_ids_params.go | 2 +- .../search/model_search_user_ids_response.go | 10 +- .../algolia/search/model_snippet_result.go | 21 +- .../search/model_snippet_result_option.go | 4 +- .../algolia/search/model_source.go | 2 +- .../algolia/search/model_synonym_hit.go | 4 +- .../algolia/search/model_tag_filters.go | 21 +- .../algolia/search/model_time_range.go | 4 +- .../algolia/search/model_typo_tolerance.go | 21 +- .../search/model_update_api_key_response.go | 4 +- .../search/model_updated_at_response.go | 4 +- .../search/model_updated_rule_response.go | 6 +- .../search/model_user_highlight_result.go | 4 +- .../algolia/search/model_user_hit.go | 12 +- .../algolia/search/model_user_id.go | 8 +- .../algolia/search/utils.go | 2 + .../client-bom/README.md | 16 + .../kotlin/com/algolia/client/BuildConfig.kt | 5 + .../com/algolia/client/api/AbtestingClient.kt | 217 ++ .../com/algolia/client/api/AnalyticsClient.kt | 625 ++++ .../com/algolia/client/api/ApiClient.kt | 18 + .../com/algolia/client/api/IngestionClient.kt | 770 ++++ .../com/algolia/client/api/InsightsClient.kt | 140 + .../client/api/PersonalizationClient.kt | 192 + .../com/algolia/client/api/PredictClient.kt | 416 +++ .../client/api/QuerySuggestionsClient.kt | 248 ++ .../com/algolia/client/api/RecommendClient.kt | 144 + .../com/algolia/client/api/SearchClient.kt | 1290 +++++++ .../algolia/client/model/abtesting/ABTest.kt | 49 + .../client/model/abtesting/ABTestResponse.kt | 25 + .../client/model/abtesting/AbTestsVariant.kt | 25 + .../abtesting/AbTestsVariantSearchParams.kt | 28 + .../model/abtesting/AddABTestsRequest.kt | 25 + .../model/abtesting/AddABTestsVariant.kt | 96 + .../model/abtesting/CustomSearchParams.kt | 16 + .../client/model/abtesting/ErrorBase.kt | 46 + .../model/abtesting/ListABTestsResponse.kt | 25 + .../algolia/client/model/abtesting/Variant.kt | 61 + .../model/analytics/AverageClickEvent.kt | 25 + .../client/model/analytics/ClickPosition.kt | 21 + .../model/analytics/ClickThroughRateEvent.kt | 29 + .../model/analytics/ConversionRateEvent.kt | 29 + .../client/model/analytics/Direction.kt | 16 + .../client/model/analytics/ErrorBase.kt | 46 + .../GetAverageClickPositionResponse.kt | 25 + .../analytics/GetClickPositionsResponse.kt | 17 + .../analytics/GetClickThroughRateResponse.kt | 29 + .../analytics/GetConversationRateResponse.kt | 29 + .../model/analytics/GetNoClickRateResponse.kt | 29 + .../analytics/GetNoResultsRateResponse.kt | 29 + .../analytics/GetSearchesCountResponse.kt | 21 + .../analytics/GetSearchesNoClicksResponse.kt | 17 + .../analytics/GetSearchesNoResultsResponse.kt | 17 + .../model/analytics/GetStatusResponse.kt | 17 + .../analytics/GetTopCountriesResponse.kt | 17 + .../model/analytics/GetTopFilterAttribute.kt | 21 + .../GetTopFilterAttributesResponse.kt | 17 + .../analytics/GetTopFilterForAttribute.kt | 29 + .../GetTopFilterForAttributeResponse.kt | 17 + .../GetTopFiltersNoResultsResponse.kt | 17 + .../analytics/GetTopFiltersNoResultsValue.kt | 25 + .../analytics/GetTopFiltersNoResultsValues.kt | 21 + .../model/analytics/GetTopHitsResponse.kt | 81 + .../model/analytics/GetTopSearchesResponse.kt | 81 + .../model/analytics/GetUsersCountResponse.kt | 21 + .../model/analytics/NoClickRateEvent.kt | 29 + .../model/analytics/NoResultsRateEvent.kt | 29 + .../algolia/client/model/analytics/OrderBy.kt | 22 + .../client/model/analytics/SearchEvent.kt | 21 + .../model/analytics/SearchNoClickEvent.kt | 25 + .../model/analytics/SearchNoResultEvent.kt | 25 + .../client/model/analytics/TopCountry.kt | 21 + .../algolia/client/model/analytics/TopHit.kt | 21 + .../model/analytics/TopHitWithAnalytics.kt | 41 + .../client/model/analytics/TopHitsResponse.kt | 17 + .../analytics/TopHitsResponseWithAnalytics.kt | 17 + .../client/model/analytics/TopSearch.kt | 25 + .../model/analytics/TopSearchWithAnalytics.kt | 49 + .../model/analytics/TopSearchesResponse.kt | 17 + .../TopSearchesResponseWithAnalytics.kt | 17 + .../client/model/analytics/UserWithDate.kt | 21 + .../client/model/ingestion/ActionType.kt | 19 + .../client/model/ingestion/AuthAPIKey.kt | 16 + .../client/model/ingestion/AuthAlgolia.kt | 21 + .../client/model/ingestion/AuthBasic.kt | 19 + .../ingestion/AuthGoogleServiceAccount.kt | 21 + .../client/model/ingestion/AuthInput.kt | 162 + .../client/model/ingestion/AuthOAuth.kt | 25 + .../client/model/ingestion/Authentication.kt | 35 + .../model/ingestion/AuthenticationCreate.kt | 26 + .../ingestion/AuthenticationCreateResponse.kt | 25 + .../model/ingestion/AuthenticationInput.kt | 16 + .../model/ingestion/AuthenticationSearch.kt | 16 + .../model/ingestion/AuthenticationSortKeys.kt | 28 + .../model/ingestion/AuthenticationType.kt | 28 + .../model/ingestion/AuthenticationUpdate.kt | 26 + .../ingestion/AuthenticationUpdateResponse.kt | 25 + .../ingestion/AuthenticationWithInput.kt | 38 + .../model/ingestion/BigCommerceChannel.kt | 21 + .../model/ingestion/BigQueryDataType.kt | 16 + .../client/model/ingestion/DeleteResponse.kt | 17 + .../client/model/ingestion/Destination.kt | 38 + .../model/ingestion/DestinationCreate.kt | 27 + .../ingestion/DestinationCreateResponse.kt | 25 + .../model/ingestion/DestinationIndexName.kt | 17 + .../model/ingestion/DestinationIndexPrefix.kt | 17 + .../model/ingestion/DestinationInput.kt | 81 + .../model/ingestion/DestinationSearch.kt | 16 + .../model/ingestion/DestinationSortKeys.kt | 25 + .../client/model/ingestion/DestinationType.kt | 25 + .../model/ingestion/DestinationUpdate.kt | 26 + .../ingestion/DestinationUpdateResponse.kt | 25 + .../client/model/ingestion/ErrorBase.kt | 46 + .../algolia/client/model/ingestion/Event.kt | 38 + .../client/model/ingestion/EventSortKeys.kt | 22 + .../client/model/ingestion/EventStatus.kt | 25 + .../client/model/ingestion/EventType.kt | 22 + .../ingestion/ListAuthenticationsResponse.kt | 19 + .../ingestion/ListDestinationsResponse.kt | 19 + .../model/ingestion/ListEventsResponse.kt | 19 + .../model/ingestion/ListSourcesResponse.kt | 19 + .../model/ingestion/ListTasksResponse.kt | 19 + .../client/model/ingestion/MappingTypeCSV.kt | 25 + .../client/model/ingestion/MethodType.kt | 16 + .../client/model/ingestion/OnDemandTrigger.kt | 20 + .../model/ingestion/OnDemandTriggerInput.kt | 16 + .../model/ingestion/OnDemandTriggerType.kt | 16 + .../client/model/ingestion/OrderKeys.kt | 19 + .../client/model/ingestion/Pagination.kt | 25 + .../client/model/ingestion/Platform.kt | 19 + .../client/model/ingestion/PlatformNone.kt | 16 + .../model/ingestion/PlatformWithNone.kt | 69 + .../com/algolia/client/model/ingestion/Run.kt | 56 + .../client/model/ingestion/RunListResponse.kt | 19 + .../client/model/ingestion/RunOutcome.kt | 16 + .../client/model/ingestion/RunProgress.kt | 19 + .../client/model/ingestion/RunResponse.kt | 21 + .../client/model/ingestion/RunSortKeys.kt | 22 + .../client/model/ingestion/RunStatus.kt | 25 + .../algolia/client/model/ingestion/RunType.kt | 16 + .../client/model/ingestion/ScheduleTrigger.kt | 28 + .../model/ingestion/ScheduleTriggerInput.kt | 20 + .../model/ingestion/ScheduleTriggerType.kt | 16 + .../algolia/client/model/ingestion/Source.kt | 38 + .../model/ingestion/SourceBigCommerce.kt | 20 + .../client/model/ingestion/SourceBigQuery.kt | 32 + .../client/model/ingestion/SourceCSV.kt | 32 + .../model/ingestion/SourceCommercetools.kt | 26 + .../client/model/ingestion/SourceCreate.kt | 26 + .../model/ingestion/SourceCreateResponse.kt | 24 + .../client/model/ingestion/SourceInput.kt | 189 + .../client/model/ingestion/SourceJSON.kt | 24 + .../client/model/ingestion/SourceSearch.kt | 16 + .../client/model/ingestion/SourceSortKeys.kt | 25 + .../client/model/ingestion/SourceType.kt | 25 + .../client/model/ingestion/SourceUpdate.kt | 23 + .../ingestion/SourceUpdateCommercetools.kt | 21 + .../model/ingestion/SourceUpdateInput.kt | 158 + .../model/ingestion/SourceUpdateResponse.kt | 24 + .../model/ingestion/SubscriptionTrigger.kt | 16 + .../ingestion/SubscriptionTriggerType.kt | 16 + .../algolia/client/model/ingestion/Task.kt | 47 + .../client/model/ingestion/TaskCreate.kt | 31 + .../model/ingestion/TaskCreateResponse.kt | 21 + .../model/ingestion/TaskCreateTrigger.kt | 106 + .../client/model/ingestion/TaskSearch.kt | 16 + .../client/model/ingestion/TaskSortKeys.kt | 28 + .../client/model/ingestion/TaskUpdate.kt | 24 + .../model/ingestion/TaskUpdateResponse.kt | 21 + .../algolia/client/model/ingestion/Trigger.kt | 115 + .../client/model/ingestion/TriggerInput.kt | 16 + .../client/model/ingestion/TriggerType.kt | 22 + .../client/model/insights/ErrorBase.kt | 46 + .../client/model/insights/EventType.kt | 19 + .../client/model/insights/InsightEvent.kt | 48 + .../client/model/insights/InsightEvents.kt | 17 + .../model/insights/PushEventsResponse.kt | 17 + .../DeleteUserProfileResponse.kt | 21 + .../client/model/personalization/ErrorBase.kt | 46 + .../model/personalization/EventScoring.kt | 25 + .../model/personalization/FacetScoring.kt | 21 + .../personalization/GetUserTokenResponse.kt | 25 + .../PersonalizationStrategyParams.kt | 25 + .../SetPersonalizationStrategyResponse.kt | 17 + .../predict/ActivateModelInstanceResponse.kt | 21 + .../model/predict/ActivateModelParams.kt | 31 + .../algolia/client/model/predict/Affinity.kt | 22 + .../algolia/client/model/predict/AllParams.kt | 19 + .../model/predict/AllUpdateSegmentParams.kt | 20 + .../client/model/predict/CompatibleSources.kt | 13 + .../model/predict/CreateSegmentParams.kt | 20 + .../model/predict/CreateSegmentResponse.kt | 25 + .../predict/DeleteModelInstanceResponse.kt | 21 + .../model/predict/DeleteSegmentResponse.kt | 21 + .../predict/DeleteUserProfileResponse.kt | 21 + .../com/algolia/client/model/predict/Error.kt | 16 + .../algolia/client/model/predict/ErrorBase.kt | 46 + .../predict/FetchAllUserProfilesParams.kt | 147 + .../predict/FetchAllUserProfilesResponse.kt | 24 + .../client/model/predict/FunnelStage.kt | 19 + .../GetAvailableModelTypesResponseInner.kt | 27 + ...ModelTypesResponseInnerDataRequirements.kt | 21 + .../predict/GetModelInstanceConfigStatus.kt | 25 + .../model/predict/GetModelMetricsResponse.kt | 20 + .../model/predict/GetSegmentUsersResponse.kt | 28 + .../client/model/predict/LimitParam.kt | 16 + .../client/model/predict/ModelAttributes.kt | 19 + .../client/model/predict/ModelInstance.kt | 47 + .../client/model/predict/ModelMetrics.kt | 32 + .../client/model/predict/ModelStatus.kt | 19 + .../client/model/predict/ModelsToRetrieve.kt | 19 + .../model/predict/ModelsToRetrieveParam.kt | 16 + .../model/predict/NextPageTokenParam.kt | 17 + .../algolia/client/model/predict/Params.kt | 106 + .../model/predict/PredictionAffinityValue.kt | 106 + .../client/model/predict/Predictions.kt | 22 + .../model/predict/PredictionsAffinities.kt | 84 + .../predict/PredictionsAffinitiesSuccess.kt | 19 + .../model/predict/PredictionsFunnelStage.kt | 84 + .../predict/PredictionsFunnelStageSuccess.kt | 19 + .../model/predict/PredictionsOrderValue.kt | 84 + .../predict/PredictionsOrderValueSuccess.kt | 19 + .../model/predict/PreviousPageTokenParam.kt | 17 + .../client/model/predict/Properties.kt | 25 + .../algolia/client/model/predict/Segment.kt | 41 + .../model/predict/SegmentAffinityFilter.kt | 22 + .../predict/SegmentAffinityFilterValue.kt | 129 + .../predict/SegmentChildConditionOperands.kt | 137 + .../model/predict/SegmentChildConditions.kt | 19 + .../model/predict/SegmentConditionOperator.kt | 19 + .../model/predict/SegmentConditionsParam.kt | 16 + .../predict/SegmentFilterOperatorBoolean.kt | 19 + .../predict/SegmentFilterOperatorNumerical.kt | 31 + .../model/predict/SegmentFilterProbability.kt | 25 + .../model/predict/SegmentFunnelStageFilter.kt | 22 + .../client/model/predict/SegmentNameParam.kt | 17 + .../model/predict/SegmentOperandAffinity.kt | 19 + .../predict/SegmentOperandFunnelStage.kt | 19 + .../model/predict/SegmentOperandOrderValue.kt | 19 + .../model/predict/SegmentOperandProperty.kt | 19 + .../model/predict/SegmentOrderValueFilter.kt | 19 + .../predict/SegmentParentConditionOperands.kt | 162 + .../model/predict/SegmentParentConditions.kt | 19 + .../model/predict/SegmentPropertyFilter.kt | 19 + .../predict/SegmentPropertyFilterValue.kt | 7 + .../client/model/predict/SegmentStatus.kt | 22 + .../client/model/predict/SegmentType.kt | 19 + .../algolia/client/model/predict/Segments.kt | 21 + .../client/model/predict/TypesToRetrieve.kt | 16 + .../model/predict/TypesToRetrieveParam.kt | 16 + .../predict/UpdateModelInstanceResponse.kt | 21 + .../client/model/predict/UpdateModelParams.kt | 23 + .../model/predict/UpdateSegmentParams.kt | 106 + .../model/predict/UpdateSegmentResponse.kt | 25 + .../client/model/predict/UserProfile.kt | 25 + .../model/querysuggestions/ErrorBase.kt | 46 + .../model/querysuggestions/IndexName.kt | 17 + .../client/model/querysuggestions/LogFile.kt | 28 + .../client/model/querysuggestions/LogLevel.kt | 22 + .../querysuggestions/QuerySuggestionsIndex.kt | 29 + .../QuerySuggestionsIndexParam.kt | 25 + .../QuerySuggestionsIndexWithIndexParam.kt | 29 + .../model/querysuggestions/SourceIndex.kt | 41 + .../querysuggestions/SourceIndexExternal.kt | 21 + .../SourceIndexWithReplicas.kt | 45 + .../client/model/querysuggestions/Status.kt | 25 + .../model/querysuggestions/SuccessResponse.kt | 21 + .../model/recommend/AdvancedSyntaxFeatures.kt | 16 + .../model/recommend/AlternativesAsExact.kt | 19 + .../client/model/recommend/AroundRadius.kt | 76 + .../client/model/recommend/AroundRadiusAll.kt | 13 + .../model/recommend/BaseRecommendRequest.kt | 31 + .../recommend/BaseRecommendationRequest.kt | 20 + .../model/recommend/BaseSearchParams.kt | 143 + .../recommend/BaseSearchParamsWithoutQuery.kt | 139 + .../model/recommend/BaseSearchResponse.kt | 115 + .../recommend/BaseSearchResponseRedirect.kt | 16 + .../model/recommend/BaseTrendingRequest.kt | 24 + .../client/model/recommend/Distinct.kt | 83 + .../client/model/recommend/ErrorBase.kt | 46 + .../model/recommend/ExactOnSingleWordQuery.kt | 22 + .../client/model/recommend/FacetFilters.kt | 83 + .../client/model/recommend/FacetOrdering.kt | 20 + .../algolia/client/model/recommend/Facets.kt | 17 + .../client/model/recommend/FacetsStats.kt | 29 + .../recommend/GetRecommendationsParams.kt | 17 + .../recommend/GetRecommendationsResponse.kt | 16 + .../client/model/recommend/HighlightResult.kt | 91 + .../model/recommend/HighlightResultOption.kt | 28 + .../client/model/recommend/IgnorePlurals.kt | 83 + .../recommend/IndexSettingsAsSearchParams.kt | 183 + ...dexSettingsAsSearchParamsSemanticSearch.kt | 17 + .../client/model/recommend/MatchLevel.kt | 22 + .../model/recommend/MatchedGeoLocation.kt | 25 + .../model/recommend/MixedSearchFilters.kt | 83 + .../algolia/client/model/recommend/Mode.kt | 19 + .../client/model/recommend/NumericFilters.kt | 83 + .../client/model/recommend/OptionalFilters.kt | 83 + .../client/model/recommend/Personalization.kt | 25 + .../client/model/recommend/QueryType.kt | 22 + .../client/model/recommend/RankingInfo.kt | 63 + .../model/recommend/ReRankingApplyFilter.kt | 83 + .../client/model/recommend/RecommendHit.kt | 80 + .../client/model/recommend/RecommendHits.kt | 16 + .../model/recommend/RecommendationModels.kt | 19 + .../model/recommend/RecommendationRequest.kt | 38 + .../model/recommend/RecommendationsRequest.kt | 120 + .../recommend/RecommendationsResponse.kt | 118 + .../recommend/RedirectRuleIndexMetadata.kt | 32 + .../RedirectRuleIndexMetadataData.kt | 16 + .../client/model/recommend/RemoveStopWords.kt | 83 + .../model/recommend/RemoveWordsIfNoResults.kt | 25 + .../model/recommend/RenderingContent.kt | 16 + .../model/recommend/SearchParamsObject.kt | 313 ++ .../model/recommend/SearchParamsQuery.kt | 17 + .../client/model/recommend/SnippetResult.kt | 85 + .../model/recommend/SnippetResultOption.kt | 20 + .../client/model/recommend/SortRemainingBy.kt | 22 + .../client/model/recommend/TagFilters.kt | 83 + .../client/model/recommend/TrendingModels.kt | 19 + .../client/model/recommend/TrendingRequest.kt | 42 + .../client/model/recommend/TypoTolerance.kt | 76 + .../model/recommend/TypoToleranceEnum.kt | 16 + .../algolia/client/model/recommend/Value.kt | 20 + .../com/algolia/client/model/search/Acl.kt | 55 + .../com/algolia/client/model/search/Action.kt | 34 + .../client/model/search/AddApiKeyResponse.kt | 21 + .../model/search/AdvancedSyntaxFeatures.kt | 16 + .../model/search/AlternativesAsExact.kt | 19 + .../algolia/client/model/search/Anchoring.kt | 25 + .../com/algolia/client/model/search/ApiKey.kt | 45 + .../client/model/search/AroundRadius.kt | 76 + .../client/model/search/AroundRadiusAll.kt | 13 + .../client/model/search/AssignUserIdParams.kt | 17 + .../client/model/search/AttributeToUpdate.kt | 85 + .../model/search/AutomaticFacetFilter.kt | 25 + .../model/search/AutomaticFacetFilters.kt | 83 + .../model/search/BaseGetApiKeyResponse.kt | 21 + .../client/model/search/BaseIndexSettings.kt | 73 + .../client/model/search/BaseSearchParams.kt | 143 + .../search/BaseSearchParamsWithoutQuery.kt | 139 + .../client/model/search/BaseSearchResponse.kt | 115 + .../search/BaseSearchResponseRedirect.kt | 16 + .../model/search/BatchAssignUserIdsParams.kt | 21 + .../search/BatchDictionaryEntriesParams.kt | 21 + .../search/BatchDictionaryEntriesRequest.kt | 19 + .../client/model/search/BatchParams.kt | 16 + .../client/model/search/BatchRequest.kt | 20 + .../client/model/search/BatchResponse.kt | 21 + .../client/model/search/BatchWriteParams.kt | 16 + .../client/model/search/BrowseParams.kt | 318 ++ .../client/model/search/BrowseParamsObject.kt | 317 ++ .../client/model/search/BrowseResponse.kt | 122 + .../client/model/search/BuiltInOperation.kt | 20 + .../model/search/BuiltInOperationType.kt | 34 + .../algolia/client/model/search/Condition.kt | 28 + .../client/model/search/Consequence.kt | 32 + .../client/model/search/ConsequenceHide.kt | 17 + .../client/model/search/ConsequenceParams.kt | 318 ++ .../client/model/search/ConsequenceQuery.kt | 85 + .../model/search/ConsequenceQueryObject.kt | 21 + .../client/model/search/CreatedAtResponse.kt | 17 + .../com/algolia/client/model/search/Cursor.kt | 17 + .../model/search/DeleteApiKeyResponse.kt | 17 + .../client/model/search/DeleteByParams.kt | 41 + .../model/search/DeleteSourceResponse.kt | 17 + .../client/model/search/DeletedAtResponse.kt | 21 + .../client/model/search/DictionaryAction.kt | 19 + .../client/model/search/DictionaryEntry.kt | 81 + .../model/search/DictionaryEntryState.kt | 19 + .../client/model/search/DictionaryLanguage.kt | 17 + .../model/search/DictionarySettingsParams.kt | 16 + .../client/model/search/DictionaryType.kt | 19 + .../algolia/client/model/search/Distinct.kt | 83 + .../com/algolia/client/model/search/Edit.kt | 24 + .../algolia/client/model/search/EditType.kt | 19 + .../algolia/client/model/search/ErrorBase.kt | 46 + .../model/search/ExactOnSingleWordQuery.kt | 22 + .../client/model/search/FacetFilters.kt | 83 + .../algolia/client/model/search/FacetHits.kt | 25 + .../client/model/search/FacetOrdering.kt | 20 + .../com/algolia/client/model/search/Facets.kt | 17 + .../client/model/search/FacetsStats.kt | 29 + .../client/model/search/FetchedIndex.kt | 57 + .../client/model/search/GetApiKeyResponse.kt | 53 + .../search/GetDictionarySettingsResponse.kt | 16 + .../client/model/search/GetLogsResponse.kt | 16 + .../client/model/search/GetObjectsParams.kt | 16 + .../client/model/search/GetObjectsRequest.kt | 25 + .../client/model/search/GetObjectsResponse.kt | 17 + .../client/model/search/GetTaskResponse.kt | 16 + .../model/search/GetTopUserIdsResponse.kt | 17 + .../search/HasPendingMappingsResponse.kt | 21 + .../client/model/search/HighlightResult.kt | 91 + .../model/search/HighlightResultOption.kt | 28 + .../com/algolia/client/model/search/Hit.kt | 73 + .../client/model/search/IgnorePlurals.kt | 83 + .../client/model/search/IndexSettings.kt | 243 ++ .../search/IndexSettingsAsSearchParams.kt | 183 + ...dexSettingsAsSearchParamsSemanticSearch.kt | 17 + .../algolia/client/model/search/Languages.kt | 22 + .../model/search/ListApiKeysResponse.kt | 17 + .../model/search/ListClustersResponse.kt | 17 + .../model/search/ListIndicesResponse.kt | 21 + .../model/search/ListUserIdsResponse.kt | 17 + .../com/algolia/client/model/search/Log.kt | 73 + .../algolia/client/model/search/LogQuery.kt | 25 + .../algolia/client/model/search/LogType.kt | 22 + .../algolia/client/model/search/MatchLevel.kt | 22 + .../client/model/search/MatchedGeoLocation.kt | 25 + .../client/model/search/MixedSearchFilters.kt | 83 + .../com/algolia/client/model/search/Mode.kt | 19 + .../model/search/MultipleBatchRequest.kt | 24 + .../model/search/MultipleBatchResponse.kt | 21 + .../client/model/search/NumericFilters.kt | 83 + .../model/search/OperationIndexParams.kt | 24 + .../client/model/search/OperationType.kt | 19 + .../client/model/search/OptionalFilters.kt | 83 + .../com/algolia/client/model/search/Params.kt | 25 + .../client/model/search/Personalization.kt | 25 + .../algolia/client/model/search/Promote.kt | 87 + .../client/model/search/PromoteObjectID.kt | 21 + .../client/model/search/PromoteObjectIDs.kt | 21 + .../algolia/client/model/search/QueryType.kt | 22 + .../client/model/search/RankingInfo.kt | 63 + .../model/search/ReRankingApplyFilter.kt | 83 + .../model/search/RedirectRuleIndexMetadata.kt | 32 + .../search/RedirectRuleIndexMetadataData.kt | 16 + .../client/model/search/RemoveStopWords.kt | 83 + .../model/search/RemoveUserIdResponse.kt | 17 + .../model/search/RemoveWordsIfNoResults.kt | 25 + .../client/model/search/RenderingContent.kt | 16 + .../model/search/ReplaceSourceResponse.kt | 17 + .../com/algolia/client/model/search/Rule.kt | 36 + .../client/model/search/SaveObjectResponse.kt | 24 + .../model/search/SaveSynonymResponse.kt | 25 + .../algolia/client/model/search/ScopeType.kt | 19 + .../search/SearchDictionaryEntriesParams.kt | 29 + .../search/SearchForFacetValuesRequest.kt | 25 + .../search/SearchForFacetValuesResponse.kt | 16 + .../client/model/search/SearchForFacets.kt | 332 ++ .../model/search/SearchForFacetsOptions.kt | 32 + .../client/model/search/SearchForHits.kt | 324 ++ .../model/search/SearchForHitsOptions.kt | 20 + .../algolia/client/model/search/SearchHits.kt | 16 + .../client/model/search/SearchMethodParams.kt | 19 + .../client/model/search/SearchParams.kt | 315 ++ .../client/model/search/SearchParamsObject.kt | 313 ++ .../client/model/search/SearchParamsQuery.kt | 17 + .../client/model/search/SearchParamsString.kt | 17 + .../client/model/search/SearchQuery.kt | 573 +++ .../client/model/search/SearchResponse.kt | 118 + .../client/model/search/SearchResponses.kt | 16 + .../client/model/search/SearchRulesParams.kt | 40 + .../model/search/SearchRulesResponse.kt | 29 + .../client/model/search/SearchStrategy.kt | 16 + .../model/search/SearchSynonymsParams.kt | 17 + .../model/search/SearchSynonymsResponse.kt | 54 + .../client/model/search/SearchTypeDefault.kt | 16 + .../client/model/search/SearchTypeFacet.kt | 16 + .../model/search/SearchUserIdsParams.kt | 29 + .../model/search/SearchUserIdsResponse.kt | 33 + .../client/model/search/SnippetResult.kt | 85 + .../model/search/SnippetResultOption.kt | 20 + .../client/model/search/SortRemainingBy.kt | 22 + .../com/algolia/client/model/search/Source.kt | 21 + .../client/model/search/StandardEntries.kt | 25 + .../algolia/client/model/search/SynonymHit.kt | 44 + .../client/model/search/SynonymType.kt | 28 + .../algolia/client/model/search/TagFilters.kt | 83 + .../algolia/client/model/search/TaskStatus.kt | 16 + .../algolia/client/model/search/TimeRange.kt | 21 + .../client/model/search/TypoTolerance.kt | 76 + .../client/model/search/TypoToleranceEnum.kt | 16 + .../model/search/UpdateApiKeyResponse.kt | 21 + .../client/model/search/UpdatedAtResponse.kt | 21 + .../search/UpdatedAtWithObjectIdResponse.kt | 25 + .../model/search/UpdatedRuleResponse.kt | 25 + .../model/search/UserHighlightResult.kt | 21 + .../algolia/client/model/search/UserHit.kt | 36 + .../com/algolia/client/model/search/UserId.kt | 29 + .../com/algolia/client/model/search/Value.kt | 20 + .../gradle.properties | 28 + .../tests/methods/requests/analytics_test.go | 1562 ++++++++ .../go/tests/methods/requests/common.go | 35 + .../tests/methods/requests/ingestion_test.go | 1609 +++++++++ .../tests/methods/requests/insights_test.go | 554 +++ .../methods/requests/personalization_test.go | 653 ++++ .../go/tests/methods/requests/predict_test.go | 1354 +++++++ .../requests/query-suggestions_test.go | 753 ++++ .../tests/methods/requests/recommend_test.go | 661 ++++ .../go/tests/methods/requests/search_test.go | 3201 +++++++++++++++++ .../com/algolia/client/AbtestingTest.kt | 101 + .../com/algolia/client/AnalyticsTest.kt | 111 + .../com/algolia/client/IngestionTest.kt | 86 + .../kotlin/com/algolia/client/InsightsTest.kt | 103 + .../com/algolia/client/PersonalizationTest.kt | 83 + .../kotlin/com/algolia/client/PredictTest.kt | 83 + .../algolia/client/QuerySuggestionsTest.kt | 83 + .../com/algolia/client/RecommendTest.kt | 94 + .../kotlin/com/algolia/client/SearchTest.kt | 145 + .../algolia/methods/requests/AbtestingTest.kt | 561 +++ .../algolia/methods/requests/AnalyticsTest.kt | 1151 ++++++ .../algolia/methods/requests/IngestionTest.kt | 1111 ++++++ .../algolia/methods/requests/InsightsTest.kt | 488 +++ .../methods/requests/PersonalizationTest.kt | 525 +++ .../algolia/methods/requests/PredictTest.kt | 1118 ++++++ .../methods/requests/QuerySuggestionsTest.kt | 600 +++ .../algolia/methods/requests/RecommendTest.kt | 664 ++++ .../algolia/methods/requests/SearchTest.kt | 2833 +++++++++++++++ 807 files changed, 50588 insertions(+), 2104 deletions(-) create mode 100644 clients/algoliasearch-client-kotlin/client-bom/README.md create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/BuildConfig.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/AbtestingClient.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/AnalyticsClient.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/ApiClient.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/IngestionClient.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/InsightsClient.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/PersonalizationClient.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/PredictClient.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/QuerySuggestionsClient.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/RecommendClient.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/SearchClient.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/ABTest.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/ABTestResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/AbTestsVariant.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/AbTestsVariantSearchParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/AddABTestsRequest.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/AddABTestsVariant.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/CustomSearchParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/ErrorBase.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/ListABTestsResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/Variant.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/AverageClickEvent.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/ClickPosition.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/ClickThroughRateEvent.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/ConversionRateEvent.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/Direction.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/ErrorBase.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetAverageClickPositionResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetClickPositionsResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetClickThroughRateResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetConversationRateResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetNoClickRateResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetNoResultsRateResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetSearchesCountResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetSearchesNoClicksResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetSearchesNoResultsResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetStatusResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopCountriesResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopFilterAttribute.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopFilterAttributesResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopFilterForAttribute.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopFilterForAttributeResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopFiltersNoResultsResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopFiltersNoResultsValue.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopFiltersNoResultsValues.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopHitsResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopSearchesResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetUsersCountResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/NoClickRateEvent.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/NoResultsRateEvent.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/OrderBy.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/SearchEvent.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/SearchNoClickEvent.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/SearchNoResultEvent.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopCountry.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopHit.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopHitWithAnalytics.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopHitsResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopHitsResponseWithAnalytics.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopSearch.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopSearchWithAnalytics.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopSearchesResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopSearchesResponseWithAnalytics.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/UserWithDate.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ActionType.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthAPIKey.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthAlgolia.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthBasic.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthGoogleServiceAccount.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthInput.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthOAuth.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Authentication.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationCreate.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationCreateResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationInput.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationSearch.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationSortKeys.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationType.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationUpdate.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationUpdateResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationWithInput.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/BigCommerceChannel.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/BigQueryDataType.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DeleteResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Destination.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationCreate.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationCreateResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationIndexName.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationIndexPrefix.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationInput.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationSearch.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationSortKeys.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationType.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationUpdate.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationUpdateResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ErrorBase.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Event.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/EventSortKeys.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/EventStatus.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/EventType.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ListAuthenticationsResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ListDestinationsResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ListEventsResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ListSourcesResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ListTasksResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/MappingTypeCSV.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/MethodType.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/OnDemandTrigger.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/OnDemandTriggerInput.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/OnDemandTriggerType.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/OrderKeys.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Pagination.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Platform.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/PlatformNone.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/PlatformWithNone.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Run.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/RunListResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/RunOutcome.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/RunProgress.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/RunResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/RunSortKeys.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/RunStatus.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/RunType.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ScheduleTrigger.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ScheduleTriggerInput.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ScheduleTriggerType.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Source.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceBigCommerce.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceBigQuery.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceCSV.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceCommercetools.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceCreate.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceCreateResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceInput.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceJSON.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceSearch.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceSortKeys.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceType.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceUpdate.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceUpdateCommercetools.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceUpdateInput.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceUpdateResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SubscriptionTrigger.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SubscriptionTriggerType.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Task.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TaskCreate.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TaskCreateResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TaskCreateTrigger.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TaskSearch.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TaskSortKeys.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TaskUpdate.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TaskUpdateResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Trigger.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TriggerInput.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TriggerType.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/insights/ErrorBase.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/insights/EventType.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/insights/InsightEvent.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/insights/InsightEvents.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/insights/PushEventsResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/personalization/DeleteUserProfileResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/personalization/ErrorBase.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/personalization/EventScoring.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/personalization/FacetScoring.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/personalization/GetUserTokenResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/personalization/PersonalizationStrategyParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/personalization/SetPersonalizationStrategyResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ActivateModelInstanceResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ActivateModelParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/Affinity.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/AllParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/AllUpdateSegmentParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/CompatibleSources.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/CreateSegmentParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/CreateSegmentResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/DeleteModelInstanceResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/DeleteSegmentResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/DeleteUserProfileResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/Error.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ErrorBase.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/FetchAllUserProfilesParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/FetchAllUserProfilesResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/FunnelStage.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/GetAvailableModelTypesResponseInner.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/GetAvailableModelTypesResponseInnerDataRequirements.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/GetModelInstanceConfigStatus.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/GetModelMetricsResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/GetSegmentUsersResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/LimitParam.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ModelAttributes.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ModelInstance.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ModelMetrics.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ModelStatus.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ModelsToRetrieve.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ModelsToRetrieveParam.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/NextPageTokenParam.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/Params.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PredictionAffinityValue.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/Predictions.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PredictionsAffinities.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PredictionsAffinitiesSuccess.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PredictionsFunnelStage.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PredictionsFunnelStageSuccess.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PredictionsOrderValue.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PredictionsOrderValueSuccess.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PreviousPageTokenParam.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/Properties.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/Segment.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentAffinityFilter.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentAffinityFilterValue.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentChildConditionOperands.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentChildConditions.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentConditionOperator.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentConditionsParam.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentFilterOperatorBoolean.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentFilterOperatorNumerical.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentFilterProbability.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentFunnelStageFilter.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentNameParam.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentOperandAffinity.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentOperandFunnelStage.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentOperandOrderValue.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentOperandProperty.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentOrderValueFilter.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentParentConditionOperands.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentParentConditions.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentPropertyFilter.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentPropertyFilterValue.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentStatus.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentType.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/Segments.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/TypesToRetrieve.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/TypesToRetrieveParam.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/UpdateModelInstanceResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/UpdateModelParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/UpdateSegmentParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/UpdateSegmentResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/UserProfile.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/ErrorBase.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/IndexName.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/LogFile.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/LogLevel.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/QuerySuggestionsIndex.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/QuerySuggestionsIndexParam.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/QuerySuggestionsIndexWithIndexParam.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/SourceIndex.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/SourceIndexExternal.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/SourceIndexWithReplicas.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/Status.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/SuccessResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/AdvancedSyntaxFeatures.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/AlternativesAsExact.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/AroundRadius.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/AroundRadiusAll.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/BaseRecommendRequest.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/BaseRecommendationRequest.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/BaseSearchParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/BaseSearchParamsWithoutQuery.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/BaseSearchResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/BaseSearchResponseRedirect.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/BaseTrendingRequest.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/Distinct.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/ErrorBase.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/ExactOnSingleWordQuery.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/FacetFilters.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/FacetOrdering.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/Facets.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/FacetsStats.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/GetRecommendationsParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/GetRecommendationsResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/HighlightResult.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/HighlightResultOption.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/IgnorePlurals.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/IndexSettingsAsSearchParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/IndexSettingsAsSearchParamsSemanticSearch.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/MatchLevel.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/MatchedGeoLocation.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/MixedSearchFilters.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/Mode.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/NumericFilters.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/OptionalFilters.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/Personalization.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/QueryType.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RankingInfo.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/ReRankingApplyFilter.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RecommendHit.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RecommendHits.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RecommendationModels.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RecommendationRequest.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RecommendationsRequest.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RecommendationsResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RedirectRuleIndexMetadata.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RedirectRuleIndexMetadataData.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RemoveStopWords.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RemoveWordsIfNoResults.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RenderingContent.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/SearchParamsObject.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/SearchParamsQuery.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/SnippetResult.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/SnippetResultOption.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/SortRemainingBy.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/TagFilters.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/TrendingModels.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/TrendingRequest.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/TypoTolerance.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/TypoToleranceEnum.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/Value.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Acl.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Action.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AddApiKeyResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AdvancedSyntaxFeatures.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AlternativesAsExact.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Anchoring.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ApiKey.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AroundRadius.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AroundRadiusAll.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AssignUserIdParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AttributeToUpdate.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AutomaticFacetFilter.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AutomaticFacetFilters.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BaseGetApiKeyResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BaseIndexSettings.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BaseSearchParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BaseSearchParamsWithoutQuery.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BaseSearchResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BaseSearchResponseRedirect.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BatchAssignUserIdsParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BatchDictionaryEntriesParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BatchDictionaryEntriesRequest.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BatchParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BatchRequest.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BatchResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BatchWriteParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BrowseParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BrowseParamsObject.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BrowseResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BuiltInOperation.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BuiltInOperationType.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Condition.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Consequence.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ConsequenceHide.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ConsequenceParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ConsequenceQuery.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ConsequenceQueryObject.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/CreatedAtResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Cursor.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DeleteApiKeyResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DeleteByParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DeleteSourceResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DeletedAtResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DictionaryAction.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DictionaryEntry.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DictionaryEntryState.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DictionaryLanguage.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DictionarySettingsParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DictionaryType.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Distinct.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Edit.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/EditType.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ErrorBase.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ExactOnSingleWordQuery.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/FacetFilters.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/FacetHits.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/FacetOrdering.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Facets.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/FacetsStats.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/FetchedIndex.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetApiKeyResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetDictionarySettingsResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetLogsResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetObjectsParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetObjectsRequest.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetObjectsResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetTaskResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetTopUserIdsResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/HasPendingMappingsResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/HighlightResult.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/HighlightResultOption.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Hit.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/IgnorePlurals.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/IndexSettings.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/IndexSettingsAsSearchParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/IndexSettingsAsSearchParamsSemanticSearch.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Languages.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ListApiKeysResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ListClustersResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ListIndicesResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ListUserIdsResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Log.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/LogQuery.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/LogType.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/MatchLevel.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/MatchedGeoLocation.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/MixedSearchFilters.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Mode.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/MultipleBatchRequest.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/MultipleBatchResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/NumericFilters.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/OperationIndexParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/OperationType.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/OptionalFilters.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Params.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Personalization.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Promote.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/PromoteObjectID.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/PromoteObjectIDs.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/QueryType.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/RankingInfo.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ReRankingApplyFilter.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/RedirectRuleIndexMetadata.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/RedirectRuleIndexMetadataData.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/RemoveStopWords.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/RemoveUserIdResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/RemoveWordsIfNoResults.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/RenderingContent.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ReplaceSourceResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Rule.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SaveObjectResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SaveSynonymResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ScopeType.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchDictionaryEntriesParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchForFacetValuesRequest.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchForFacetValuesResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchForFacets.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchForFacetsOptions.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchForHits.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchForHitsOptions.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchHits.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchMethodParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchParamsObject.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchParamsQuery.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchParamsString.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchQuery.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchResponses.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchRulesParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchRulesResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchStrategy.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchSynonymsParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchSynonymsResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchTypeDefault.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchTypeFacet.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchUserIdsParams.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchUserIdsResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SnippetResult.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SnippetResultOption.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SortRemainingBy.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Source.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/StandardEntries.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SynonymHit.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SynonymType.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/TagFilters.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/TaskStatus.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/TimeRange.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/TypoTolerance.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/TypoToleranceEnum.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/UpdateApiKeyResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/UpdatedAtResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/UpdatedAtWithObjectIdResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/UpdatedRuleResponse.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/UserHighlightResult.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/UserHit.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/UserId.kt create mode 100644 clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Value.kt create mode 100644 clients/algoliasearch-client-kotlin/gradle.properties create mode 100644 tests/output/go/tests/methods/requests/analytics_test.go create mode 100644 tests/output/go/tests/methods/requests/common.go create mode 100644 tests/output/go/tests/methods/requests/ingestion_test.go create mode 100644 tests/output/go/tests/methods/requests/insights_test.go create mode 100644 tests/output/go/tests/methods/requests/personalization_test.go create mode 100644 tests/output/go/tests/methods/requests/predict_test.go create mode 100644 tests/output/go/tests/methods/requests/query-suggestions_test.go create mode 100644 tests/output/go/tests/methods/requests/recommend_test.go create mode 100644 tests/output/go/tests/methods/requests/search_test.go create mode 100644 tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/AbtestingTest.kt create mode 100644 tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/AnalyticsTest.kt create mode 100644 tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/IngestionTest.kt create mode 100644 tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/InsightsTest.kt create mode 100644 tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/PersonalizationTest.kt create mode 100644 tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/PredictTest.kt create mode 100644 tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/QuerySuggestionsTest.kt create mode 100644 tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/RecommendTest.kt create mode 100644 tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/SearchTest.kt create mode 100644 tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/AbtestingTest.kt create mode 100644 tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/AnalyticsTest.kt create mode 100644 tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/IngestionTest.kt create mode 100644 tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/InsightsTest.kt create mode 100644 tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/PersonalizationTest.kt create mode 100644 tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/PredictTest.kt create mode 100644 tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/QuerySuggestionsTest.kt create mode 100644 tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/RecommendTest.kt create mode 100644 tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/SearchTest.kt diff --git a/clients/algoliasearch-client-go/algolia/analytics/api_analytics.go b/clients/algoliasearch-client-go/algolia/analytics/api_analytics.go index b98fbd834a..624d08eb26 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/api_analytics.go +++ b/clients/algoliasearch-client-go/algolia/analytics/api_analytics.go @@ -4,6 +4,7 @@ package analytics import ( "bytes" "context" + "encoding/json" "io" "net/http" "net/url" @@ -29,7 +30,7 @@ func QueryParamOption(name string, val any) Option { func HeaderParamOption(name string, val any) Option { return Option{ optionType: "header", - name: "itemsPerPage", + name: name, value: parameterToString(val), } } @@ -39,6 +40,34 @@ type ApiDelRequest struct { parameters map[string]interface{} } +func (r *ApiDelRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + + return nil +} + // Query parameters to be applied to the current query. func (r ApiDelRequest) WithParameters(parameters map[string]interface{}) ApiDelRequest { r.parameters = parameters @@ -66,14 +95,16 @@ func (c *APIClient) Del(r ApiDelRequest, opts ...Option) (map[string]interface{} queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -155,6 +186,34 @@ type ApiGetRequest struct { parameters map[string]interface{} } +func (r *ApiGetRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + + return nil +} + // Query parameters to be applied to the current query. func (r ApiGetRequest) WithParameters(parameters map[string]interface{}) ApiGetRequest { r.parameters = parameters @@ -182,14 +241,16 @@ func (c *APIClient) Get(r ApiGetRequest, opts ...Option) (map[string]interface{} queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -273,6 +334,52 @@ type ApiGetAverageClickPositionRequest struct { tags string } +func (r *ApiGetAverageClickPositionRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["index"]; ok { //index + err = json.Unmarshal(v, &r.index) + if err != nil { + err = json.Unmarshal(b, &r.index) + if err != nil { + return err + } + } + } + if v, ok := req["startDate"]; ok { //startDate + err = json.Unmarshal(v, &r.startDate) + if err != nil { + err = json.Unmarshal(b, &r.startDate) + if err != nil { + return err + } + } + } + if v, ok := req["endDate"]; ok { //endDate + err = json.Unmarshal(v, &r.endDate) + if err != nil { + err = json.Unmarshal(b, &r.endDate) + if err != nil { + return err + } + } + } + if v, ok := req["tags"]; ok { //tags + err = json.Unmarshal(v, &r.tags) + if err != nil { + err = json.Unmarshal(b, &r.tags) + if err != nil { + return err + } + } + } + + return nil +} + // The index name to target. func (r ApiGetAverageClickPositionRequest) WithIndex(index string) ApiGetAverageClickPositionRequest { r.index = index @@ -317,22 +424,22 @@ func (c *APIClient) GetAverageClickPosition(r ApiGetAverageClickPositionRequest, return returnValue, reportError("index is required and must be specified") } - queryParams.Add("index", parameterToString(r.index)) + queryParams.Set("index", parameterToString(r.index)) if !isNilorEmpty(r.startDate) { - queryParams.Add("startDate", parameterToString(r.startDate)) + queryParams.Set("startDate", parameterToString(r.startDate)) } if !isNilorEmpty(r.endDate) { - queryParams.Add("endDate", parameterToString(r.endDate)) + queryParams.Set("endDate", parameterToString(r.endDate)) } if !isNilorEmpty(r.tags) { - queryParams.Add("tags", parameterToString(r.tags)) + queryParams.Set("tags", parameterToString(r.tags)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -416,6 +523,52 @@ type ApiGetClickPositionsRequest struct { tags string } +func (r *ApiGetClickPositionsRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["index"]; ok { //index + err = json.Unmarshal(v, &r.index) + if err != nil { + err = json.Unmarshal(b, &r.index) + if err != nil { + return err + } + } + } + if v, ok := req["startDate"]; ok { //startDate + err = json.Unmarshal(v, &r.startDate) + if err != nil { + err = json.Unmarshal(b, &r.startDate) + if err != nil { + return err + } + } + } + if v, ok := req["endDate"]; ok { //endDate + err = json.Unmarshal(v, &r.endDate) + if err != nil { + err = json.Unmarshal(b, &r.endDate) + if err != nil { + return err + } + } + } + if v, ok := req["tags"]; ok { //tags + err = json.Unmarshal(v, &r.tags) + if err != nil { + err = json.Unmarshal(b, &r.tags) + if err != nil { + return err + } + } + } + + return nil +} + // The index name to target. func (r ApiGetClickPositionsRequest) WithIndex(index string) ApiGetClickPositionsRequest { r.index = index @@ -460,22 +613,22 @@ func (c *APIClient) GetClickPositions(r ApiGetClickPositionsRequest, opts ...Opt return returnValue, reportError("index is required and must be specified") } - queryParams.Add("index", parameterToString(r.index)) + queryParams.Set("index", parameterToString(r.index)) if !isNilorEmpty(r.startDate) { - queryParams.Add("startDate", parameterToString(r.startDate)) + queryParams.Set("startDate", parameterToString(r.startDate)) } if !isNilorEmpty(r.endDate) { - queryParams.Add("endDate", parameterToString(r.endDate)) + queryParams.Set("endDate", parameterToString(r.endDate)) } if !isNilorEmpty(r.tags) { - queryParams.Add("tags", parameterToString(r.tags)) + queryParams.Set("tags", parameterToString(r.tags)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -559,6 +712,52 @@ type ApiGetClickThroughRateRequest struct { tags string } +func (r *ApiGetClickThroughRateRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["index"]; ok { //index + err = json.Unmarshal(v, &r.index) + if err != nil { + err = json.Unmarshal(b, &r.index) + if err != nil { + return err + } + } + } + if v, ok := req["startDate"]; ok { //startDate + err = json.Unmarshal(v, &r.startDate) + if err != nil { + err = json.Unmarshal(b, &r.startDate) + if err != nil { + return err + } + } + } + if v, ok := req["endDate"]; ok { //endDate + err = json.Unmarshal(v, &r.endDate) + if err != nil { + err = json.Unmarshal(b, &r.endDate) + if err != nil { + return err + } + } + } + if v, ok := req["tags"]; ok { //tags + err = json.Unmarshal(v, &r.tags) + if err != nil { + err = json.Unmarshal(b, &r.tags) + if err != nil { + return err + } + } + } + + return nil +} + // The index name to target. func (r ApiGetClickThroughRateRequest) WithIndex(index string) ApiGetClickThroughRateRequest { r.index = index @@ -603,22 +802,22 @@ func (c *APIClient) GetClickThroughRate(r ApiGetClickThroughRateRequest, opts .. return returnValue, reportError("index is required and must be specified") } - queryParams.Add("index", parameterToString(r.index)) + queryParams.Set("index", parameterToString(r.index)) if !isNilorEmpty(r.startDate) { - queryParams.Add("startDate", parameterToString(r.startDate)) + queryParams.Set("startDate", parameterToString(r.startDate)) } if !isNilorEmpty(r.endDate) { - queryParams.Add("endDate", parameterToString(r.endDate)) + queryParams.Set("endDate", parameterToString(r.endDate)) } if !isNilorEmpty(r.tags) { - queryParams.Add("tags", parameterToString(r.tags)) + queryParams.Set("tags", parameterToString(r.tags)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -702,6 +901,52 @@ type ApiGetConversationRateRequest struct { tags string } +func (r *ApiGetConversationRateRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["index"]; ok { //index + err = json.Unmarshal(v, &r.index) + if err != nil { + err = json.Unmarshal(b, &r.index) + if err != nil { + return err + } + } + } + if v, ok := req["startDate"]; ok { //startDate + err = json.Unmarshal(v, &r.startDate) + if err != nil { + err = json.Unmarshal(b, &r.startDate) + if err != nil { + return err + } + } + } + if v, ok := req["endDate"]; ok { //endDate + err = json.Unmarshal(v, &r.endDate) + if err != nil { + err = json.Unmarshal(b, &r.endDate) + if err != nil { + return err + } + } + } + if v, ok := req["tags"]; ok { //tags + err = json.Unmarshal(v, &r.tags) + if err != nil { + err = json.Unmarshal(b, &r.tags) + if err != nil { + return err + } + } + } + + return nil +} + // The index name to target. func (r ApiGetConversationRateRequest) WithIndex(index string) ApiGetConversationRateRequest { r.index = index @@ -746,22 +991,22 @@ func (c *APIClient) GetConversationRate(r ApiGetConversationRateRequest, opts .. return returnValue, reportError("index is required and must be specified") } - queryParams.Add("index", parameterToString(r.index)) + queryParams.Set("index", parameterToString(r.index)) if !isNilorEmpty(r.startDate) { - queryParams.Add("startDate", parameterToString(r.startDate)) + queryParams.Set("startDate", parameterToString(r.startDate)) } if !isNilorEmpty(r.endDate) { - queryParams.Add("endDate", parameterToString(r.endDate)) + queryParams.Set("endDate", parameterToString(r.endDate)) } if !isNilorEmpty(r.tags) { - queryParams.Add("tags", parameterToString(r.tags)) + queryParams.Set("tags", parameterToString(r.tags)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -845,6 +1090,52 @@ type ApiGetNoClickRateRequest struct { tags string } +func (r *ApiGetNoClickRateRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["index"]; ok { //index + err = json.Unmarshal(v, &r.index) + if err != nil { + err = json.Unmarshal(b, &r.index) + if err != nil { + return err + } + } + } + if v, ok := req["startDate"]; ok { //startDate + err = json.Unmarshal(v, &r.startDate) + if err != nil { + err = json.Unmarshal(b, &r.startDate) + if err != nil { + return err + } + } + } + if v, ok := req["endDate"]; ok { //endDate + err = json.Unmarshal(v, &r.endDate) + if err != nil { + err = json.Unmarshal(b, &r.endDate) + if err != nil { + return err + } + } + } + if v, ok := req["tags"]; ok { //tags + err = json.Unmarshal(v, &r.tags) + if err != nil { + err = json.Unmarshal(b, &r.tags) + if err != nil { + return err + } + } + } + + return nil +} + // The index name to target. func (r ApiGetNoClickRateRequest) WithIndex(index string) ApiGetNoClickRateRequest { r.index = index @@ -889,22 +1180,22 @@ func (c *APIClient) GetNoClickRate(r ApiGetNoClickRateRequest, opts ...Option) ( return returnValue, reportError("index is required and must be specified") } - queryParams.Add("index", parameterToString(r.index)) + queryParams.Set("index", parameterToString(r.index)) if !isNilorEmpty(r.startDate) { - queryParams.Add("startDate", parameterToString(r.startDate)) + queryParams.Set("startDate", parameterToString(r.startDate)) } if !isNilorEmpty(r.endDate) { - queryParams.Add("endDate", parameterToString(r.endDate)) + queryParams.Set("endDate", parameterToString(r.endDate)) } if !isNilorEmpty(r.tags) { - queryParams.Add("tags", parameterToString(r.tags)) + queryParams.Set("tags", parameterToString(r.tags)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -988,6 +1279,52 @@ type ApiGetNoResultsRateRequest struct { tags string } +func (r *ApiGetNoResultsRateRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["index"]; ok { //index + err = json.Unmarshal(v, &r.index) + if err != nil { + err = json.Unmarshal(b, &r.index) + if err != nil { + return err + } + } + } + if v, ok := req["startDate"]; ok { //startDate + err = json.Unmarshal(v, &r.startDate) + if err != nil { + err = json.Unmarshal(b, &r.startDate) + if err != nil { + return err + } + } + } + if v, ok := req["endDate"]; ok { //endDate + err = json.Unmarshal(v, &r.endDate) + if err != nil { + err = json.Unmarshal(b, &r.endDate) + if err != nil { + return err + } + } + } + if v, ok := req["tags"]; ok { //tags + err = json.Unmarshal(v, &r.tags) + if err != nil { + err = json.Unmarshal(b, &r.tags) + if err != nil { + return err + } + } + } + + return nil +} + // The index name to target. func (r ApiGetNoResultsRateRequest) WithIndex(index string) ApiGetNoResultsRateRequest { r.index = index @@ -1032,22 +1369,22 @@ func (c *APIClient) GetNoResultsRate(r ApiGetNoResultsRateRequest, opts ...Optio return returnValue, reportError("index is required and must be specified") } - queryParams.Add("index", parameterToString(r.index)) + queryParams.Set("index", parameterToString(r.index)) if !isNilorEmpty(r.startDate) { - queryParams.Add("startDate", parameterToString(r.startDate)) + queryParams.Set("startDate", parameterToString(r.startDate)) } if !isNilorEmpty(r.endDate) { - queryParams.Add("endDate", parameterToString(r.endDate)) + queryParams.Set("endDate", parameterToString(r.endDate)) } if !isNilorEmpty(r.tags) { - queryParams.Add("tags", parameterToString(r.tags)) + queryParams.Set("tags", parameterToString(r.tags)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1131,6 +1468,52 @@ type ApiGetSearchesCountRequest struct { tags string } +func (r *ApiGetSearchesCountRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["index"]; ok { //index + err = json.Unmarshal(v, &r.index) + if err != nil { + err = json.Unmarshal(b, &r.index) + if err != nil { + return err + } + } + } + if v, ok := req["startDate"]; ok { //startDate + err = json.Unmarshal(v, &r.startDate) + if err != nil { + err = json.Unmarshal(b, &r.startDate) + if err != nil { + return err + } + } + } + if v, ok := req["endDate"]; ok { //endDate + err = json.Unmarshal(v, &r.endDate) + if err != nil { + err = json.Unmarshal(b, &r.endDate) + if err != nil { + return err + } + } + } + if v, ok := req["tags"]; ok { //tags + err = json.Unmarshal(v, &r.tags) + if err != nil { + err = json.Unmarshal(b, &r.tags) + if err != nil { + return err + } + } + } + + return nil +} + // The index name to target. func (r ApiGetSearchesCountRequest) WithIndex(index string) ApiGetSearchesCountRequest { r.index = index @@ -1175,22 +1558,22 @@ func (c *APIClient) GetSearchesCount(r ApiGetSearchesCountRequest, opts ...Optio return returnValue, reportError("index is required and must be specified") } - queryParams.Add("index", parameterToString(r.index)) + queryParams.Set("index", parameterToString(r.index)) if !isNilorEmpty(r.startDate) { - queryParams.Add("startDate", parameterToString(r.startDate)) + queryParams.Set("startDate", parameterToString(r.startDate)) } if !isNilorEmpty(r.endDate) { - queryParams.Add("endDate", parameterToString(r.endDate)) + queryParams.Set("endDate", parameterToString(r.endDate)) } if !isNilorEmpty(r.tags) { - queryParams.Add("tags", parameterToString(r.tags)) + queryParams.Set("tags", parameterToString(r.tags)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1276,6 +1659,70 @@ type ApiGetSearchesNoClicksRequest struct { tags string } +func (r *ApiGetSearchesNoClicksRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["index"]; ok { //index + err = json.Unmarshal(v, &r.index) + if err != nil { + err = json.Unmarshal(b, &r.index) + if err != nil { + return err + } + } + } + if v, ok := req["startDate"]; ok { //startDate + err = json.Unmarshal(v, &r.startDate) + if err != nil { + err = json.Unmarshal(b, &r.startDate) + if err != nil { + return err + } + } + } + if v, ok := req["endDate"]; ok { //endDate + err = json.Unmarshal(v, &r.endDate) + if err != nil { + err = json.Unmarshal(b, &r.endDate) + if err != nil { + return err + } + } + } + if v, ok := req["limit"]; ok { //limit + err = json.Unmarshal(v, &r.limit) + if err != nil { + err = json.Unmarshal(b, &r.limit) + if err != nil { + return err + } + } + } + if v, ok := req["offset"]; ok { //offset + err = json.Unmarshal(v, &r.offset) + if err != nil { + err = json.Unmarshal(b, &r.offset) + if err != nil { + return err + } + } + } + if v, ok := req["tags"]; ok { //tags + err = json.Unmarshal(v, &r.tags) + if err != nil { + err = json.Unmarshal(b, &r.tags) + if err != nil { + return err + } + } + } + + return nil +} + // The index name to target. func (r ApiGetSearchesNoClicksRequest) WithIndex(index string) ApiGetSearchesNoClicksRequest { r.index = index @@ -1332,28 +1779,28 @@ func (c *APIClient) GetSearchesNoClicks(r ApiGetSearchesNoClicksRequest, opts .. return returnValue, reportError("index is required and must be specified") } - queryParams.Add("index", parameterToString(r.index)) + queryParams.Set("index", parameterToString(r.index)) if !isNilorEmpty(r.startDate) { - queryParams.Add("startDate", parameterToString(r.startDate)) + queryParams.Set("startDate", parameterToString(r.startDate)) } if !isNilorEmpty(r.endDate) { - queryParams.Add("endDate", parameterToString(r.endDate)) + queryParams.Set("endDate", parameterToString(r.endDate)) } if !isNilorEmpty(r.limit) { - queryParams.Add("limit", parameterToString(r.limit)) + queryParams.Set("limit", parameterToString(r.limit)) } if !isNilorEmpty(r.offset) { - queryParams.Add("offset", parameterToString(r.offset)) + queryParams.Set("offset", parameterToString(r.offset)) } if !isNilorEmpty(r.tags) { - queryParams.Add("tags", parameterToString(r.tags)) + queryParams.Set("tags", parameterToString(r.tags)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1439,6 +1886,70 @@ type ApiGetSearchesNoResultsRequest struct { tags string } +func (r *ApiGetSearchesNoResultsRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["index"]; ok { //index + err = json.Unmarshal(v, &r.index) + if err != nil { + err = json.Unmarshal(b, &r.index) + if err != nil { + return err + } + } + } + if v, ok := req["startDate"]; ok { //startDate + err = json.Unmarshal(v, &r.startDate) + if err != nil { + err = json.Unmarshal(b, &r.startDate) + if err != nil { + return err + } + } + } + if v, ok := req["endDate"]; ok { //endDate + err = json.Unmarshal(v, &r.endDate) + if err != nil { + err = json.Unmarshal(b, &r.endDate) + if err != nil { + return err + } + } + } + if v, ok := req["limit"]; ok { //limit + err = json.Unmarshal(v, &r.limit) + if err != nil { + err = json.Unmarshal(b, &r.limit) + if err != nil { + return err + } + } + } + if v, ok := req["offset"]; ok { //offset + err = json.Unmarshal(v, &r.offset) + if err != nil { + err = json.Unmarshal(b, &r.offset) + if err != nil { + return err + } + } + } + if v, ok := req["tags"]; ok { //tags + err = json.Unmarshal(v, &r.tags) + if err != nil { + err = json.Unmarshal(b, &r.tags) + if err != nil { + return err + } + } + } + + return nil +} + // The index name to target. func (r ApiGetSearchesNoResultsRequest) WithIndex(index string) ApiGetSearchesNoResultsRequest { r.index = index @@ -1495,28 +2006,28 @@ func (c *APIClient) GetSearchesNoResults(r ApiGetSearchesNoResultsRequest, opts return returnValue, reportError("index is required and must be specified") } - queryParams.Add("index", parameterToString(r.index)) + queryParams.Set("index", parameterToString(r.index)) if !isNilorEmpty(r.startDate) { - queryParams.Add("startDate", parameterToString(r.startDate)) + queryParams.Set("startDate", parameterToString(r.startDate)) } if !isNilorEmpty(r.endDate) { - queryParams.Add("endDate", parameterToString(r.endDate)) + queryParams.Set("endDate", parameterToString(r.endDate)) } if !isNilorEmpty(r.limit) { - queryParams.Add("limit", parameterToString(r.limit)) + queryParams.Set("limit", parameterToString(r.limit)) } if !isNilorEmpty(r.offset) { - queryParams.Add("offset", parameterToString(r.offset)) + queryParams.Set("offset", parameterToString(r.offset)) } if !isNilorEmpty(r.tags) { - queryParams.Add("tags", parameterToString(r.tags)) + queryParams.Set("tags", parameterToString(r.tags)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1597,6 +2108,25 @@ type ApiGetStatusRequest struct { index string } +func (r *ApiGetStatusRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["index"]; ok { //index + err = json.Unmarshal(v, &r.index) + if err != nil { + err = json.Unmarshal(b, &r.index) + if err != nil { + return err + } + } + } + + return nil +} + // The index name to target. func (r ApiGetStatusRequest) WithIndex(index string) ApiGetStatusRequest { r.index = index @@ -1623,13 +2153,13 @@ func (c *APIClient) GetStatus(r ApiGetStatusRequest, opts ...Option) (*GetStatus return returnValue, reportError("index is required and must be specified") } - queryParams.Add("index", parameterToString(r.index)) + queryParams.Set("index", parameterToString(r.index)) // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1715,6 +2245,70 @@ type ApiGetTopCountriesRequest struct { tags string } +func (r *ApiGetTopCountriesRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["index"]; ok { //index + err = json.Unmarshal(v, &r.index) + if err != nil { + err = json.Unmarshal(b, &r.index) + if err != nil { + return err + } + } + } + if v, ok := req["startDate"]; ok { //startDate + err = json.Unmarshal(v, &r.startDate) + if err != nil { + err = json.Unmarshal(b, &r.startDate) + if err != nil { + return err + } + } + } + if v, ok := req["endDate"]; ok { //endDate + err = json.Unmarshal(v, &r.endDate) + if err != nil { + err = json.Unmarshal(b, &r.endDate) + if err != nil { + return err + } + } + } + if v, ok := req["limit"]; ok { //limit + err = json.Unmarshal(v, &r.limit) + if err != nil { + err = json.Unmarshal(b, &r.limit) + if err != nil { + return err + } + } + } + if v, ok := req["offset"]; ok { //offset + err = json.Unmarshal(v, &r.offset) + if err != nil { + err = json.Unmarshal(b, &r.offset) + if err != nil { + return err + } + } + } + if v, ok := req["tags"]; ok { //tags + err = json.Unmarshal(v, &r.tags) + if err != nil { + err = json.Unmarshal(b, &r.tags) + if err != nil { + return err + } + } + } + + return nil +} + // The index name to target. func (r ApiGetTopCountriesRequest) WithIndex(index string) ApiGetTopCountriesRequest { r.index = index @@ -1771,28 +2365,28 @@ func (c *APIClient) GetTopCountries(r ApiGetTopCountriesRequest, opts ...Option) return returnValue, reportError("index is required and must be specified") } - queryParams.Add("index", parameterToString(r.index)) + queryParams.Set("index", parameterToString(r.index)) if !isNilorEmpty(r.startDate) { - queryParams.Add("startDate", parameterToString(r.startDate)) + queryParams.Set("startDate", parameterToString(r.startDate)) } if !isNilorEmpty(r.endDate) { - queryParams.Add("endDate", parameterToString(r.endDate)) + queryParams.Set("endDate", parameterToString(r.endDate)) } if !isNilorEmpty(r.limit) { - queryParams.Add("limit", parameterToString(r.limit)) + queryParams.Set("limit", parameterToString(r.limit)) } if !isNilorEmpty(r.offset) { - queryParams.Add("offset", parameterToString(r.offset)) + queryParams.Set("offset", parameterToString(r.offset)) } if !isNilorEmpty(r.tags) { - queryParams.Add("tags", parameterToString(r.tags)) + queryParams.Set("tags", parameterToString(r.tags)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1879,6 +2473,79 @@ type ApiGetTopFilterAttributesRequest struct { tags string } +func (r *ApiGetTopFilterAttributesRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["index"]; ok { //index + err = json.Unmarshal(v, &r.index) + if err != nil { + err = json.Unmarshal(b, &r.index) + if err != nil { + return err + } + } + } + if v, ok := req["search"]; ok { //search + err = json.Unmarshal(v, &r.search) + if err != nil { + err = json.Unmarshal(b, &r.search) + if err != nil { + return err + } + } + } + if v, ok := req["startDate"]; ok { //startDate + err = json.Unmarshal(v, &r.startDate) + if err != nil { + err = json.Unmarshal(b, &r.startDate) + if err != nil { + return err + } + } + } + if v, ok := req["endDate"]; ok { //endDate + err = json.Unmarshal(v, &r.endDate) + if err != nil { + err = json.Unmarshal(b, &r.endDate) + if err != nil { + return err + } + } + } + if v, ok := req["limit"]; ok { //limit + err = json.Unmarshal(v, &r.limit) + if err != nil { + err = json.Unmarshal(b, &r.limit) + if err != nil { + return err + } + } + } + if v, ok := req["offset"]; ok { //offset + err = json.Unmarshal(v, &r.offset) + if err != nil { + err = json.Unmarshal(b, &r.offset) + if err != nil { + return err + } + } + } + if v, ok := req["tags"]; ok { //tags + err = json.Unmarshal(v, &r.tags) + if err != nil { + err = json.Unmarshal(b, &r.tags) + if err != nil { + return err + } + } + } + + return nil +} + // The index name to target. func (r ApiGetTopFilterAttributesRequest) WithIndex(index string) ApiGetTopFilterAttributesRequest { r.index = index @@ -1941,31 +2608,31 @@ func (c *APIClient) GetTopFilterAttributes(r ApiGetTopFilterAttributesRequest, o return returnValue, reportError("index is required and must be specified") } - queryParams.Add("index", parameterToString(r.index)) + queryParams.Set("index", parameterToString(r.index)) if !isNilorEmpty(r.search) { - queryParams.Add("search", parameterToString(r.search)) + queryParams.Set("search", parameterToString(r.search)) } if !isNilorEmpty(r.startDate) { - queryParams.Add("startDate", parameterToString(r.startDate)) + queryParams.Set("startDate", parameterToString(r.startDate)) } if !isNilorEmpty(r.endDate) { - queryParams.Add("endDate", parameterToString(r.endDate)) + queryParams.Set("endDate", parameterToString(r.endDate)) } if !isNilorEmpty(r.limit) { - queryParams.Add("limit", parameterToString(r.limit)) + queryParams.Set("limit", parameterToString(r.limit)) } if !isNilorEmpty(r.offset) { - queryParams.Add("offset", parameterToString(r.offset)) + queryParams.Set("offset", parameterToString(r.offset)) } if !isNilorEmpty(r.tags) { - queryParams.Add("tags", parameterToString(r.tags)) + queryParams.Set("tags", parameterToString(r.tags)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -2053,6 +2720,88 @@ type ApiGetTopFilterForAttributeRequest struct { tags string } +func (r *ApiGetTopFilterForAttributeRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["attribute"]; ok { //attribute + err = json.Unmarshal(v, &r.attribute) + if err != nil { + err = json.Unmarshal(b, &r.attribute) + if err != nil { + return err + } + } + } + if v, ok := req["index"]; ok { //index + err = json.Unmarshal(v, &r.index) + if err != nil { + err = json.Unmarshal(b, &r.index) + if err != nil { + return err + } + } + } + if v, ok := req["search"]; ok { //search + err = json.Unmarshal(v, &r.search) + if err != nil { + err = json.Unmarshal(b, &r.search) + if err != nil { + return err + } + } + } + if v, ok := req["startDate"]; ok { //startDate + err = json.Unmarshal(v, &r.startDate) + if err != nil { + err = json.Unmarshal(b, &r.startDate) + if err != nil { + return err + } + } + } + if v, ok := req["endDate"]; ok { //endDate + err = json.Unmarshal(v, &r.endDate) + if err != nil { + err = json.Unmarshal(b, &r.endDate) + if err != nil { + return err + } + } + } + if v, ok := req["limit"]; ok { //limit + err = json.Unmarshal(v, &r.limit) + if err != nil { + err = json.Unmarshal(b, &r.limit) + if err != nil { + return err + } + } + } + if v, ok := req["offset"]; ok { //offset + err = json.Unmarshal(v, &r.offset) + if err != nil { + err = json.Unmarshal(b, &r.offset) + if err != nil { + return err + } + } + } + if v, ok := req["tags"]; ok { //tags + err = json.Unmarshal(v, &r.tags) + if err != nil { + err = json.Unmarshal(b, &r.tags) + if err != nil { + return err + } + } + } + + return nil +} + // The index name to target. func (r ApiGetTopFilterForAttributeRequest) WithIndex(index string) ApiGetTopFilterForAttributeRequest { r.index = index @@ -2118,31 +2867,31 @@ func (c *APIClient) GetTopFilterForAttribute(r ApiGetTopFilterForAttributeReques return returnValue, reportError("index is required and must be specified") } - queryParams.Add("index", parameterToString(r.index)) + queryParams.Set("index", parameterToString(r.index)) if !isNilorEmpty(r.search) { - queryParams.Add("search", parameterToString(r.search)) + queryParams.Set("search", parameterToString(r.search)) } if !isNilorEmpty(r.startDate) { - queryParams.Add("startDate", parameterToString(r.startDate)) + queryParams.Set("startDate", parameterToString(r.startDate)) } if !isNilorEmpty(r.endDate) { - queryParams.Add("endDate", parameterToString(r.endDate)) + queryParams.Set("endDate", parameterToString(r.endDate)) } if !isNilorEmpty(r.limit) { - queryParams.Add("limit", parameterToString(r.limit)) + queryParams.Set("limit", parameterToString(r.limit)) } if !isNilorEmpty(r.offset) { - queryParams.Add("offset", parameterToString(r.offset)) + queryParams.Set("offset", parameterToString(r.offset)) } if !isNilorEmpty(r.tags) { - queryParams.Add("tags", parameterToString(r.tags)) + queryParams.Set("tags", parameterToString(r.tags)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -2229,6 +2978,79 @@ type ApiGetTopFiltersNoResultsRequest struct { tags string } +func (r *ApiGetTopFiltersNoResultsRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["index"]; ok { //index + err = json.Unmarshal(v, &r.index) + if err != nil { + err = json.Unmarshal(b, &r.index) + if err != nil { + return err + } + } + } + if v, ok := req["search"]; ok { //search + err = json.Unmarshal(v, &r.search) + if err != nil { + err = json.Unmarshal(b, &r.search) + if err != nil { + return err + } + } + } + if v, ok := req["startDate"]; ok { //startDate + err = json.Unmarshal(v, &r.startDate) + if err != nil { + err = json.Unmarshal(b, &r.startDate) + if err != nil { + return err + } + } + } + if v, ok := req["endDate"]; ok { //endDate + err = json.Unmarshal(v, &r.endDate) + if err != nil { + err = json.Unmarshal(b, &r.endDate) + if err != nil { + return err + } + } + } + if v, ok := req["limit"]; ok { //limit + err = json.Unmarshal(v, &r.limit) + if err != nil { + err = json.Unmarshal(b, &r.limit) + if err != nil { + return err + } + } + } + if v, ok := req["offset"]; ok { //offset + err = json.Unmarshal(v, &r.offset) + if err != nil { + err = json.Unmarshal(b, &r.offset) + if err != nil { + return err + } + } + } + if v, ok := req["tags"]; ok { //tags + err = json.Unmarshal(v, &r.tags) + if err != nil { + err = json.Unmarshal(b, &r.tags) + if err != nil { + return err + } + } + } + + return nil +} + // The index name to target. func (r ApiGetTopFiltersNoResultsRequest) WithIndex(index string) ApiGetTopFiltersNoResultsRequest { r.index = index @@ -2291,31 +3113,31 @@ func (c *APIClient) GetTopFiltersNoResults(r ApiGetTopFiltersNoResultsRequest, o return returnValue, reportError("index is required and must be specified") } - queryParams.Add("index", parameterToString(r.index)) + queryParams.Set("index", parameterToString(r.index)) if !isNilorEmpty(r.search) { - queryParams.Add("search", parameterToString(r.search)) + queryParams.Set("search", parameterToString(r.search)) } if !isNilorEmpty(r.startDate) { - queryParams.Add("startDate", parameterToString(r.startDate)) + queryParams.Set("startDate", parameterToString(r.startDate)) } if !isNilorEmpty(r.endDate) { - queryParams.Add("endDate", parameterToString(r.endDate)) + queryParams.Set("endDate", parameterToString(r.endDate)) } if !isNilorEmpty(r.limit) { - queryParams.Add("limit", parameterToString(r.limit)) + queryParams.Set("limit", parameterToString(r.limit)) } if !isNilorEmpty(r.offset) { - queryParams.Add("offset", parameterToString(r.offset)) + queryParams.Set("offset", parameterToString(r.offset)) } if !isNilorEmpty(r.tags) { - queryParams.Add("tags", parameterToString(r.tags)) + queryParams.Set("tags", parameterToString(r.tags)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -2403,6 +3225,88 @@ type ApiGetTopHitsRequest struct { tags string } +func (r *ApiGetTopHitsRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["index"]; ok { //index + err = json.Unmarshal(v, &r.index) + if err != nil { + err = json.Unmarshal(b, &r.index) + if err != nil { + return err + } + } + } + if v, ok := req["search"]; ok { //search + err = json.Unmarshal(v, &r.search) + if err != nil { + err = json.Unmarshal(b, &r.search) + if err != nil { + return err + } + } + } + if v, ok := req["clickAnalytics"]; ok { //clickAnalytics + err = json.Unmarshal(v, &r.clickAnalytics) + if err != nil { + err = json.Unmarshal(b, &r.clickAnalytics) + if err != nil { + return err + } + } + } + if v, ok := req["startDate"]; ok { //startDate + err = json.Unmarshal(v, &r.startDate) + if err != nil { + err = json.Unmarshal(b, &r.startDate) + if err != nil { + return err + } + } + } + if v, ok := req["endDate"]; ok { //endDate + err = json.Unmarshal(v, &r.endDate) + if err != nil { + err = json.Unmarshal(b, &r.endDate) + if err != nil { + return err + } + } + } + if v, ok := req["limit"]; ok { //limit + err = json.Unmarshal(v, &r.limit) + if err != nil { + err = json.Unmarshal(b, &r.limit) + if err != nil { + return err + } + } + } + if v, ok := req["offset"]; ok { //offset + err = json.Unmarshal(v, &r.offset) + if err != nil { + err = json.Unmarshal(b, &r.offset) + if err != nil { + return err + } + } + } + if v, ok := req["tags"]; ok { //tags + err = json.Unmarshal(v, &r.tags) + if err != nil { + err = json.Unmarshal(b, &r.tags) + if err != nil { + return err + } + } + } + + return nil +} + // The index name to target. func (r ApiGetTopHitsRequest) WithIndex(index string) ApiGetTopHitsRequest { r.index = index @@ -2471,34 +3375,34 @@ func (c *APIClient) GetTopHits(r ApiGetTopHitsRequest, opts ...Option) (*GetTopH return returnValue, reportError("index is required and must be specified") } - queryParams.Add("index", parameterToString(r.index)) + queryParams.Set("index", parameterToString(r.index)) if !isNilorEmpty(r.search) { - queryParams.Add("search", parameterToString(r.search)) + queryParams.Set("search", parameterToString(r.search)) } if !isNilorEmpty(r.clickAnalytics) { - queryParams.Add("clickAnalytics", parameterToString(r.clickAnalytics)) + queryParams.Set("clickAnalytics", parameterToString(r.clickAnalytics)) } if !isNilorEmpty(r.startDate) { - queryParams.Add("startDate", parameterToString(r.startDate)) + queryParams.Set("startDate", parameterToString(r.startDate)) } if !isNilorEmpty(r.endDate) { - queryParams.Add("endDate", parameterToString(r.endDate)) + queryParams.Set("endDate", parameterToString(r.endDate)) } if !isNilorEmpty(r.limit) { - queryParams.Add("limit", parameterToString(r.limit)) + queryParams.Set("limit", parameterToString(r.limit)) } if !isNilorEmpty(r.offset) { - queryParams.Add("offset", parameterToString(r.offset)) + queryParams.Set("offset", parameterToString(r.offset)) } if !isNilorEmpty(r.tags) { - queryParams.Add("tags", parameterToString(r.tags)) + queryParams.Set("tags", parameterToString(r.tags)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -2587,6 +3491,97 @@ type ApiGetTopSearchesRequest struct { tags string } +func (r *ApiGetTopSearchesRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["index"]; ok { //index + err = json.Unmarshal(v, &r.index) + if err != nil { + err = json.Unmarshal(b, &r.index) + if err != nil { + return err + } + } + } + if v, ok := req["clickAnalytics"]; ok { //clickAnalytics + err = json.Unmarshal(v, &r.clickAnalytics) + if err != nil { + err = json.Unmarshal(b, &r.clickAnalytics) + if err != nil { + return err + } + } + } + if v, ok := req["startDate"]; ok { //startDate + err = json.Unmarshal(v, &r.startDate) + if err != nil { + err = json.Unmarshal(b, &r.startDate) + if err != nil { + return err + } + } + } + if v, ok := req["endDate"]; ok { //endDate + err = json.Unmarshal(v, &r.endDate) + if err != nil { + err = json.Unmarshal(b, &r.endDate) + if err != nil { + return err + } + } + } + if v, ok := req["orderBy"]; ok { //orderBy + err = json.Unmarshal(v, &r.orderBy) + if err != nil { + err = json.Unmarshal(b, &r.orderBy) + if err != nil { + return err + } + } + } + if v, ok := req["direction"]; ok { //direction + err = json.Unmarshal(v, &r.direction) + if err != nil { + err = json.Unmarshal(b, &r.direction) + if err != nil { + return err + } + } + } + if v, ok := req["limit"]; ok { //limit + err = json.Unmarshal(v, &r.limit) + if err != nil { + err = json.Unmarshal(b, &r.limit) + if err != nil { + return err + } + } + } + if v, ok := req["offset"]; ok { //offset + err = json.Unmarshal(v, &r.offset) + if err != nil { + err = json.Unmarshal(b, &r.offset) + if err != nil { + return err + } + } + } + if v, ok := req["tags"]; ok { //tags + err = json.Unmarshal(v, &r.tags) + if err != nil { + err = json.Unmarshal(b, &r.tags) + if err != nil { + return err + } + } + } + + return nil +} + // The index name to target. func (r ApiGetTopSearchesRequest) WithIndex(index string) ApiGetTopSearchesRequest { r.index = index @@ -2612,14 +3607,14 @@ func (r ApiGetTopSearchesRequest) WithEndDate(endDate string) ApiGetTopSearchesR } // Reorder the results. -func (r ApiGetTopSearchesRequest) WithOrderBy(orderBy OrderBy) ApiGetTopSearchesRequest { - r.orderBy = &orderBy +func (r ApiGetTopSearchesRequest) WithOrderBy(orderBy *OrderBy) ApiGetTopSearchesRequest { + r.orderBy = orderBy return r } // The sorting of the result. -func (r ApiGetTopSearchesRequest) WithDirection(direction Direction) ApiGetTopSearchesRequest { - r.direction = &direction +func (r ApiGetTopSearchesRequest) WithDirection(direction *Direction) ApiGetTopSearchesRequest { + r.direction = direction return r } @@ -2661,37 +3656,37 @@ func (c *APIClient) GetTopSearches(r ApiGetTopSearchesRequest, opts ...Option) ( return returnValue, reportError("index is required and must be specified") } - queryParams.Add("index", parameterToString(r.index)) + queryParams.Set("index", parameterToString(r.index)) if !isNilorEmpty(r.clickAnalytics) { - queryParams.Add("clickAnalytics", parameterToString(r.clickAnalytics)) + queryParams.Set("clickAnalytics", parameterToString(r.clickAnalytics)) } if !isNilorEmpty(r.startDate) { - queryParams.Add("startDate", parameterToString(r.startDate)) + queryParams.Set("startDate", parameterToString(r.startDate)) } if !isNilorEmpty(r.endDate) { - queryParams.Add("endDate", parameterToString(r.endDate)) + queryParams.Set("endDate", parameterToString(r.endDate)) } if !isNilorEmpty(r.orderBy) { - queryParams.Add("orderBy", parameterToString(*r.orderBy)) + queryParams.Set("orderBy", parameterToString(*r.orderBy)) } if !isNilorEmpty(r.direction) { - queryParams.Add("direction", parameterToString(*r.direction)) + queryParams.Set("direction", parameterToString(*r.direction)) } if !isNilorEmpty(r.limit) { - queryParams.Add("limit", parameterToString(r.limit)) + queryParams.Set("limit", parameterToString(r.limit)) } if !isNilorEmpty(r.offset) { - queryParams.Add("offset", parameterToString(r.offset)) + queryParams.Set("offset", parameterToString(r.offset)) } if !isNilorEmpty(r.tags) { - queryParams.Add("tags", parameterToString(r.tags)) + queryParams.Set("tags", parameterToString(r.tags)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -2775,6 +3770,52 @@ type ApiGetUsersCountRequest struct { tags string } +func (r *ApiGetUsersCountRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["index"]; ok { //index + err = json.Unmarshal(v, &r.index) + if err != nil { + err = json.Unmarshal(b, &r.index) + if err != nil { + return err + } + } + } + if v, ok := req["startDate"]; ok { //startDate + err = json.Unmarshal(v, &r.startDate) + if err != nil { + err = json.Unmarshal(b, &r.startDate) + if err != nil { + return err + } + } + } + if v, ok := req["endDate"]; ok { //endDate + err = json.Unmarshal(v, &r.endDate) + if err != nil { + err = json.Unmarshal(b, &r.endDate) + if err != nil { + return err + } + } + } + if v, ok := req["tags"]; ok { //tags + err = json.Unmarshal(v, &r.tags) + if err != nil { + err = json.Unmarshal(b, &r.tags) + if err != nil { + return err + } + } + } + + return nil +} + // The index name to target. func (r ApiGetUsersCountRequest) WithIndex(index string) ApiGetUsersCountRequest { r.index = index @@ -2819,22 +3860,22 @@ func (c *APIClient) GetUsersCount(r ApiGetUsersCountRequest, opts ...Option) (*G return returnValue, reportError("index is required and must be specified") } - queryParams.Add("index", parameterToString(r.index)) + queryParams.Set("index", parameterToString(r.index)) if !isNilorEmpty(r.startDate) { - queryParams.Add("startDate", parameterToString(r.startDate)) + queryParams.Set("startDate", parameterToString(r.startDate)) } if !isNilorEmpty(r.endDate) { - queryParams.Add("endDate", parameterToString(r.endDate)) + queryParams.Set("endDate", parameterToString(r.endDate)) } if !isNilorEmpty(r.tags) { - queryParams.Add("tags", parameterToString(r.tags)) + queryParams.Set("tags", parameterToString(r.tags)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -2917,6 +3958,43 @@ type ApiPostRequest struct { body map[string]interface{} } +func (r *ApiPostRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + if v, ok := req["body"]; ok { //body + err = json.Unmarshal(v, &r.body) + if err != nil { + err = json.Unmarshal(b, &r.body) + if err != nil { + return err + } + } + } + + return nil +} + // Query parameters to be applied to the current query. func (r ApiPostRequest) WithParameters(parameters map[string]interface{}) ApiPostRequest { r.parameters = parameters @@ -2950,21 +4028,27 @@ func (c *APIClient) Post(r ApiPostRequest, opts ...Option) (map[string]interface queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } } // body params - postBody = r.body + if isNilorEmpty(r.body) { + postBody = "{}" + } else { + postBody = r.body + } req, err := c.prepareRequest(context.Background(), requestPath, http.MethodPost, postBody, headers, queryParams) if err != nil { return returnValue, err @@ -3042,6 +4126,43 @@ type ApiPutRequest struct { body map[string]interface{} } +func (r *ApiPutRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + if v, ok := req["body"]; ok { //body + err = json.Unmarshal(v, &r.body) + if err != nil { + err = json.Unmarshal(b, &r.body) + if err != nil { + return err + } + } + } + + return nil +} + // Query parameters to be applied to the current query. func (r ApiPutRequest) WithParameters(parameters map[string]interface{}) ApiPutRequest { r.parameters = parameters @@ -3075,21 +4196,27 @@ func (c *APIClient) Put(r ApiPutRequest, opts ...Option) (map[string]interface{} queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } } // body params - postBody = r.body + if isNilorEmpty(r.body) { + postBody = "{}" + } else { + postBody = r.body + } req, err := c.prepareRequest(context.Background(), requestPath, http.MethodPut, postBody, headers, queryParams) if err != nil { return returnValue, err diff --git a/clients/algoliasearch-client-go/algolia/analytics/client.go b/clients/algoliasearch-client-go/algolia/analytics/client.go index 3e314c0ca3..64146b77d9 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/client.go +++ b/clients/algoliasearch-client-go/algolia/analytics/client.go @@ -20,6 +20,8 @@ import ( "strings" "time" + "github.com/go-playground/validator/v10" + "github.com/algolia/algoliasearch-client-go/v4/algolia/call" "github.com/algolia/algoliasearch-client-go/v4/algolia/compression" "github.com/algolia/algoliasearch-client-go/v4/algolia/internal/transport" @@ -132,7 +134,7 @@ func typeCheckParameter(obj any, expected string, name string) error { // parameterToString convert any parameters to string. func parameterToString(obj any) string { if reflect.TypeOf(obj).Kind() == reflect.Slice { - return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", "", -1), "[]") + return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", ",", -1), "[]") } else if t, ok := obj.(time.Time); ok { return t.Format(time.RFC3339) } @@ -231,11 +233,9 @@ func (c *APIClient) prepareRequest( // add header parameters, if any if len(headerParams) > 0 { - headers := http.Header{} for h, v := range headerParams { - headers[h] = []string{v} + req.Header.Add(h, v) } - req.Header = headers } // Add the user agent to the request. @@ -294,6 +294,17 @@ func newStrictDecoder(data []byte) *json.Decoder { return dec } +// A wrapper for validating a struct, returns nil if value is not a struct +func validateStruct(v any) error { + err := validator.New().Struct(v) + validationErrors, ok := err.(validator.ValidationErrors) + if ok && len(validationErrors) > 0 { + return validationErrors + } + + return nil +} + // Set request body from an any func setBody(body any, contentType string, c compression.Compression) (bodyBuf *bytes.Buffer, err error) { if body == nil { diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_average_click_event.go b/clients/algoliasearch-client-go/algolia/analytics/model_average_click_event.go index d01544c093..47ac8cac44 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_average_click_event.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_average_click_event.go @@ -9,11 +9,11 @@ import ( // AverageClickEvent struct for AverageClickEvent type AverageClickEvent struct { // The average of all the click count event. - Average float64 `json:"average"` + Average float64 `json:"average" validate:"required"` // The number of click event. - ClickCount int32 `json:"clickCount"` + ClickCount int32 `json:"clickCount" validate:"required"` // Date of the event. - Date string `json:"date"` + Date string `json:"date" validate:"required"` } // NewAverageClickEvent instantiates a new AverageClickEvent object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_click_position.go b/clients/algoliasearch-client-go/algolia/analytics/model_click_position.go index 454e40cbc0..b633afe747 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_click_position.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_click_position.go @@ -9,9 +9,9 @@ import ( // ClickPosition struct for ClickPosition type ClickPosition struct { // Range of positions with the following pattern: - Positions from 1 to 10 included are displayed in separated groups. - Positions from 11 to 20 included are grouped together. - Positions from 21 and up are grouped together. - Position []int32 `json:"position"` + Position []int32 `json:"position" validate:"required"` // The number of click event. - ClickCount int32 `json:"clickCount"` + ClickCount int32 `json:"clickCount" validate:"required"` } // NewClickPosition instantiates a new ClickPosition object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_click_through_rate_event.go b/clients/algoliasearch-client-go/algolia/analytics/model_click_through_rate_event.go index e356b0d449..4dcc04dc3d 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_click_through_rate_event.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_click_through_rate_event.go @@ -9,13 +9,13 @@ import ( // ClickThroughRateEvent struct for ClickThroughRateEvent type ClickThroughRateEvent struct { // The click-through rate. - Rate float64 `json:"rate"` + Rate float64 `json:"rate" validate:"required"` // The number of click event. - ClickCount int32 `json:"clickCount"` + ClickCount int32 `json:"clickCount" validate:"required"` // The number of tracked search click. - TrackedSearchCount int32 `json:"trackedSearchCount"` + TrackedSearchCount int32 `json:"trackedSearchCount" validate:"required"` // Date of the event. - Date string `json:"date"` + Date string `json:"date" validate:"required"` } // NewClickThroughRateEvent instantiates a new ClickThroughRateEvent object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_conversion_rate_event.go b/clients/algoliasearch-client-go/algolia/analytics/model_conversion_rate_event.go index 84e97771d9..e6116ce299 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_conversion_rate_event.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_conversion_rate_event.go @@ -9,13 +9,13 @@ import ( // ConversionRateEvent struct for ConversionRateEvent type ConversionRateEvent struct { // The click-through rate. - Rate float64 `json:"rate"` + Rate float64 `json:"rate" validate:"required"` // The number of tracked search click. - TrackedSearchCount int32 `json:"trackedSearchCount"` + TrackedSearchCount int32 `json:"trackedSearchCount" validate:"required"` // The number of converted clicks. - ConversionCount int32 `json:"conversionCount"` + ConversionCount int32 `json:"conversionCount" validate:"required"` // Date of the event. - Date string `json:"date"` + Date string `json:"date" validate:"required"` } // NewConversionRateEvent instantiates a new ConversionRateEvent object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_get_average_click_position_response.go b/clients/algoliasearch-client-go/algolia/analytics/model_get_average_click_position_response.go index 09c156e47b..3c1e6eb0ba 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_get_average_click_position_response.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_get_average_click_position_response.go @@ -9,11 +9,11 @@ import ( // GetAverageClickPositionResponse struct for GetAverageClickPositionResponse type GetAverageClickPositionResponse struct { // The average of all the click count event. - Average float64 `json:"average"` + Average float64 `json:"average" validate:"required"` // The number of click event. - ClickCount int32 `json:"clickCount"` + ClickCount int32 `json:"clickCount" validate:"required"` // A list of average click position with their date. - Dates []AverageClickEvent `json:"dates"` + Dates []AverageClickEvent `json:"dates" validate:"required"` } // NewGetAverageClickPositionResponse instantiates a new GetAverageClickPositionResponse object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_get_click_positions_response.go b/clients/algoliasearch-client-go/algolia/analytics/model_get_click_positions_response.go index d56a93bd81..781c28ac30 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_get_click_positions_response.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_get_click_positions_response.go @@ -9,7 +9,7 @@ import ( // GetClickPositionsResponse struct for GetClickPositionsResponse type GetClickPositionsResponse struct { // A list of the click positions with their click count. - Positions []ClickPosition `json:"positions"` + Positions []ClickPosition `json:"positions" validate:"required"` } // NewGetClickPositionsResponse instantiates a new GetClickPositionsResponse object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_get_click_through_rate_response.go b/clients/algoliasearch-client-go/algolia/analytics/model_get_click_through_rate_response.go index ffe0f9e5f1..57858564bf 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_get_click_through_rate_response.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_get_click_through_rate_response.go @@ -9,13 +9,13 @@ import ( // GetClickThroughRateResponse struct for GetClickThroughRateResponse type GetClickThroughRateResponse struct { // The click-through rate. - Rate float64 `json:"rate"` + Rate float64 `json:"rate" validate:"required"` // The number of click event. - ClickCount int32 `json:"clickCount"` + ClickCount int32 `json:"clickCount" validate:"required"` // The number of tracked search click. - TrackedSearchCount int32 `json:"trackedSearchCount"` + TrackedSearchCount int32 `json:"trackedSearchCount" validate:"required"` // A list of click-through rate events with their date. - Dates []ClickThroughRateEvent `json:"dates"` + Dates []ClickThroughRateEvent `json:"dates" validate:"required"` } // NewGetClickThroughRateResponse instantiates a new GetClickThroughRateResponse object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_get_conversation_rate_response.go b/clients/algoliasearch-client-go/algolia/analytics/model_get_conversation_rate_response.go index 6479c76b29..b028e85007 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_get_conversation_rate_response.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_get_conversation_rate_response.go @@ -9,13 +9,13 @@ import ( // GetConversationRateResponse struct for GetConversationRateResponse type GetConversationRateResponse struct { // The click-through rate. - Rate float64 `json:"rate"` + Rate float64 `json:"rate" validate:"required"` // The number of tracked search click. - TrackedSearchCount int32 `json:"trackedSearchCount"` + TrackedSearchCount int32 `json:"trackedSearchCount" validate:"required"` // The number of converted clicks. - ConversionCount int32 `json:"conversionCount"` + ConversionCount int32 `json:"conversionCount" validate:"required"` // A list of conversion events with their date. - Dates []ConversionRateEvent `json:"dates"` + Dates []ConversionRateEvent `json:"dates" validate:"required"` } // NewGetConversationRateResponse instantiates a new GetConversationRateResponse object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_get_no_click_rate_response.go b/clients/algoliasearch-client-go/algolia/analytics/model_get_no_click_rate_response.go index 89faa53da1..86e338081b 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_get_no_click_rate_response.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_get_no_click_rate_response.go @@ -9,13 +9,13 @@ import ( // GetNoClickRateResponse struct for GetNoClickRateResponse type GetNoClickRateResponse struct { // The click-through rate. - Rate float64 `json:"rate"` + Rate float64 `json:"rate" validate:"required"` // The number of click event. - Count int32 `json:"count"` + Count int32 `json:"count" validate:"required"` // The number of click event. - NoClickCount int32 `json:"noClickCount"` + NoClickCount int32 `json:"noClickCount" validate:"required"` // A list of searches without clicks with their date, rate and counts. - Dates []NoClickRateEvent `json:"dates"` + Dates []NoClickRateEvent `json:"dates" validate:"required"` } // NewGetNoClickRateResponse instantiates a new GetNoClickRateResponse object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_get_no_results_rate_response.go b/clients/algoliasearch-client-go/algolia/analytics/model_get_no_results_rate_response.go index fbca303b01..aef01e2ff0 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_get_no_results_rate_response.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_get_no_results_rate_response.go @@ -9,13 +9,13 @@ import ( // GetNoResultsRateResponse struct for GetNoResultsRateResponse type GetNoResultsRateResponse struct { // The click-through rate. - Rate float64 `json:"rate"` + Rate float64 `json:"rate" validate:"required"` // The number of occurrences. - Count int32 `json:"count"` + Count int32 `json:"count" validate:"required"` // The number of occurrences. - NoResultCount int32 `json:"noResultCount"` + NoResultCount int32 `json:"noResultCount" validate:"required"` // A list of searches without results with their date, rate and counts. - Dates []NoResultsRateEvent `json:"dates"` + Dates []NoResultsRateEvent `json:"dates" validate:"required"` } // NewGetNoResultsRateResponse instantiates a new GetNoResultsRateResponse object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_get_searches_count_response.go b/clients/algoliasearch-client-go/algolia/analytics/model_get_searches_count_response.go index 47af5dd8fe..16fcd2c208 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_get_searches_count_response.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_get_searches_count_response.go @@ -9,9 +9,9 @@ import ( // GetSearchesCountResponse struct for GetSearchesCountResponse type GetSearchesCountResponse struct { // The number of occurrences. - Count int32 `json:"count"` + Count int32 `json:"count" validate:"required"` // A list of search events with their date and count. - Dates []SearchEvent `json:"dates"` + Dates []SearchEvent `json:"dates" validate:"required"` } // NewGetSearchesCountResponse instantiates a new GetSearchesCountResponse object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_get_searches_no_clicks_response.go b/clients/algoliasearch-client-go/algolia/analytics/model_get_searches_no_clicks_response.go index 52c07267d5..36caf40b2b 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_get_searches_no_clicks_response.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_get_searches_no_clicks_response.go @@ -9,7 +9,7 @@ import ( // GetSearchesNoClicksResponse struct for GetSearchesNoClicksResponse type GetSearchesNoClicksResponse struct { // A list of searches with no clicks and their count. - Searches []SearchNoClickEvent `json:"searches"` + Searches []SearchNoClickEvent `json:"searches" validate:"required"` } // NewGetSearchesNoClicksResponse instantiates a new GetSearchesNoClicksResponse object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_get_searches_no_results_response.go b/clients/algoliasearch-client-go/algolia/analytics/model_get_searches_no_results_response.go index 447499e127..9cfa24589a 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_get_searches_no_results_response.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_get_searches_no_results_response.go @@ -9,7 +9,7 @@ import ( // GetSearchesNoResultsResponse struct for GetSearchesNoResultsResponse type GetSearchesNoResultsResponse struct { // A list of searches with no results and their count. - Searches []SearchNoResultEvent `json:"searches"` + Searches []SearchNoResultEvent `json:"searches" validate:"required"` } // NewGetSearchesNoResultsResponse instantiates a new GetSearchesNoResultsResponse object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_get_status_response.go b/clients/algoliasearch-client-go/algolia/analytics/model_get_status_response.go index 2029d69c26..adea715293 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_get_status_response.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_get_status_response.go @@ -9,7 +9,7 @@ import ( // GetStatusResponse struct for GetStatusResponse type GetStatusResponse struct { // Date of last update (ISO-8601 format). - UpdatedAt string `json:"updatedAt"` + UpdatedAt string `json:"updatedAt" validate:"required"` } // NewGetStatusResponse instantiates a new GetStatusResponse object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_get_top_countries_response.go b/clients/algoliasearch-client-go/algolia/analytics/model_get_top_countries_response.go index 7770a7cefb..c86e5296c1 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_get_top_countries_response.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_get_top_countries_response.go @@ -9,7 +9,7 @@ import ( // GetTopCountriesResponse struct for GetTopCountriesResponse type GetTopCountriesResponse struct { // A list of countries with their count. - Countries []TopCountry `json:"countries"` + Countries []TopCountry `json:"countries" validate:"required"` } // NewGetTopCountriesResponse instantiates a new GetTopCountriesResponse object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_get_top_filter_attribute.go b/clients/algoliasearch-client-go/algolia/analytics/model_get_top_filter_attribute.go index f049e774b8..aa53fcd788 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_get_top_filter_attribute.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_get_top_filter_attribute.go @@ -9,9 +9,9 @@ import ( // GetTopFilterAttribute struct for GetTopFilterAttribute type GetTopFilterAttribute struct { // The attribute. - Attribute string `json:"attribute"` + Attribute string `json:"attribute" validate:"required"` // The number of occurrences. - Count int32 `json:"count"` + Count int32 `json:"count" validate:"required"` } // NewGetTopFilterAttribute instantiates a new GetTopFilterAttribute object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_get_top_filter_attributes_response.go b/clients/algoliasearch-client-go/algolia/analytics/model_get_top_filter_attributes_response.go index a3947b061b..c8b0b36203 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_get_top_filter_attributes_response.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_get_top_filter_attributes_response.go @@ -9,7 +9,7 @@ import ( // GetTopFilterAttributesResponse struct for GetTopFilterAttributesResponse type GetTopFilterAttributesResponse struct { // A list of attributes with their count. - Attributes []GetTopFilterAttribute `json:"attributes"` + Attributes []GetTopFilterAttribute `json:"attributes" validate:"required"` } // NewGetTopFilterAttributesResponse instantiates a new GetTopFilterAttributesResponse object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_get_top_filter_for_attribute.go b/clients/algoliasearch-client-go/algolia/analytics/model_get_top_filter_for_attribute.go index cf5c05a24c..b227d2e664 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_get_top_filter_for_attribute.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_get_top_filter_for_attribute.go @@ -9,13 +9,13 @@ import ( // GetTopFilterForAttribute struct for GetTopFilterForAttribute type GetTopFilterForAttribute struct { // The attribute. - Attribute string `json:"attribute"` + Attribute string `json:"attribute" validate:"required"` // The operator. - Operator string `json:"operator"` + Operator string `json:"operator" validate:"required"` // The value of the attribute. - Value string `json:"value"` + Value string `json:"value" validate:"required"` // The number of occurrences. - Count int32 `json:"count"` + Count int32 `json:"count" validate:"required"` } // NewGetTopFilterForAttribute instantiates a new GetTopFilterForAttribute object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_get_top_filter_for_attribute_response.go b/clients/algoliasearch-client-go/algolia/analytics/model_get_top_filter_for_attribute_response.go index 05a4e08c0d..2f6d809d3f 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_get_top_filter_for_attribute_response.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_get_top_filter_for_attribute_response.go @@ -9,7 +9,7 @@ import ( // GetTopFilterForAttributeResponse struct for GetTopFilterForAttributeResponse type GetTopFilterForAttributeResponse struct { // A list of filters for the given attributes. - Values []GetTopFilterForAttribute `json:"values"` + Values []GetTopFilterForAttribute `json:"values" validate:"required"` } // NewGetTopFilterForAttributeResponse instantiates a new GetTopFilterForAttributeResponse object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_get_top_filters_no_results_response.go b/clients/algoliasearch-client-go/algolia/analytics/model_get_top_filters_no_results_response.go index 4e7876f904..ab765e7e2e 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_get_top_filters_no_results_response.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_get_top_filters_no_results_response.go @@ -9,7 +9,7 @@ import ( // GetTopFiltersNoResultsResponse struct for GetTopFiltersNoResultsResponse type GetTopFiltersNoResultsResponse struct { // A list of filters without results. - Values []GetTopFiltersNoResultsValues `json:"values"` + Values []GetTopFiltersNoResultsValues `json:"values" validate:"required"` } // NewGetTopFiltersNoResultsResponse instantiates a new GetTopFiltersNoResultsResponse object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_get_top_filters_no_results_value.go b/clients/algoliasearch-client-go/algolia/analytics/model_get_top_filters_no_results_value.go index deb229fc1c..e4d205d7ee 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_get_top_filters_no_results_value.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_get_top_filters_no_results_value.go @@ -9,11 +9,11 @@ import ( // GetTopFiltersNoResultsValue struct for GetTopFiltersNoResultsValue type GetTopFiltersNoResultsValue struct { // The attribute. - Attribute string `json:"attribute"` + Attribute string `json:"attribute" validate:"required"` // The operator. - Operator string `json:"operator"` + Operator string `json:"operator" validate:"required"` // The value of the attribute. - Value string `json:"value"` + Value string `json:"value" validate:"required"` } // NewGetTopFiltersNoResultsValue instantiates a new GetTopFiltersNoResultsValue object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_get_top_filters_no_results_values.go b/clients/algoliasearch-client-go/algolia/analytics/model_get_top_filters_no_results_values.go index 127821cdfe..633295770b 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_get_top_filters_no_results_values.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_get_top_filters_no_results_values.go @@ -9,9 +9,9 @@ import ( // GetTopFiltersNoResultsValues struct for GetTopFiltersNoResultsValues type GetTopFiltersNoResultsValues struct { // The number of occurrences. - Count int32 `json:"count"` + Count int32 `json:"count" validate:"required"` // A list of filters without results. - Values []GetTopFiltersNoResultsValue `json:"values"` + Values []GetTopFiltersNoResultsValue `json:"values" validate:"required"` } // NewGetTopFiltersNoResultsValues instantiates a new GetTopFiltersNoResultsValues object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_get_top_hits_response.go b/clients/algoliasearch-client-go/algolia/analytics/model_get_top_hits_response.go index a76c98e56f..56be44aea7 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_get_top_hits_response.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_get_top_hits_response.go @@ -29,15 +29,14 @@ func TopHitsResponseWithAnalyticsAsGetTopHitsResponse(v *TopHitsResponseWithAnal // Unmarshal JSON data into one of the pointers in the struct func (dst *GetTopHitsResponse) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into TopHitsResponse err = newStrictDecoder(data).Decode(&dst.TopHitsResponse) - if err == nil { + if err == nil && validateStruct(dst.TopHitsResponse) == nil { jsonTopHitsResponse, _ := json.Marshal(dst.TopHitsResponse) if string(jsonTopHitsResponse) == "{}" { // empty struct dst.TopHitsResponse = nil } else { - match++ + return nil } } else { dst.TopHitsResponse = nil @@ -45,28 +44,18 @@ func (dst *GetTopHitsResponse) UnmarshalJSON(data []byte) error { // try to unmarshal data into TopHitsResponseWithAnalytics err = newStrictDecoder(data).Decode(&dst.TopHitsResponseWithAnalytics) - if err == nil { + if err == nil && validateStruct(dst.TopHitsResponseWithAnalytics) == nil { jsonTopHitsResponseWithAnalytics, _ := json.Marshal(dst.TopHitsResponseWithAnalytics) if string(jsonTopHitsResponseWithAnalytics) == "{}" { // empty struct dst.TopHitsResponseWithAnalytics = nil } else { - match++ + return nil } } else { dst.TopHitsResponseWithAnalytics = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.TopHitsResponse = nil - dst.TopHitsResponseWithAnalytics = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(GetTopHitsResponse)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(GetTopHitsResponse)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(GetTopHitsResponse)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_get_top_searches_response.go b/clients/algoliasearch-client-go/algolia/analytics/model_get_top_searches_response.go index 8b49ccd3f4..8d01223ff3 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_get_top_searches_response.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_get_top_searches_response.go @@ -29,15 +29,14 @@ func TopSearchesResponseWithAnalyticsAsGetTopSearchesResponse(v *TopSearchesResp // Unmarshal JSON data into one of the pointers in the struct func (dst *GetTopSearchesResponse) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into TopSearchesResponse err = newStrictDecoder(data).Decode(&dst.TopSearchesResponse) - if err == nil { + if err == nil && validateStruct(dst.TopSearchesResponse) == nil { jsonTopSearchesResponse, _ := json.Marshal(dst.TopSearchesResponse) if string(jsonTopSearchesResponse) == "{}" { // empty struct dst.TopSearchesResponse = nil } else { - match++ + return nil } } else { dst.TopSearchesResponse = nil @@ -45,28 +44,18 @@ func (dst *GetTopSearchesResponse) UnmarshalJSON(data []byte) error { // try to unmarshal data into TopSearchesResponseWithAnalytics err = newStrictDecoder(data).Decode(&dst.TopSearchesResponseWithAnalytics) - if err == nil { + if err == nil && validateStruct(dst.TopSearchesResponseWithAnalytics) == nil { jsonTopSearchesResponseWithAnalytics, _ := json.Marshal(dst.TopSearchesResponseWithAnalytics) if string(jsonTopSearchesResponseWithAnalytics) == "{}" { // empty struct dst.TopSearchesResponseWithAnalytics = nil } else { - match++ + return nil } } else { dst.TopSearchesResponseWithAnalytics = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.TopSearchesResponse = nil - dst.TopSearchesResponseWithAnalytics = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(GetTopSearchesResponse)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(GetTopSearchesResponse)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(GetTopSearchesResponse)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_get_users_count_response.go b/clients/algoliasearch-client-go/algolia/analytics/model_get_users_count_response.go index cc4274c639..cab9c7a362 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_get_users_count_response.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_get_users_count_response.go @@ -9,9 +9,9 @@ import ( // GetUsersCountResponse struct for GetUsersCountResponse type GetUsersCountResponse struct { // The number of occurrences. - Count int32 `json:"count"` + Count int32 `json:"count" validate:"required"` // A list of users count with their date. - Dates []UserWithDate `json:"dates"` + Dates []UserWithDate `json:"dates" validate:"required"` } // NewGetUsersCountResponse instantiates a new GetUsersCountResponse object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_no_click_rate_event.go b/clients/algoliasearch-client-go/algolia/analytics/model_no_click_rate_event.go index 2c767a56ce..ae2275884b 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_no_click_rate_event.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_no_click_rate_event.go @@ -9,13 +9,13 @@ import ( // NoClickRateEvent struct for NoClickRateEvent type NoClickRateEvent struct { // The click-through rate. - Rate float64 `json:"rate"` + Rate float64 `json:"rate" validate:"required"` // The number of click event. - Count int32 `json:"count"` + Count int32 `json:"count" validate:"required"` // The number of click event. - NoClickCount int32 `json:"noClickCount"` + NoClickCount int32 `json:"noClickCount" validate:"required"` // Date of the event. - Date string `json:"date"` + Date string `json:"date" validate:"required"` } // NewNoClickRateEvent instantiates a new NoClickRateEvent object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_no_results_rate_event.go b/clients/algoliasearch-client-go/algolia/analytics/model_no_results_rate_event.go index 0012b8c09d..62b9808bfe 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_no_results_rate_event.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_no_results_rate_event.go @@ -9,13 +9,13 @@ import ( // NoResultsRateEvent struct for NoResultsRateEvent type NoResultsRateEvent struct { // Date of the event. - Date string `json:"date"` + Date string `json:"date" validate:"required"` // The number of occurrences. - NoResultCount int32 `json:"noResultCount"` + NoResultCount int32 `json:"noResultCount" validate:"required"` // The number of occurrences. - Count int32 `json:"count"` + Count int32 `json:"count" validate:"required"` // The click-through rate. - Rate float64 `json:"rate"` + Rate float64 `json:"rate" validate:"required"` } // NewNoResultsRateEvent instantiates a new NoResultsRateEvent object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_search_event.go b/clients/algoliasearch-client-go/algolia/analytics/model_search_event.go index 73f1413817..b8001c8ab9 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_search_event.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_search_event.go @@ -9,9 +9,9 @@ import ( // SearchEvent struct for SearchEvent type SearchEvent struct { // Date of the event. - Date string `json:"date"` + Date string `json:"date" validate:"required"` // The number of occurrences. - Count int32 `json:"count"` + Count int32 `json:"count" validate:"required"` } // NewSearchEvent instantiates a new SearchEvent object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_search_no_click_event.go b/clients/algoliasearch-client-go/algolia/analytics/model_search_no_click_event.go index 4a64a275ca..a5463d144d 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_search_no_click_event.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_search_no_click_event.go @@ -9,11 +9,11 @@ import ( // SearchNoClickEvent struct for SearchNoClickEvent type SearchNoClickEvent struct { // The search query. - Search string `json:"search"` + Search string `json:"search" validate:"required"` // The number of occurrences. - Count int32 `json:"count"` + Count int32 `json:"count" validate:"required"` // The number of occurrences. - WithFilterCount int32 `json:"withFilterCount"` + WithFilterCount int32 `json:"withFilterCount" validate:"required"` } // NewSearchNoClickEvent instantiates a new SearchNoClickEvent object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_search_no_result_event.go b/clients/algoliasearch-client-go/algolia/analytics/model_search_no_result_event.go index ab5a3f5d28..9dfea6fa73 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_search_no_result_event.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_search_no_result_event.go @@ -9,11 +9,11 @@ import ( // SearchNoResultEvent struct for SearchNoResultEvent type SearchNoResultEvent struct { // The search query. - Search string `json:"search"` + Search string `json:"search" validate:"required"` // The number of occurrences. - Count int32 `json:"count"` + Count int32 `json:"count" validate:"required"` // Number of hits that the search query matched. - NbHits int32 `json:"nbHits"` + NbHits int32 `json:"nbHits" validate:"required"` } // NewSearchNoResultEvent instantiates a new SearchNoResultEvent object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_top_country.go b/clients/algoliasearch-client-go/algolia/analytics/model_top_country.go index 69a61230dc..c4a0eaec59 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_top_country.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_top_country.go @@ -9,9 +9,9 @@ import ( // TopCountry struct for TopCountry type TopCountry struct { // The country. - Country string `json:"country"` + Country string `json:"country" validate:"required"` // The number of occurrences. - Count int32 `json:"count"` + Count int32 `json:"count" validate:"required"` } // NewTopCountry instantiates a new TopCountry object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_top_hit.go b/clients/algoliasearch-client-go/algolia/analytics/model_top_hit.go index b0d03b8947..397d9fd205 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_top_hit.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_top_hit.go @@ -9,9 +9,9 @@ import ( // TopHit struct for TopHit type TopHit struct { // The hit. - Hit string `json:"hit"` + Hit string `json:"hit" validate:"required"` // The number of occurrences. - Count int32 `json:"count"` + Count int32 `json:"count" validate:"required"` } // NewTopHit instantiates a new TopHit object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_top_hit_with_analytics.go b/clients/algoliasearch-client-go/algolia/analytics/model_top_hit_with_analytics.go index a5e594719e..54cdfd0c01 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_top_hit_with_analytics.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_top_hit_with_analytics.go @@ -9,19 +9,19 @@ import ( // TopHitWithAnalytics struct for TopHitWithAnalytics type TopHitWithAnalytics struct { // The hit. - Hit string `json:"hit"` + Hit string `json:"hit" validate:"required"` // The number of occurrences. - Count int32 `json:"count"` + Count int32 `json:"count" validate:"required"` // The click-through rate. - ClickThroughRate float64 `json:"clickThroughRate"` + ClickThroughRate float64 `json:"clickThroughRate" validate:"required"` // The conversion rate. - ConversionRate float64 `json:"conversionRate"` + ConversionRate float64 `json:"conversionRate" validate:"required"` // The number of tracked search click. - TrackedSearchCount int32 `json:"trackedSearchCount"` + TrackedSearchCount int32 `json:"trackedSearchCount" validate:"required"` // The number of click event. - ClickCount int32 `json:"clickCount"` + ClickCount int32 `json:"clickCount" validate:"required"` // The number of converted clicks. - ConversionCount int32 `json:"conversionCount"` + ConversionCount int32 `json:"conversionCount" validate:"required"` } // NewTopHitWithAnalytics instantiates a new TopHitWithAnalytics object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_top_hits_response.go b/clients/algoliasearch-client-go/algolia/analytics/model_top_hits_response.go index 88e3a3643b..f37de7d852 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_top_hits_response.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_top_hits_response.go @@ -9,7 +9,7 @@ import ( // TopHitsResponse struct for TopHitsResponse type TopHitsResponse struct { // A list of top hits with their count. - Hits []TopHit `json:"hits"` + Hits []TopHit `json:"hits" validate:"required"` } // NewTopHitsResponse instantiates a new TopHitsResponse object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_top_hits_response_with_analytics.go b/clients/algoliasearch-client-go/algolia/analytics/model_top_hits_response_with_analytics.go index 88a7d1de83..b243357bfb 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_top_hits_response_with_analytics.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_top_hits_response_with_analytics.go @@ -9,7 +9,7 @@ import ( // TopHitsResponseWithAnalytics struct for TopHitsResponseWithAnalytics type TopHitsResponseWithAnalytics struct { // A list of top hits with their count and analytics. - Hits []TopHitWithAnalytics `json:"hits"` + Hits []TopHitWithAnalytics `json:"hits" validate:"required"` } // NewTopHitsResponseWithAnalytics instantiates a new TopHitsResponseWithAnalytics object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_top_search.go b/clients/algoliasearch-client-go/algolia/analytics/model_top_search.go index 3fed963753..38a7df35cb 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_top_search.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_top_search.go @@ -9,11 +9,11 @@ import ( // TopSearch struct for TopSearch type TopSearch struct { // The search query. - Search string `json:"search"` + Search string `json:"search" validate:"required"` // The number of occurrences. - Count int32 `json:"count"` + Count int32 `json:"count" validate:"required"` // Number of hits that the search query matched. - NbHits int32 `json:"nbHits"` + NbHits int32 `json:"nbHits" validate:"required"` } // NewTopSearch instantiates a new TopSearch object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_top_search_with_analytics.go b/clients/algoliasearch-client-go/algolia/analytics/model_top_search_with_analytics.go index 588817f8b9..4eafa5b273 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_top_search_with_analytics.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_top_search_with_analytics.go @@ -9,23 +9,23 @@ import ( // TopSearchWithAnalytics struct for TopSearchWithAnalytics type TopSearchWithAnalytics struct { // The search query. - Search string `json:"search"` + Search string `json:"search" validate:"required"` // The number of occurrences. - Count int32 `json:"count"` + Count int32 `json:"count" validate:"required"` // The click-through rate. - ClickThroughRate float64 `json:"clickThroughRate"` + ClickThroughRate float64 `json:"clickThroughRate" validate:"required"` // The average position of all the click count event. - AverageClickPosition int32 `json:"averageClickPosition"` + AverageClickPosition int32 `json:"averageClickPosition" validate:"required"` // The conversion rate. - ConversionRate float64 `json:"conversionRate"` + ConversionRate float64 `json:"conversionRate" validate:"required"` // The number of tracked search click. - TrackedSearchCount int32 `json:"trackedSearchCount"` + TrackedSearchCount int32 `json:"trackedSearchCount" validate:"required"` // The number of click event. - ClickCount int32 `json:"clickCount"` + ClickCount int32 `json:"clickCount" validate:"required"` // The number of converted clicks. - ConversionCount int32 `json:"conversionCount"` + ConversionCount int32 `json:"conversionCount" validate:"required"` // Number of hits that the search query matched. - NbHits int32 `json:"nbHits"` + NbHits int32 `json:"nbHits" validate:"required"` } // NewTopSearchWithAnalytics instantiates a new TopSearchWithAnalytics object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_top_searches_response.go b/clients/algoliasearch-client-go/algolia/analytics/model_top_searches_response.go index eecdd1bf68..5e907bac4c 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_top_searches_response.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_top_searches_response.go @@ -9,7 +9,7 @@ import ( // TopSearchesResponse struct for TopSearchesResponse type TopSearchesResponse struct { // A list of top searches with their count. - Searches []TopSearch `json:"searches"` + Searches []TopSearch `json:"searches" validate:"required"` } // NewTopSearchesResponse instantiates a new TopSearchesResponse object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_top_searches_response_with_analytics.go b/clients/algoliasearch-client-go/algolia/analytics/model_top_searches_response_with_analytics.go index e02ce9c672..e16f3ad2d1 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_top_searches_response_with_analytics.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_top_searches_response_with_analytics.go @@ -9,7 +9,7 @@ import ( // TopSearchesResponseWithAnalytics struct for TopSearchesResponseWithAnalytics type TopSearchesResponseWithAnalytics struct { // A list of top searches with their count and analytics. - Searches []TopSearchWithAnalytics `json:"searches"` + Searches []TopSearchWithAnalytics `json:"searches" validate:"required"` } // NewTopSearchesResponseWithAnalytics instantiates a new TopSearchesResponseWithAnalytics object diff --git a/clients/algoliasearch-client-go/algolia/analytics/model_user_with_date.go b/clients/algoliasearch-client-go/algolia/analytics/model_user_with_date.go index 7a0a8508fd..dd1bdbb804 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/model_user_with_date.go +++ b/clients/algoliasearch-client-go/algolia/analytics/model_user_with_date.go @@ -9,9 +9,9 @@ import ( // UserWithDate struct for UserWithDate type UserWithDate struct { // Date of the event. - Date string `json:"date"` + Date string `json:"date" validate:"required"` // The number of occurrences. - Count int32 `json:"count"` + Count int32 `json:"count" validate:"required"` } // NewUserWithDate instantiates a new UserWithDate object diff --git a/clients/algoliasearch-client-go/algolia/analytics/utils.go b/clients/algoliasearch-client-go/algolia/analytics/utils.go index d0c6acdc32..1ca4b00636 100644 --- a/clients/algoliasearch-client-go/algolia/analytics/utils.go +++ b/clients/algoliasearch-client-go/algolia/analytics/utils.go @@ -336,6 +336,8 @@ func isNilorEmpty(i any) bool { switch reflect.TypeOf(i).Kind() { case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.UnsafePointer, reflect.Interface, reflect.Slice: return reflect.ValueOf(i).IsNil() + case reflect.Bool: + return false default: return reflect.ValueOf(i).IsZero() } diff --git a/clients/algoliasearch-client-go/algolia/ingestion/api_ingestion.go b/clients/algoliasearch-client-go/algolia/ingestion/api_ingestion.go index c0a05a3d98..afb0b4458b 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/api_ingestion.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/api_ingestion.go @@ -4,6 +4,7 @@ package ingestion import ( "bytes" "context" + "encoding/json" "io" "net/http" "net/url" @@ -29,7 +30,7 @@ func QueryParamOption(name string, val any) Option { func HeaderParamOption(name string, val any) Option { return Option{ optionType: "header", - name: "itemsPerPage", + name: name, value: parameterToString(val), } } @@ -38,8 +39,32 @@ type ApiCreateAuthenticationRequest struct { authenticationCreate *AuthenticationCreate } -func (r ApiCreateAuthenticationRequest) WithAuthenticationCreate(authenticationCreate AuthenticationCreate) ApiCreateAuthenticationRequest { - r.authenticationCreate = &authenticationCreate +func (r *ApiCreateAuthenticationRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["authenticationCreate"]; ok { //authenticationCreate + err = json.Unmarshal(v, &r.authenticationCreate) + if err != nil { + err = json.Unmarshal(b, &r.authenticationCreate) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.authenticationCreate) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiCreateAuthenticationRequest) WithAuthenticationCreate(authenticationCreate *AuthenticationCreate) ApiCreateAuthenticationRequest { + r.authenticationCreate = authenticationCreate return r } @@ -67,7 +92,7 @@ func (c *APIClient) CreateAuthentication(r ApiCreateAuthenticationRequest, opts for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -123,8 +148,32 @@ type ApiCreateDestinationRequest struct { destinationCreate *DestinationCreate } -func (r ApiCreateDestinationRequest) WithDestinationCreate(destinationCreate DestinationCreate) ApiCreateDestinationRequest { - r.destinationCreate = &destinationCreate +func (r *ApiCreateDestinationRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["destinationCreate"]; ok { //destinationCreate + err = json.Unmarshal(v, &r.destinationCreate) + if err != nil { + err = json.Unmarshal(b, &r.destinationCreate) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.destinationCreate) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiCreateDestinationRequest) WithDestinationCreate(destinationCreate *DestinationCreate) ApiCreateDestinationRequest { + r.destinationCreate = destinationCreate return r } @@ -152,7 +201,7 @@ func (c *APIClient) CreateDestination(r ApiCreateDestinationRequest, opts ...Opt for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -208,8 +257,32 @@ type ApiCreateSourceRequest struct { sourceCreate *SourceCreate } -func (r ApiCreateSourceRequest) WithSourceCreate(sourceCreate SourceCreate) ApiCreateSourceRequest { - r.sourceCreate = &sourceCreate +func (r *ApiCreateSourceRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["sourceCreate"]; ok { //sourceCreate + err = json.Unmarshal(v, &r.sourceCreate) + if err != nil { + err = json.Unmarshal(b, &r.sourceCreate) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.sourceCreate) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiCreateSourceRequest) WithSourceCreate(sourceCreate *SourceCreate) ApiCreateSourceRequest { + r.sourceCreate = sourceCreate return r } @@ -237,7 +310,7 @@ func (c *APIClient) CreateSource(r ApiCreateSourceRequest, opts ...Option) (*Sou for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -293,8 +366,32 @@ type ApiCreateTaskRequest struct { taskCreate *TaskCreate } -func (r ApiCreateTaskRequest) WithTaskCreate(taskCreate TaskCreate) ApiCreateTaskRequest { - r.taskCreate = &taskCreate +func (r *ApiCreateTaskRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["taskCreate"]; ok { //taskCreate + err = json.Unmarshal(v, &r.taskCreate) + if err != nil { + err = json.Unmarshal(b, &r.taskCreate) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.taskCreate) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiCreateTaskRequest) WithTaskCreate(taskCreate *TaskCreate) ApiCreateTaskRequest { + r.taskCreate = taskCreate return r } @@ -322,7 +419,7 @@ func (c *APIClient) CreateTask(r ApiCreateTaskRequest, opts ...Option) (*TaskCre for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -379,6 +476,34 @@ type ApiDelRequest struct { parameters map[string]interface{} } +func (r *ApiDelRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + + return nil +} + // Query parameters to be applied to the current query. func (r ApiDelRequest) WithParameters(parameters map[string]interface{}) ApiDelRequest { r.parameters = parameters @@ -406,14 +531,16 @@ func (c *APIClient) Del(r ApiDelRequest, opts ...Option) (map[string]interface{} queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -494,6 +621,25 @@ type ApiDeleteAuthenticationRequest struct { authenticationID string } +func (r *ApiDeleteAuthenticationRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["authenticationID"]; ok { //authenticationID + err = json.Unmarshal(v, &r.authenticationID) + if err != nil { + err = json.Unmarshal(b, &r.authenticationID) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiDeleteAuthenticationRequest func (c *APIClient) NewApiDeleteAuthenticationRequest(authenticationID string) ApiDeleteAuthenticationRequest { return ApiDeleteAuthenticationRequest{ @@ -518,7 +664,7 @@ func (c *APIClient) DeleteAuthentication(r ApiDeleteAuthenticationRequest, opts for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -572,6 +718,25 @@ type ApiDeleteDestinationRequest struct { destinationID string } +func (r *ApiDeleteDestinationRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["destinationID"]; ok { //destinationID + err = json.Unmarshal(v, &r.destinationID) + if err != nil { + err = json.Unmarshal(b, &r.destinationID) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiDeleteDestinationRequest func (c *APIClient) NewApiDeleteDestinationRequest(destinationID string) ApiDeleteDestinationRequest { return ApiDeleteDestinationRequest{ @@ -596,7 +761,7 @@ func (c *APIClient) DeleteDestination(r ApiDeleteDestinationRequest, opts ...Opt for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -650,6 +815,25 @@ type ApiDeleteSourceRequest struct { sourceID string } +func (r *ApiDeleteSourceRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["sourceID"]; ok { //sourceID + err = json.Unmarshal(v, &r.sourceID) + if err != nil { + err = json.Unmarshal(b, &r.sourceID) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiDeleteSourceRequest func (c *APIClient) NewApiDeleteSourceRequest(sourceID string) ApiDeleteSourceRequest { return ApiDeleteSourceRequest{ @@ -674,7 +858,7 @@ func (c *APIClient) DeleteSource(r ApiDeleteSourceRequest, opts ...Option) (*Del for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -728,6 +912,25 @@ type ApiDeleteTaskRequest struct { taskID string } +func (r *ApiDeleteTaskRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["taskID"]; ok { //taskID + err = json.Unmarshal(v, &r.taskID) + if err != nil { + err = json.Unmarshal(b, &r.taskID) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiDeleteTaskRequest func (c *APIClient) NewApiDeleteTaskRequest(taskID string) ApiDeleteTaskRequest { return ApiDeleteTaskRequest{ @@ -752,7 +955,7 @@ func (c *APIClient) DeleteTask(r ApiDeleteTaskRequest, opts ...Option) (*DeleteR for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -806,6 +1009,25 @@ type ApiDisableTaskRequest struct { taskID string } +func (r *ApiDisableTaskRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["taskID"]; ok { //taskID + err = json.Unmarshal(v, &r.taskID) + if err != nil { + err = json.Unmarshal(b, &r.taskID) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiDisableTaskRequest func (c *APIClient) NewApiDisableTaskRequest(taskID string) ApiDisableTaskRequest { return ApiDisableTaskRequest{ @@ -830,7 +1052,7 @@ func (c *APIClient) DisableTask(r ApiDisableTaskRequest, opts ...Option) (*TaskU for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -884,6 +1106,25 @@ type ApiEnableTaskRequest struct { taskID string } +func (r *ApiEnableTaskRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["taskID"]; ok { //taskID + err = json.Unmarshal(v, &r.taskID) + if err != nil { + err = json.Unmarshal(b, &r.taskID) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiEnableTaskRequest func (c *APIClient) NewApiEnableTaskRequest(taskID string) ApiEnableTaskRequest { return ApiEnableTaskRequest{ @@ -908,7 +1149,7 @@ func (c *APIClient) EnableTask(r ApiEnableTaskRequest, opts ...Option) (*TaskUpd for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -963,6 +1204,34 @@ type ApiGetRequest struct { parameters map[string]interface{} } +func (r *ApiGetRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + + return nil +} + // Query parameters to be applied to the current query. func (r ApiGetRequest) WithParameters(parameters map[string]interface{}) ApiGetRequest { r.parameters = parameters @@ -990,14 +1259,16 @@ func (c *APIClient) Get(r ApiGetRequest, opts ...Option) (map[string]interface{} queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1078,6 +1349,25 @@ type ApiGetAuthenticationRequest struct { authenticationID string } +func (r *ApiGetAuthenticationRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["authenticationID"]; ok { //authenticationID + err = json.Unmarshal(v, &r.authenticationID) + if err != nil { + err = json.Unmarshal(b, &r.authenticationID) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiGetAuthenticationRequest func (c *APIClient) NewApiGetAuthenticationRequest(authenticationID string) ApiGetAuthenticationRequest { return ApiGetAuthenticationRequest{ @@ -1102,7 +1392,7 @@ func (c *APIClient) GetAuthentication(r ApiGetAuthenticationRequest, opts ...Opt for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1155,12 +1445,76 @@ func (c *APIClient) GetAuthentication(r ApiGetAuthenticationRequest, opts ...Opt type ApiGetAuthenticationsRequest struct { itemsPerPage int32 page int32 - type_ *[]AuthenticationType - platform *[]PlatformWithNone + type_ []AuthenticationType + platform []PlatformWithNone sort *AuthenticationSortKeys order *OrderKeys } +func (r *ApiGetAuthenticationsRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["itemsPerPage"]; ok { //itemsPerPage + err = json.Unmarshal(v, &r.itemsPerPage) + if err != nil { + err = json.Unmarshal(b, &r.itemsPerPage) + if err != nil { + return err + } + } + } + if v, ok := req["page"]; ok { //page + err = json.Unmarshal(v, &r.page) + if err != nil { + err = json.Unmarshal(b, &r.page) + if err != nil { + return err + } + } + } + if v, ok := req["type"]; ok { //type_ + err = json.Unmarshal(v, &r.type_) + if err != nil { + err = json.Unmarshal(b, &r.type_) + if err != nil { + return err + } + } + } + if v, ok := req["platform"]; ok { //platform + err = json.Unmarshal(v, &r.platform) + if err != nil { + err = json.Unmarshal(b, &r.platform) + if err != nil { + return err + } + } + } + if v, ok := req["sort"]; ok { //sort + err = json.Unmarshal(v, &r.sort) + if err != nil { + err = json.Unmarshal(b, &r.sort) + if err != nil { + return err + } + } + } + if v, ok := req["order"]; ok { //order + err = json.Unmarshal(v, &r.order) + if err != nil { + err = json.Unmarshal(b, &r.order) + if err != nil { + return err + } + } + } + + return nil +} + // The number of items per page to return. func (r ApiGetAuthenticationsRequest) WithItemsPerPage(itemsPerPage int32) ApiGetAuthenticationsRequest { r.itemsPerPage = itemsPerPage @@ -1175,25 +1529,25 @@ func (r ApiGetAuthenticationsRequest) WithPage(page int32) ApiGetAuthentications // The type of the authentications to retrieve. func (r ApiGetAuthenticationsRequest) WithType_(type_ []AuthenticationType) ApiGetAuthenticationsRequest { - r.type_ = &type_ + r.type_ = type_ return r } // The platform of the authentications to retrieve. func (r ApiGetAuthenticationsRequest) WithPlatform(platform []PlatformWithNone) ApiGetAuthenticationsRequest { - r.platform = &platform + r.platform = platform return r } // The key by which the list should be sorted. -func (r ApiGetAuthenticationsRequest) WithSort(sort AuthenticationSortKeys) ApiGetAuthenticationsRequest { - r.sort = &sort +func (r ApiGetAuthenticationsRequest) WithSort(sort *AuthenticationSortKeys) ApiGetAuthenticationsRequest { + r.sort = sort return r } // The order of the returned list. -func (r ApiGetAuthenticationsRequest) WithOrder(order OrderKeys) ApiGetAuthenticationsRequest { - r.order = &order +func (r ApiGetAuthenticationsRequest) WithOrder(order *OrderKeys) ApiGetAuthenticationsRequest { + r.order = order return r } @@ -1215,29 +1569,29 @@ func (c *APIClient) GetAuthentications(r ApiGetAuthenticationsRequest, opts ...O queryParams := url.Values{} if !isNilorEmpty(r.itemsPerPage) { - queryParams.Add("itemsPerPage", parameterToString(r.itemsPerPage)) + queryParams.Set("itemsPerPage", parameterToString(r.itemsPerPage)) } if !isNilorEmpty(r.page) { - queryParams.Add("page", parameterToString(r.page)) + queryParams.Set("page", parameterToString(r.page)) } if !isNilorEmpty(r.type_) { - queryParams.Add("type", parameterToString(*r.type_)) + queryParams.Set("type", parameterToString(r.type_)) } if !isNilorEmpty(r.platform) { - queryParams.Add("platform", parameterToString(*r.platform)) + queryParams.Set("platform", parameterToString(r.platform)) } if !isNilorEmpty(r.sort) { - queryParams.Add("sort", parameterToString(*r.sort)) + queryParams.Set("sort", parameterToString(*r.sort)) } if !isNilorEmpty(r.order) { - queryParams.Add("order", parameterToString(*r.order)) + queryParams.Set("order", parameterToString(*r.order)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1291,6 +1645,25 @@ type ApiGetDestinationRequest struct { destinationID string } +func (r *ApiGetDestinationRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["destinationID"]; ok { //destinationID + err = json.Unmarshal(v, &r.destinationID) + if err != nil { + err = json.Unmarshal(b, &r.destinationID) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiGetDestinationRequest func (c *APIClient) NewApiGetDestinationRequest(destinationID string) ApiGetDestinationRequest { return ApiGetDestinationRequest{ @@ -1315,7 +1688,7 @@ func (c *APIClient) GetDestination(r ApiGetDestinationRequest, opts ...Option) ( for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1368,12 +1741,76 @@ func (c *APIClient) GetDestination(r ApiGetDestinationRequest, opts ...Option) ( type ApiGetDestinationsRequest struct { itemsPerPage int32 page int32 - type_ *[]DestinationType - authenticationID *[]string + type_ []DestinationType + authenticationID []string sort *DestinationSortKeys order *OrderKeys } +func (r *ApiGetDestinationsRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["itemsPerPage"]; ok { //itemsPerPage + err = json.Unmarshal(v, &r.itemsPerPage) + if err != nil { + err = json.Unmarshal(b, &r.itemsPerPage) + if err != nil { + return err + } + } + } + if v, ok := req["page"]; ok { //page + err = json.Unmarshal(v, &r.page) + if err != nil { + err = json.Unmarshal(b, &r.page) + if err != nil { + return err + } + } + } + if v, ok := req["type"]; ok { //type_ + err = json.Unmarshal(v, &r.type_) + if err != nil { + err = json.Unmarshal(b, &r.type_) + if err != nil { + return err + } + } + } + if v, ok := req["authenticationID"]; ok { //authenticationID + err = json.Unmarshal(v, &r.authenticationID) + if err != nil { + err = json.Unmarshal(b, &r.authenticationID) + if err != nil { + return err + } + } + } + if v, ok := req["sort"]; ok { //sort + err = json.Unmarshal(v, &r.sort) + if err != nil { + err = json.Unmarshal(b, &r.sort) + if err != nil { + return err + } + } + } + if v, ok := req["order"]; ok { //order + err = json.Unmarshal(v, &r.order) + if err != nil { + err = json.Unmarshal(b, &r.order) + if err != nil { + return err + } + } + } + + return nil +} + // The number of items per page to return. func (r ApiGetDestinationsRequest) WithItemsPerPage(itemsPerPage int32) ApiGetDestinationsRequest { r.itemsPerPage = itemsPerPage @@ -1388,25 +1825,25 @@ func (r ApiGetDestinationsRequest) WithPage(page int32) ApiGetDestinationsReques // The type of the destinations to retrive. func (r ApiGetDestinationsRequest) WithType_(type_ []DestinationType) ApiGetDestinationsRequest { - r.type_ = &type_ + r.type_ = type_ return r } // The authenticationIDs of the destinations to retrive. func (r ApiGetDestinationsRequest) WithAuthenticationID(authenticationID []string) ApiGetDestinationsRequest { - r.authenticationID = &authenticationID + r.authenticationID = authenticationID return r } // The key by which the list should be sorted. -func (r ApiGetDestinationsRequest) WithSort(sort DestinationSortKeys) ApiGetDestinationsRequest { - r.sort = &sort +func (r ApiGetDestinationsRequest) WithSort(sort *DestinationSortKeys) ApiGetDestinationsRequest { + r.sort = sort return r } // The order of the returned list. -func (r ApiGetDestinationsRequest) WithOrder(order OrderKeys) ApiGetDestinationsRequest { - r.order = &order +func (r ApiGetDestinationsRequest) WithOrder(order *OrderKeys) ApiGetDestinationsRequest { + r.order = order return r } @@ -1428,29 +1865,29 @@ func (c *APIClient) GetDestinations(r ApiGetDestinationsRequest, opts ...Option) queryParams := url.Values{} if !isNilorEmpty(r.itemsPerPage) { - queryParams.Add("itemsPerPage", parameterToString(r.itemsPerPage)) + queryParams.Set("itemsPerPage", parameterToString(r.itemsPerPage)) } if !isNilorEmpty(r.page) { - queryParams.Add("page", parameterToString(r.page)) + queryParams.Set("page", parameterToString(r.page)) } if !isNilorEmpty(r.type_) { - queryParams.Add("type", parameterToString(*r.type_)) + queryParams.Set("type", parameterToString(r.type_)) } if !isNilorEmpty(r.authenticationID) { - queryParams.Add("authenticationID", parameterToString(*r.authenticationID)) + queryParams.Set("authenticationID", parameterToString(r.authenticationID)) } if !isNilorEmpty(r.sort) { - queryParams.Add("sort", parameterToString(*r.sort)) + queryParams.Set("sort", parameterToString(*r.sort)) } if !isNilorEmpty(r.order) { - queryParams.Add("order", parameterToString(*r.order)) + queryParams.Set("order", parameterToString(*r.order)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1505,6 +1942,34 @@ type ApiGetEventRequest struct { eventID string } +func (r *ApiGetEventRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["runID"]; ok { //runID + err = json.Unmarshal(v, &r.runID) + if err != nil { + err = json.Unmarshal(b, &r.runID) + if err != nil { + return err + } + } + } + if v, ok := req["eventID"]; ok { //eventID + err = json.Unmarshal(v, &r.eventID) + if err != nil { + err = json.Unmarshal(b, &r.eventID) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiGetEventRequest func (c *APIClient) NewApiGetEventRequest(runID string, eventID string) ApiGetEventRequest { return ApiGetEventRequest{ @@ -1531,7 +1996,7 @@ func (c *APIClient) GetEvent(r ApiGetEventRequest, opts ...Option) (*Event, erro for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1585,12 +2050,85 @@ type ApiGetEventsRequest struct { runID string itemsPerPage int32 page int32 - status *[]EventStatus - type_ *[]EventType + status []EventStatus + type_ []EventType sort *EventSortKeys order *OrderKeys } +func (r *ApiGetEventsRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["runID"]; ok { //runID + err = json.Unmarshal(v, &r.runID) + if err != nil { + err = json.Unmarshal(b, &r.runID) + if err != nil { + return err + } + } + } + if v, ok := req["itemsPerPage"]; ok { //itemsPerPage + err = json.Unmarshal(v, &r.itemsPerPage) + if err != nil { + err = json.Unmarshal(b, &r.itemsPerPage) + if err != nil { + return err + } + } + } + if v, ok := req["page"]; ok { //page + err = json.Unmarshal(v, &r.page) + if err != nil { + err = json.Unmarshal(b, &r.page) + if err != nil { + return err + } + } + } + if v, ok := req["status"]; ok { //status + err = json.Unmarshal(v, &r.status) + if err != nil { + err = json.Unmarshal(b, &r.status) + if err != nil { + return err + } + } + } + if v, ok := req["type"]; ok { //type_ + err = json.Unmarshal(v, &r.type_) + if err != nil { + err = json.Unmarshal(b, &r.type_) + if err != nil { + return err + } + } + } + if v, ok := req["sort"]; ok { //sort + err = json.Unmarshal(v, &r.sort) + if err != nil { + err = json.Unmarshal(b, &r.sort) + if err != nil { + return err + } + } + } + if v, ok := req["order"]; ok { //order + err = json.Unmarshal(v, &r.order) + if err != nil { + err = json.Unmarshal(b, &r.order) + if err != nil { + return err + } + } + } + + return nil +} + // The number of items per page to return. func (r ApiGetEventsRequest) WithItemsPerPage(itemsPerPage int32) ApiGetEventsRequest { r.itemsPerPage = itemsPerPage @@ -1605,25 +2143,25 @@ func (r ApiGetEventsRequest) WithPage(page int32) ApiGetEventsRequest { // Filter the status of the events. func (r ApiGetEventsRequest) WithStatus(status []EventStatus) ApiGetEventsRequest { - r.status = &status + r.status = status return r } // Filter the type of the events. func (r ApiGetEventsRequest) WithType_(type_ []EventType) ApiGetEventsRequest { - r.type_ = &type_ + r.type_ = type_ return r } // The key by which the list should be sorted. -func (r ApiGetEventsRequest) WithSort(sort EventSortKeys) ApiGetEventsRequest { - r.sort = &sort +func (r ApiGetEventsRequest) WithSort(sort *EventSortKeys) ApiGetEventsRequest { + r.sort = sort return r } // The order of the returned list. -func (r ApiGetEventsRequest) WithOrder(order OrderKeys) ApiGetEventsRequest { - r.order = &order +func (r ApiGetEventsRequest) WithOrder(order *OrderKeys) ApiGetEventsRequest { + r.order = order return r } @@ -1648,29 +2186,29 @@ func (c *APIClient) GetEvents(r ApiGetEventsRequest, opts ...Option) (*ListEvent queryParams := url.Values{} if !isNilorEmpty(r.itemsPerPage) { - queryParams.Add("itemsPerPage", parameterToString(r.itemsPerPage)) + queryParams.Set("itemsPerPage", parameterToString(r.itemsPerPage)) } if !isNilorEmpty(r.page) { - queryParams.Add("page", parameterToString(r.page)) + queryParams.Set("page", parameterToString(r.page)) } if !isNilorEmpty(r.status) { - queryParams.Add("status", parameterToString(*r.status)) + queryParams.Set("status", parameterToString(r.status)) } if !isNilorEmpty(r.type_) { - queryParams.Add("type", parameterToString(*r.type_)) + queryParams.Set("type", parameterToString(r.type_)) } if !isNilorEmpty(r.sort) { - queryParams.Add("sort", parameterToString(*r.sort)) + queryParams.Set("sort", parameterToString(*r.sort)) } if !isNilorEmpty(r.order) { - queryParams.Add("order", parameterToString(*r.order)) + queryParams.Set("order", parameterToString(*r.order)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1724,6 +2262,25 @@ type ApiGetRunRequest struct { runID string } +func (r *ApiGetRunRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["runID"]; ok { //runID + err = json.Unmarshal(v, &r.runID) + if err != nil { + err = json.Unmarshal(b, &r.runID) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiGetRunRequest func (c *APIClient) NewApiGetRunRequest(runID string) ApiGetRunRequest { return ApiGetRunRequest{ @@ -1748,7 +2305,7 @@ func (c *APIClient) GetRun(r ApiGetRunRequest, opts ...Option) (*Run, error) { for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1801,14 +2358,78 @@ func (c *APIClient) GetRun(r ApiGetRunRequest, opts ...Option) (*Run, error) { type ApiGetRunsRequest struct { itemsPerPage int32 page int32 - status *[]RunStatus + status []RunStatus taskID string sort *RunSortKeys order *OrderKeys } -// The number of items per page to return. -func (r ApiGetRunsRequest) WithItemsPerPage(itemsPerPage int32) ApiGetRunsRequest { +func (r *ApiGetRunsRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["itemsPerPage"]; ok { //itemsPerPage + err = json.Unmarshal(v, &r.itemsPerPage) + if err != nil { + err = json.Unmarshal(b, &r.itemsPerPage) + if err != nil { + return err + } + } + } + if v, ok := req["page"]; ok { //page + err = json.Unmarshal(v, &r.page) + if err != nil { + err = json.Unmarshal(b, &r.page) + if err != nil { + return err + } + } + } + if v, ok := req["status"]; ok { //status + err = json.Unmarshal(v, &r.status) + if err != nil { + err = json.Unmarshal(b, &r.status) + if err != nil { + return err + } + } + } + if v, ok := req["taskID"]; ok { //taskID + err = json.Unmarshal(v, &r.taskID) + if err != nil { + err = json.Unmarshal(b, &r.taskID) + if err != nil { + return err + } + } + } + if v, ok := req["sort"]; ok { //sort + err = json.Unmarshal(v, &r.sort) + if err != nil { + err = json.Unmarshal(b, &r.sort) + if err != nil { + return err + } + } + } + if v, ok := req["order"]; ok { //order + err = json.Unmarshal(v, &r.order) + if err != nil { + err = json.Unmarshal(b, &r.order) + if err != nil { + return err + } + } + } + + return nil +} + +// The number of items per page to return. +func (r ApiGetRunsRequest) WithItemsPerPage(itemsPerPage int32) ApiGetRunsRequest { r.itemsPerPage = itemsPerPage return r } @@ -1821,7 +2442,7 @@ func (r ApiGetRunsRequest) WithPage(page int32) ApiGetRunsRequest { // Filter the status of the runs. func (r ApiGetRunsRequest) WithStatus(status []RunStatus) ApiGetRunsRequest { - r.status = &status + r.status = status return r } @@ -1832,14 +2453,14 @@ func (r ApiGetRunsRequest) WithTaskID(taskID string) ApiGetRunsRequest { } // The key by which the list should be sorted. -func (r ApiGetRunsRequest) WithSort(sort RunSortKeys) ApiGetRunsRequest { - r.sort = &sort +func (r ApiGetRunsRequest) WithSort(sort *RunSortKeys) ApiGetRunsRequest { + r.sort = sort return r } // The order of the returned list. -func (r ApiGetRunsRequest) WithOrder(order OrderKeys) ApiGetRunsRequest { - r.order = &order +func (r ApiGetRunsRequest) WithOrder(order *OrderKeys) ApiGetRunsRequest { + r.order = order return r } @@ -1861,29 +2482,29 @@ func (c *APIClient) GetRuns(r ApiGetRunsRequest, opts ...Option) (*RunListRespon queryParams := url.Values{} if !isNilorEmpty(r.itemsPerPage) { - queryParams.Add("itemsPerPage", parameterToString(r.itemsPerPage)) + queryParams.Set("itemsPerPage", parameterToString(r.itemsPerPage)) } if !isNilorEmpty(r.page) { - queryParams.Add("page", parameterToString(r.page)) + queryParams.Set("page", parameterToString(r.page)) } if !isNilorEmpty(r.status) { - queryParams.Add("status", parameterToString(*r.status)) + queryParams.Set("status", parameterToString(r.status)) } if !isNilorEmpty(r.taskID) { - queryParams.Add("taskID", parameterToString(r.taskID)) + queryParams.Set("taskID", parameterToString(r.taskID)) } if !isNilorEmpty(r.sort) { - queryParams.Add("sort", parameterToString(*r.sort)) + queryParams.Set("sort", parameterToString(*r.sort)) } if !isNilorEmpty(r.order) { - queryParams.Add("order", parameterToString(*r.order)) + queryParams.Set("order", parameterToString(*r.order)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1937,6 +2558,25 @@ type ApiGetSourceRequest struct { sourceID string } +func (r *ApiGetSourceRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["sourceID"]; ok { //sourceID + err = json.Unmarshal(v, &r.sourceID) + if err != nil { + err = json.Unmarshal(b, &r.sourceID) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiGetSourceRequest func (c *APIClient) NewApiGetSourceRequest(sourceID string) ApiGetSourceRequest { return ApiGetSourceRequest{ @@ -1961,7 +2601,7 @@ func (c *APIClient) GetSource(r ApiGetSourceRequest, opts ...Option) (*Source, e for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -2014,12 +2654,76 @@ func (c *APIClient) GetSource(r ApiGetSourceRequest, opts ...Option) (*Source, e type ApiGetSourcesRequest struct { itemsPerPage int32 page int32 - type_ *[]SourceType - authenticationID *[]string + type_ []SourceType + authenticationID []string sort *SourceSortKeys order *OrderKeys } +func (r *ApiGetSourcesRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["itemsPerPage"]; ok { //itemsPerPage + err = json.Unmarshal(v, &r.itemsPerPage) + if err != nil { + err = json.Unmarshal(b, &r.itemsPerPage) + if err != nil { + return err + } + } + } + if v, ok := req["page"]; ok { //page + err = json.Unmarshal(v, &r.page) + if err != nil { + err = json.Unmarshal(b, &r.page) + if err != nil { + return err + } + } + } + if v, ok := req["type"]; ok { //type_ + err = json.Unmarshal(v, &r.type_) + if err != nil { + err = json.Unmarshal(b, &r.type_) + if err != nil { + return err + } + } + } + if v, ok := req["authenticationID"]; ok { //authenticationID + err = json.Unmarshal(v, &r.authenticationID) + if err != nil { + err = json.Unmarshal(b, &r.authenticationID) + if err != nil { + return err + } + } + } + if v, ok := req["sort"]; ok { //sort + err = json.Unmarshal(v, &r.sort) + if err != nil { + err = json.Unmarshal(b, &r.sort) + if err != nil { + return err + } + } + } + if v, ok := req["order"]; ok { //order + err = json.Unmarshal(v, &r.order) + if err != nil { + err = json.Unmarshal(b, &r.order) + if err != nil { + return err + } + } + } + + return nil +} + // The number of items per page to return. func (r ApiGetSourcesRequest) WithItemsPerPage(itemsPerPage int32) ApiGetSourcesRequest { r.itemsPerPage = itemsPerPage @@ -2034,25 +2738,25 @@ func (r ApiGetSourcesRequest) WithPage(page int32) ApiGetSourcesRequest { // The type of the sources to retrieve. func (r ApiGetSourcesRequest) WithType_(type_ []SourceType) ApiGetSourcesRequest { - r.type_ = &type_ + r.type_ = type_ return r } // The authenticationIDs of the sources to retrieve. 'none' returns sources that doesn't have an authentication. func (r ApiGetSourcesRequest) WithAuthenticationID(authenticationID []string) ApiGetSourcesRequest { - r.authenticationID = &authenticationID + r.authenticationID = authenticationID return r } // The key by which the list should be sorted. -func (r ApiGetSourcesRequest) WithSort(sort SourceSortKeys) ApiGetSourcesRequest { - r.sort = &sort +func (r ApiGetSourcesRequest) WithSort(sort *SourceSortKeys) ApiGetSourcesRequest { + r.sort = sort return r } // The order of the returned list. -func (r ApiGetSourcesRequest) WithOrder(order OrderKeys) ApiGetSourcesRequest { - r.order = &order +func (r ApiGetSourcesRequest) WithOrder(order *OrderKeys) ApiGetSourcesRequest { + r.order = order return r } @@ -2074,29 +2778,29 @@ func (c *APIClient) GetSources(r ApiGetSourcesRequest, opts ...Option) (*ListSou queryParams := url.Values{} if !isNilorEmpty(r.itemsPerPage) { - queryParams.Add("itemsPerPage", parameterToString(r.itemsPerPage)) + queryParams.Set("itemsPerPage", parameterToString(r.itemsPerPage)) } if !isNilorEmpty(r.page) { - queryParams.Add("page", parameterToString(r.page)) + queryParams.Set("page", parameterToString(r.page)) } if !isNilorEmpty(r.type_) { - queryParams.Add("type", parameterToString(*r.type_)) + queryParams.Set("type", parameterToString(r.type_)) } if !isNilorEmpty(r.authenticationID) { - queryParams.Add("authenticationID", parameterToString(*r.authenticationID)) + queryParams.Set("authenticationID", parameterToString(r.authenticationID)) } if !isNilorEmpty(r.sort) { - queryParams.Add("sort", parameterToString(*r.sort)) + queryParams.Set("sort", parameterToString(*r.sort)) } if !isNilorEmpty(r.order) { - queryParams.Add("order", parameterToString(*r.order)) + queryParams.Set("order", parameterToString(*r.order)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -2150,6 +2854,25 @@ type ApiGetTaskRequest struct { taskID string } +func (r *ApiGetTaskRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["taskID"]; ok { //taskID + err = json.Unmarshal(v, &r.taskID) + if err != nil { + err = json.Unmarshal(b, &r.taskID) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiGetTaskRequest func (c *APIClient) NewApiGetTaskRequest(taskID string) ApiGetTaskRequest { return ApiGetTaskRequest{ @@ -2174,7 +2897,7 @@ func (c *APIClient) GetTask(r ApiGetTaskRequest, opts ...Option) (*Task, error) for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -2227,15 +2950,106 @@ func (c *APIClient) GetTask(r ApiGetTaskRequest, opts ...Option) (*Task, error) type ApiGetTasksRequest struct { itemsPerPage int32 page int32 - action *[]ActionType + action []ActionType enabled bool - sourceID *[]string - destinationID *[]string - triggerType *[]TriggerType + sourceID []string + destinationID []string + triggerType []TriggerType sort *TaskSortKeys order *OrderKeys } +func (r *ApiGetTasksRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["itemsPerPage"]; ok { //itemsPerPage + err = json.Unmarshal(v, &r.itemsPerPage) + if err != nil { + err = json.Unmarshal(b, &r.itemsPerPage) + if err != nil { + return err + } + } + } + if v, ok := req["page"]; ok { //page + err = json.Unmarshal(v, &r.page) + if err != nil { + err = json.Unmarshal(b, &r.page) + if err != nil { + return err + } + } + } + if v, ok := req["action"]; ok { //action + err = json.Unmarshal(v, &r.action) + if err != nil { + err = json.Unmarshal(b, &r.action) + if err != nil { + return err + } + } + } + if v, ok := req["enabled"]; ok { //enabled + err = json.Unmarshal(v, &r.enabled) + if err != nil { + err = json.Unmarshal(b, &r.enabled) + if err != nil { + return err + } + } + } + if v, ok := req["sourceID"]; ok { //sourceID + err = json.Unmarshal(v, &r.sourceID) + if err != nil { + err = json.Unmarshal(b, &r.sourceID) + if err != nil { + return err + } + } + } + if v, ok := req["destinationID"]; ok { //destinationID + err = json.Unmarshal(v, &r.destinationID) + if err != nil { + err = json.Unmarshal(b, &r.destinationID) + if err != nil { + return err + } + } + } + if v, ok := req["triggerType"]; ok { //triggerType + err = json.Unmarshal(v, &r.triggerType) + if err != nil { + err = json.Unmarshal(b, &r.triggerType) + if err != nil { + return err + } + } + } + if v, ok := req["sort"]; ok { //sort + err = json.Unmarshal(v, &r.sort) + if err != nil { + err = json.Unmarshal(b, &r.sort) + if err != nil { + return err + } + } + } + if v, ok := req["order"]; ok { //order + err = json.Unmarshal(v, &r.order) + if err != nil { + err = json.Unmarshal(b, &r.order) + if err != nil { + return err + } + } + } + + return nil +} + // The number of items per page to return. func (r ApiGetTasksRequest) WithItemsPerPage(itemsPerPage int32) ApiGetTasksRequest { r.itemsPerPage = itemsPerPage @@ -2250,7 +3064,7 @@ func (r ApiGetTasksRequest) WithPage(page int32) ApiGetTasksRequest { // The action of the tasks to retrieve. func (r ApiGetTasksRequest) WithAction(action []ActionType) ApiGetTasksRequest { - r.action = &action + r.action = action return r } @@ -2262,31 +3076,31 @@ func (r ApiGetTasksRequest) WithEnabled(enabled bool) ApiGetTasksRequest { // The sourceIDs of the tasks to retrive. func (r ApiGetTasksRequest) WithSourceID(sourceID []string) ApiGetTasksRequest { - r.sourceID = &sourceID + r.sourceID = sourceID return r } // The destinationIDs of the tasks to retrive. func (r ApiGetTasksRequest) WithDestinationID(destinationID []string) ApiGetTasksRequest { - r.destinationID = &destinationID + r.destinationID = destinationID return r } // The trigger type of the task. func (r ApiGetTasksRequest) WithTriggerType(triggerType []TriggerType) ApiGetTasksRequest { - r.triggerType = &triggerType + r.triggerType = triggerType return r } // The key by which the list should be sorted. -func (r ApiGetTasksRequest) WithSort(sort TaskSortKeys) ApiGetTasksRequest { - r.sort = &sort +func (r ApiGetTasksRequest) WithSort(sort *TaskSortKeys) ApiGetTasksRequest { + r.sort = sort return r } // The order of the returned list. -func (r ApiGetTasksRequest) WithOrder(order OrderKeys) ApiGetTasksRequest { - r.order = &order +func (r ApiGetTasksRequest) WithOrder(order *OrderKeys) ApiGetTasksRequest { + r.order = order return r } @@ -2308,38 +3122,38 @@ func (c *APIClient) GetTasks(r ApiGetTasksRequest, opts ...Option) (*ListTasksRe queryParams := url.Values{} if !isNilorEmpty(r.itemsPerPage) { - queryParams.Add("itemsPerPage", parameterToString(r.itemsPerPage)) + queryParams.Set("itemsPerPage", parameterToString(r.itemsPerPage)) } if !isNilorEmpty(r.page) { - queryParams.Add("page", parameterToString(r.page)) + queryParams.Set("page", parameterToString(r.page)) } if !isNilorEmpty(r.action) { - queryParams.Add("action", parameterToString(*r.action)) + queryParams.Set("action", parameterToString(r.action)) } if !isNilorEmpty(r.enabled) { - queryParams.Add("enabled", parameterToString(r.enabled)) + queryParams.Set("enabled", parameterToString(r.enabled)) } if !isNilorEmpty(r.sourceID) { - queryParams.Add("sourceID", parameterToString(*r.sourceID)) + queryParams.Set("sourceID", parameterToString(r.sourceID)) } if !isNilorEmpty(r.destinationID) { - queryParams.Add("destinationID", parameterToString(*r.destinationID)) + queryParams.Set("destinationID", parameterToString(r.destinationID)) } if !isNilorEmpty(r.triggerType) { - queryParams.Add("triggerType", parameterToString(*r.triggerType)) + queryParams.Set("triggerType", parameterToString(r.triggerType)) } if !isNilorEmpty(r.sort) { - queryParams.Add("sort", parameterToString(*r.sort)) + queryParams.Set("sort", parameterToString(*r.sort)) } if !isNilorEmpty(r.order) { - queryParams.Add("order", parameterToString(*r.order)) + queryParams.Set("order", parameterToString(*r.order)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -2395,6 +3209,43 @@ type ApiPostRequest struct { body map[string]interface{} } +func (r *ApiPostRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + if v, ok := req["body"]; ok { //body + err = json.Unmarshal(v, &r.body) + if err != nil { + err = json.Unmarshal(b, &r.body) + if err != nil { + return err + } + } + } + + return nil +} + // Query parameters to be applied to the current query. func (r ApiPostRequest) WithParameters(parameters map[string]interface{}) ApiPostRequest { r.parameters = parameters @@ -2428,21 +3279,27 @@ func (c *APIClient) Post(r ApiPostRequest, opts ...Option) (map[string]interface queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } } // body params - postBody = r.body + if isNilorEmpty(r.body) { + postBody = "{}" + } else { + postBody = r.body + } req, err := c.prepareRequest(context.Background(), requestPath, http.MethodPost, postBody, headers, queryParams) if err != nil { return returnValue, err @@ -2520,6 +3377,43 @@ type ApiPutRequest struct { body map[string]interface{} } +func (r *ApiPutRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + if v, ok := req["body"]; ok { //body + err = json.Unmarshal(v, &r.body) + if err != nil { + err = json.Unmarshal(b, &r.body) + if err != nil { + return err + } + } + } + + return nil +} + // Query parameters to be applied to the current query. func (r ApiPutRequest) WithParameters(parameters map[string]interface{}) ApiPutRequest { r.parameters = parameters @@ -2553,21 +3447,27 @@ func (c *APIClient) Put(r ApiPutRequest, opts ...Option) (map[string]interface{} queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } } // body params - postBody = r.body + if isNilorEmpty(r.body) { + postBody = "{}" + } else { + postBody = r.body + } req, err := c.prepareRequest(context.Background(), requestPath, http.MethodPut, postBody, headers, queryParams) if err != nil { return returnValue, err @@ -2643,6 +3543,25 @@ type ApiRunTaskRequest struct { taskID string } +func (r *ApiRunTaskRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["taskID"]; ok { //taskID + err = json.Unmarshal(v, &r.taskID) + if err != nil { + err = json.Unmarshal(b, &r.taskID) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiRunTaskRequest func (c *APIClient) NewApiRunTaskRequest(taskID string) ApiRunTaskRequest { return ApiRunTaskRequest{ @@ -2667,7 +3586,7 @@ func (c *APIClient) RunTask(r ApiRunTaskRequest, opts ...Option) (*RunResponse, for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -2721,8 +3640,32 @@ type ApiSearchAuthenticationsRequest struct { authenticationSearch *AuthenticationSearch } -func (r ApiSearchAuthenticationsRequest) WithAuthenticationSearch(authenticationSearch AuthenticationSearch) ApiSearchAuthenticationsRequest { - r.authenticationSearch = &authenticationSearch +func (r *ApiSearchAuthenticationsRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["authenticationSearch"]; ok { //authenticationSearch + err = json.Unmarshal(v, &r.authenticationSearch) + if err != nil { + err = json.Unmarshal(b, &r.authenticationSearch) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.authenticationSearch) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiSearchAuthenticationsRequest) WithAuthenticationSearch(authenticationSearch *AuthenticationSearch) ApiSearchAuthenticationsRequest { + r.authenticationSearch = authenticationSearch return r } @@ -2750,7 +3693,7 @@ func (c *APIClient) SearchAuthentications(r ApiSearchAuthenticationsRequest, opt for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -2806,8 +3749,32 @@ type ApiSearchDestinationsRequest struct { destinationSearch *DestinationSearch } -func (r ApiSearchDestinationsRequest) WithDestinationSearch(destinationSearch DestinationSearch) ApiSearchDestinationsRequest { - r.destinationSearch = &destinationSearch +func (r *ApiSearchDestinationsRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["destinationSearch"]; ok { //destinationSearch + err = json.Unmarshal(v, &r.destinationSearch) + if err != nil { + err = json.Unmarshal(b, &r.destinationSearch) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.destinationSearch) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiSearchDestinationsRequest) WithDestinationSearch(destinationSearch *DestinationSearch) ApiSearchDestinationsRequest { + r.destinationSearch = destinationSearch return r } @@ -2835,7 +3802,7 @@ func (c *APIClient) SearchDestinations(r ApiSearchDestinationsRequest, opts ...O for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -2891,8 +3858,32 @@ type ApiSearchSourcesRequest struct { sourceSearch *SourceSearch } -func (r ApiSearchSourcesRequest) WithSourceSearch(sourceSearch SourceSearch) ApiSearchSourcesRequest { - r.sourceSearch = &sourceSearch +func (r *ApiSearchSourcesRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["sourceSearch"]; ok { //sourceSearch + err = json.Unmarshal(v, &r.sourceSearch) + if err != nil { + err = json.Unmarshal(b, &r.sourceSearch) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.sourceSearch) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiSearchSourcesRequest) WithSourceSearch(sourceSearch *SourceSearch) ApiSearchSourcesRequest { + r.sourceSearch = sourceSearch return r } @@ -2920,7 +3911,7 @@ func (c *APIClient) SearchSources(r ApiSearchSourcesRequest, opts ...Option) ([] for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -2976,8 +3967,32 @@ type ApiSearchTasksRequest struct { taskSearch *TaskSearch } -func (r ApiSearchTasksRequest) WithTaskSearch(taskSearch TaskSearch) ApiSearchTasksRequest { - r.taskSearch = &taskSearch +func (r *ApiSearchTasksRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["taskSearch"]; ok { //taskSearch + err = json.Unmarshal(v, &r.taskSearch) + if err != nil { + err = json.Unmarshal(b, &r.taskSearch) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.taskSearch) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiSearchTasksRequest) WithTaskSearch(taskSearch *TaskSearch) ApiSearchTasksRequest { + r.taskSearch = taskSearch return r } @@ -3005,7 +4020,7 @@ func (c *APIClient) SearchTasks(r ApiSearchTasksRequest, opts ...Option) ([]Task for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -3062,8 +4077,41 @@ type ApiUpdateAuthenticationRequest struct { authenticationUpdate *AuthenticationUpdate } -func (r ApiUpdateAuthenticationRequest) WithAuthenticationUpdate(authenticationUpdate AuthenticationUpdate) ApiUpdateAuthenticationRequest { - r.authenticationUpdate = &authenticationUpdate +func (r *ApiUpdateAuthenticationRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["authenticationID"]; ok { //authenticationID + err = json.Unmarshal(v, &r.authenticationID) + if err != nil { + err = json.Unmarshal(b, &r.authenticationID) + if err != nil { + return err + } + } + } + if v, ok := req["authenticationUpdate"]; ok { //authenticationUpdate + err = json.Unmarshal(v, &r.authenticationUpdate) + if err != nil { + err = json.Unmarshal(b, &r.authenticationUpdate) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.authenticationUpdate) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiUpdateAuthenticationRequest) WithAuthenticationUpdate(authenticationUpdate *AuthenticationUpdate) ApiUpdateAuthenticationRequest { + r.authenticationUpdate = authenticationUpdate return r } @@ -3094,7 +4142,7 @@ func (c *APIClient) UpdateAuthentication(r ApiUpdateAuthenticationRequest, opts for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -3151,8 +4199,41 @@ type ApiUpdateDestinationRequest struct { destinationUpdate *DestinationUpdate } -func (r ApiUpdateDestinationRequest) WithDestinationUpdate(destinationUpdate DestinationUpdate) ApiUpdateDestinationRequest { - r.destinationUpdate = &destinationUpdate +func (r *ApiUpdateDestinationRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["destinationID"]; ok { //destinationID + err = json.Unmarshal(v, &r.destinationID) + if err != nil { + err = json.Unmarshal(b, &r.destinationID) + if err != nil { + return err + } + } + } + if v, ok := req["destinationUpdate"]; ok { //destinationUpdate + err = json.Unmarshal(v, &r.destinationUpdate) + if err != nil { + err = json.Unmarshal(b, &r.destinationUpdate) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.destinationUpdate) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiUpdateDestinationRequest) WithDestinationUpdate(destinationUpdate *DestinationUpdate) ApiUpdateDestinationRequest { + r.destinationUpdate = destinationUpdate return r } @@ -3183,7 +4264,7 @@ func (c *APIClient) UpdateDestination(r ApiUpdateDestinationRequest, opts ...Opt for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -3240,8 +4321,41 @@ type ApiUpdateSourceRequest struct { sourceUpdate *SourceUpdate } -func (r ApiUpdateSourceRequest) WithSourceUpdate(sourceUpdate SourceUpdate) ApiUpdateSourceRequest { - r.sourceUpdate = &sourceUpdate +func (r *ApiUpdateSourceRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["sourceID"]; ok { //sourceID + err = json.Unmarshal(v, &r.sourceID) + if err != nil { + err = json.Unmarshal(b, &r.sourceID) + if err != nil { + return err + } + } + } + if v, ok := req["sourceUpdate"]; ok { //sourceUpdate + err = json.Unmarshal(v, &r.sourceUpdate) + if err != nil { + err = json.Unmarshal(b, &r.sourceUpdate) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.sourceUpdate) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiUpdateSourceRequest) WithSourceUpdate(sourceUpdate *SourceUpdate) ApiUpdateSourceRequest { + r.sourceUpdate = sourceUpdate return r } @@ -3272,7 +4386,7 @@ func (c *APIClient) UpdateSource(r ApiUpdateSourceRequest, opts ...Option) (*Sou for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -3329,8 +4443,41 @@ type ApiUpdateTaskRequest struct { taskUpdate *TaskUpdate } -func (r ApiUpdateTaskRequest) WithTaskUpdate(taskUpdate TaskUpdate) ApiUpdateTaskRequest { - r.taskUpdate = &taskUpdate +func (r *ApiUpdateTaskRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["taskID"]; ok { //taskID + err = json.Unmarshal(v, &r.taskID) + if err != nil { + err = json.Unmarshal(b, &r.taskID) + if err != nil { + return err + } + } + } + if v, ok := req["taskUpdate"]; ok { //taskUpdate + err = json.Unmarshal(v, &r.taskUpdate) + if err != nil { + err = json.Unmarshal(b, &r.taskUpdate) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.taskUpdate) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiUpdateTaskRequest) WithTaskUpdate(taskUpdate *TaskUpdate) ApiUpdateTaskRequest { + r.taskUpdate = taskUpdate return r } @@ -3361,7 +4508,7 @@ func (c *APIClient) UpdateTask(r ApiUpdateTaskRequest, opts ...Option) (*TaskUpd for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } diff --git a/clients/algoliasearch-client-go/algolia/ingestion/client.go b/clients/algoliasearch-client-go/algolia/ingestion/client.go index e937468995..b80e914a82 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/client.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/client.go @@ -20,6 +20,8 @@ import ( "strings" "time" + "github.com/go-playground/validator/v10" + "github.com/algolia/algoliasearch-client-go/v4/algolia/call" "github.com/algolia/algoliasearch-client-go/v4/algolia/compression" "github.com/algolia/algoliasearch-client-go/v4/algolia/internal/transport" @@ -130,7 +132,7 @@ func typeCheckParameter(obj any, expected string, name string) error { // parameterToString convert any parameters to string. func parameterToString(obj any) string { if reflect.TypeOf(obj).Kind() == reflect.Slice { - return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", "", -1), "[]") + return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", ",", -1), "[]") } else if t, ok := obj.(time.Time); ok { return t.Format(time.RFC3339) } @@ -229,11 +231,9 @@ func (c *APIClient) prepareRequest( // add header parameters, if any if len(headerParams) > 0 { - headers := http.Header{} for h, v := range headerParams { - headers[h] = []string{v} + req.Header.Add(h, v) } - req.Header = headers } // Add the user agent to the request. @@ -292,6 +292,17 @@ func newStrictDecoder(data []byte) *json.Decoder { return dec } +// A wrapper for validating a struct, returns nil if value is not a struct +func validateStruct(v any) error { + err := validator.New().Struct(v) + validationErrors, ok := err.(validator.ValidationErrors) + if ok && len(validationErrors) > 0 { + return validationErrors + } + + return nil +} + // Set request body from an any func setBody(body any, contentType string, c compression.Compression) (bodyBuf *bytes.Buffer, err error) { if body == nil { diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_auth_algolia.go b/clients/algoliasearch-client-go/algolia/ingestion/model_auth_algolia.go index 3913106b2b..101a3f9163 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_auth_algolia.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_auth_algolia.go @@ -9,9 +9,9 @@ import ( // AuthAlgolia struct for AuthAlgolia type AuthAlgolia struct { // Algolia Application ID. - AppID string `json:"appID"` + AppID string `json:"appID" validate:"required"` // Algolia API Key, with the correct rights to push to an index and change settings. - ApiKey string `json:"apiKey"` + ApiKey string `json:"apiKey" validate:"required"` } // NewAuthAlgolia instantiates a new AuthAlgolia object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_auth_api_key.go b/clients/algoliasearch-client-go/algolia/ingestion/model_auth_api_key.go index ae9b8fba23..c5f6bd1426 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_auth_api_key.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_auth_api_key.go @@ -8,7 +8,7 @@ import ( // AuthAPIKey Authentication input used for token credentials. type AuthAPIKey struct { - Key string `json:"key"` + Key string `json:"key" validate:"required"` } // NewAuthAPIKey instantiates a new AuthAPIKey object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_auth_basic.go b/clients/algoliasearch-client-go/algolia/ingestion/model_auth_basic.go index d662e69a6f..e8e185bc26 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_auth_basic.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_auth_basic.go @@ -8,8 +8,8 @@ import ( // AuthBasic Authentication input for Basic login with username and password. type AuthBasic struct { - Username string `json:"username"` - Password string `json:"password"` + Username string `json:"username" validate:"required"` + Password string `json:"password" validate:"required"` } // NewAuthBasic instantiates a new AuthBasic object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_auth_google_service_account.go b/clients/algoliasearch-client-go/algolia/ingestion/model_auth_google_service_account.go index 107f717efe..cf5b10d8bf 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_auth_google_service_account.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_auth_google_service_account.go @@ -9,9 +9,9 @@ import ( // AuthGoogleServiceAccount Authentication input to connect to a Google service (e.g. BigQuery). type AuthGoogleServiceAccount struct { // Email address of the Service Account. - ClientEmail string `json:"clientEmail"` + ClientEmail string `json:"clientEmail" validate:"required"` // Private key of the Service Account. - PrivateKey string `json:"privateKey"` + PrivateKey string `json:"privateKey" validate:"required"` } // NewAuthGoogleServiceAccount instantiates a new AuthGoogleServiceAccount object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_auth_input.go b/clients/algoliasearch-client-go/algolia/ingestion/model_auth_input.go index 010078addb..f5db6c6d46 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_auth_input.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_auth_input.go @@ -53,15 +53,14 @@ func AuthOAuthAsAuthInput(v *AuthOAuth) AuthInput { // Unmarshal JSON data into one of the pointers in the struct func (dst *AuthInput) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into AuthAPIKey err = newStrictDecoder(data).Decode(&dst.AuthAPIKey) - if err == nil { + if err == nil && validateStruct(dst.AuthAPIKey) == nil { jsonAuthAPIKey, _ := json.Marshal(dst.AuthAPIKey) if string(jsonAuthAPIKey) == "{}" { // empty struct dst.AuthAPIKey = nil } else { - match++ + return nil } } else { dst.AuthAPIKey = nil @@ -69,12 +68,12 @@ func (dst *AuthInput) UnmarshalJSON(data []byte) error { // try to unmarshal data into AuthAlgolia err = newStrictDecoder(data).Decode(&dst.AuthAlgolia) - if err == nil { + if err == nil && validateStruct(dst.AuthAlgolia) == nil { jsonAuthAlgolia, _ := json.Marshal(dst.AuthAlgolia) if string(jsonAuthAlgolia) == "{}" { // empty struct dst.AuthAlgolia = nil } else { - match++ + return nil } } else { dst.AuthAlgolia = nil @@ -82,12 +81,12 @@ func (dst *AuthInput) UnmarshalJSON(data []byte) error { // try to unmarshal data into AuthBasic err = newStrictDecoder(data).Decode(&dst.AuthBasic) - if err == nil { + if err == nil && validateStruct(dst.AuthBasic) == nil { jsonAuthBasic, _ := json.Marshal(dst.AuthBasic) if string(jsonAuthBasic) == "{}" { // empty struct dst.AuthBasic = nil } else { - match++ + return nil } } else { dst.AuthBasic = nil @@ -95,12 +94,12 @@ func (dst *AuthInput) UnmarshalJSON(data []byte) error { // try to unmarshal data into AuthGoogleServiceAccount err = newStrictDecoder(data).Decode(&dst.AuthGoogleServiceAccount) - if err == nil { + if err == nil && validateStruct(dst.AuthGoogleServiceAccount) == nil { jsonAuthGoogleServiceAccount, _ := json.Marshal(dst.AuthGoogleServiceAccount) if string(jsonAuthGoogleServiceAccount) == "{}" { // empty struct dst.AuthGoogleServiceAccount = nil } else { - match++ + return nil } } else { dst.AuthGoogleServiceAccount = nil @@ -108,31 +107,18 @@ func (dst *AuthInput) UnmarshalJSON(data []byte) error { // try to unmarshal data into AuthOAuth err = newStrictDecoder(data).Decode(&dst.AuthOAuth) - if err == nil { + if err == nil && validateStruct(dst.AuthOAuth) == nil { jsonAuthOAuth, _ := json.Marshal(dst.AuthOAuth) if string(jsonAuthOAuth) == "{}" { // empty struct dst.AuthOAuth = nil } else { - match++ + return nil } } else { dst.AuthOAuth = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.AuthAPIKey = nil - dst.AuthAlgolia = nil - dst.AuthBasic = nil - dst.AuthGoogleServiceAccount = nil - dst.AuthOAuth = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(AuthInput)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(AuthInput)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(AuthInput)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_auth_o_auth.go b/clients/algoliasearch-client-go/algolia/ingestion/model_auth_o_auth.go index b1242f1b64..e99ecf3e13 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_auth_o_auth.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_auth_o_auth.go @@ -9,11 +9,11 @@ import ( // AuthOAuth Authentication input for OAuth login. type AuthOAuth struct { // The OAuth endpoint URL. - Url string `json:"url"` + Url string `json:"url" validate:"required"` // The clientID. - ClientId string `json:"client_id"` + ClientId string `json:"client_id" validate:"required"` // The secret. - ClientSecret string `json:"client_secret"` + ClientSecret string `json:"client_secret" validate:"required"` } // NewAuthOAuth instantiates a new AuthOAuth object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_authentication.go b/clients/algoliasearch-client-go/algolia/ingestion/model_authentication.go index 36e9d3269d..411bbd6d4e 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_authentication.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_authentication.go @@ -9,13 +9,13 @@ import ( // Authentication An authentication is used to login into a Source or a Destination. type Authentication struct { // The authentication UUID. - AuthenticationID string `json:"authenticationID"` - Type AuthenticationType `json:"type"` + AuthenticationID string `json:"authenticationID" validate:"required"` + Type AuthenticationType `json:"type" validate:"required"` // An human readable name describing the object. - Name string `json:"name"` + Name string `json:"name" validate:"required"` Platform *Platform `json:"platform,omitempty"` // Date of creation (RFC3339 format). - CreatedAt string `json:"createdAt"` + CreatedAt string `json:"createdAt" validate:"required"` // Date of last update (RFC3339 format). UpdatedAt *string `json:"updatedAt,omitempty"` } diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_authentication_create.go b/clients/algoliasearch-client-go/algolia/ingestion/model_authentication_create.go index 48b05d96e5..9c1b107cc7 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_authentication_create.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_authentication_create.go @@ -8,11 +8,11 @@ import ( // AuthenticationCreate The payload when creating an authentication. type AuthenticationCreate struct { - Type AuthenticationType `json:"type"` + Type AuthenticationType `json:"type" validate:"required"` // An human readable name describing the object. - Name string `json:"name"` + Name string `json:"name" validate:"required"` Platform *Platform `json:"platform,omitempty"` - Input AuthInput `json:"input"` + Input AuthInput `json:"input" validate:"required"` } type AuthenticationCreateOption func(f *AuthenticationCreate) diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_authentication_create_response.go b/clients/algoliasearch-client-go/algolia/ingestion/model_authentication_create_response.go index 2edf546994..3ea31af409 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_authentication_create_response.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_authentication_create_response.go @@ -9,11 +9,11 @@ import ( // AuthenticationCreateResponse Response from the API when the Authentication is successfully created. type AuthenticationCreateResponse struct { // The authentication UUID. - AuthenticationID string `json:"authenticationID"` + AuthenticationID string `json:"authenticationID" validate:"required"` // An human readable name describing the object. - Name string `json:"name"` + Name string `json:"name" validate:"required"` // Date of creation (RFC3339 format). - CreatedAt string `json:"createdAt"` + CreatedAt string `json:"createdAt" validate:"required"` } // NewAuthenticationCreateResponse instantiates a new AuthenticationCreateResponse object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_authentication_input.go b/clients/algoliasearch-client-go/algolia/ingestion/model_authentication_input.go index a6c5569ca7..dcc8ebef02 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_authentication_input.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_authentication_input.go @@ -8,7 +8,7 @@ import ( // AuthenticationInput The authentication input property stores the (encrypted) credentials. type AuthenticationInput struct { - Input AuthInput `json:"input"` + Input AuthInput `json:"input" validate:"required"` } // NewAuthenticationInput instantiates a new AuthenticationInput object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_authentication_search.go b/clients/algoliasearch-client-go/algolia/ingestion/model_authentication_search.go index 8e6263c1b4..12ef052a67 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_authentication_search.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_authentication_search.go @@ -8,7 +8,7 @@ import ( // AuthenticationSearch Payload to search for multiple authentications, based on the given `authenticationIDs`. type AuthenticationSearch struct { - AuthenticationIDs []string `json:"authenticationIDs"` + AuthenticationIDs []string `json:"authenticationIDs" validate:"required"` } // NewAuthenticationSearch instantiates a new AuthenticationSearch object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_authentication_update_response.go b/clients/algoliasearch-client-go/algolia/ingestion/model_authentication_update_response.go index 88bce51a19..6b9f3476c3 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_authentication_update_response.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_authentication_update_response.go @@ -9,11 +9,11 @@ import ( // AuthenticationUpdateResponse Response from the API when the Authentication is successfully updated. type AuthenticationUpdateResponse struct { // The authentication UUID. - AuthenticationID string `json:"authenticationID"` + AuthenticationID string `json:"authenticationID" validate:"required"` // An human readable name describing the object. - Name string `json:"name"` + Name string `json:"name" validate:"required"` // Date of last update (RFC3339 format). - UpdatedAt string `json:"updatedAt"` + UpdatedAt string `json:"updatedAt" validate:"required"` } // NewAuthenticationUpdateResponse instantiates a new AuthenticationUpdateResponse object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_authentication_with_input.go b/clients/algoliasearch-client-go/algolia/ingestion/model_authentication_with_input.go index ebc9d5bd2a..7fc4f1ea3d 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_authentication_with_input.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_authentication_with_input.go @@ -9,16 +9,16 @@ import ( // AuthenticationWithInput struct for AuthenticationWithInput type AuthenticationWithInput struct { // The authentication UUID. - AuthenticationID string `json:"authenticationID"` - Type AuthenticationType `json:"type"` + AuthenticationID string `json:"authenticationID" validate:"required"` + Type AuthenticationType `json:"type" validate:"required"` // An human readable name describing the object. - Name string `json:"name"` + Name string `json:"name" validate:"required"` Platform *Platform `json:"platform,omitempty"` // Date of creation (RFC3339 format). - CreatedAt string `json:"createdAt"` + CreatedAt string `json:"createdAt" validate:"required"` // Date of last update (RFC3339 format). UpdatedAt *string `json:"updatedAt,omitempty"` - Input AuthInput `json:"input"` + Input AuthInput `json:"input" validate:"required"` } type AuthenticationWithInputOption func(f *AuthenticationWithInput) diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_big_commerce_channel.go b/clients/algoliasearch-client-go/algolia/ingestion/model_big_commerce_channel.go index 1d41152129..11366dc947 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_big_commerce_channel.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_big_commerce_channel.go @@ -9,7 +9,7 @@ import ( // BigCommerceChannel struct for BigCommerceChannel type BigCommerceChannel struct { // The ID of the bigcommerce channel. - Id int32 `json:"id"` + Id int32 `json:"id" validate:"required"` // An array of currencies for the given channel `ID`, a currency is a trigram string that represents the currency code. Currencies []string `json:"currencies,omitempty"` } diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_delete_response.go b/clients/algoliasearch-client-go/algolia/ingestion/model_delete_response.go index 7d0d81c084..699220dae1 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_delete_response.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_delete_response.go @@ -9,7 +9,7 @@ import ( // DeleteResponse struct for DeleteResponse type DeleteResponse struct { // Date of deletion (RFC3339 format). - DeletedAt string `json:"deletedAt"` + DeletedAt string `json:"deletedAt" validate:"required"` } // NewDeleteResponse instantiates a new DeleteResponse object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_destination.go b/clients/algoliasearch-client-go/algolia/ingestion/model_destination.go index 59e2b7008c..21601939a7 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_destination.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_destination.go @@ -9,13 +9,13 @@ import ( // Destination A destination describe how the data is indexed on the Algolia side. type Destination struct { // The destination UUID. - DestinationID string `json:"destinationID"` - Type DestinationType `json:"type"` + DestinationID string `json:"destinationID" validate:"required"` + Type DestinationType `json:"type" validate:"required"` // An human readable name describing the object. - Name string `json:"name"` - Input DestinationInput `json:"input"` + Name string `json:"name" validate:"required"` + Input DestinationInput `json:"input" validate:"required"` // Date of creation (RFC3339 format). - CreatedAt string `json:"createdAt"` + CreatedAt string `json:"createdAt" validate:"required"` // Date of last update (RFC3339 format). UpdatedAt *string `json:"updatedAt,omitempty"` AuthenticationID *string `json:"authenticationID,omitempty"` diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_destination_create.go b/clients/algoliasearch-client-go/algolia/ingestion/model_destination_create.go index 2950edee97..0d98817e14 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_destination_create.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_destination_create.go @@ -8,10 +8,10 @@ import ( // DestinationCreate The payload when creating a destination. type DestinationCreate struct { - Type DestinationType `json:"type"` + Type DestinationType `json:"type" validate:"required"` // An human readable name describing the object. - Name string `json:"name"` - Input DestinationInput `json:"input"` + Name string `json:"name" validate:"required"` + Input DestinationInput `json:"input" validate:"required"` // The authentication UUID. AuthenticationID *string `json:"authenticationID,omitempty"` } diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_destination_create_response.go b/clients/algoliasearch-client-go/algolia/ingestion/model_destination_create_response.go index 7fca43a01c..f66fbebe67 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_destination_create_response.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_destination_create_response.go @@ -9,11 +9,11 @@ import ( // DestinationCreateResponse Response from the API when the Destination is successfully created. type DestinationCreateResponse struct { // The destination UUID. - DestinationID string `json:"destinationID"` + DestinationID string `json:"destinationID" validate:"required"` // An human readable name describing the object. - Name string `json:"name"` + Name string `json:"name" validate:"required"` // Date of creation (RFC3339 format). - CreatedAt string `json:"createdAt"` + CreatedAt string `json:"createdAt" validate:"required"` } // NewDestinationCreateResponse instantiates a new DestinationCreateResponse object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_destination_index_name.go b/clients/algoliasearch-client-go/algolia/ingestion/model_destination_index_name.go index e7656e961e..9470e5a322 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_destination_index_name.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_destination_index_name.go @@ -9,7 +9,7 @@ import ( // DestinationIndexName struct for DestinationIndexName type DestinationIndexName struct { // The index name to store data in. - IndexName string `json:"indexName"` + IndexName string `json:"indexName" validate:"required"` } // NewDestinationIndexName instantiates a new DestinationIndexName object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_destination_index_prefix.go b/clients/algoliasearch-client-go/algolia/ingestion/model_destination_index_prefix.go index 07b1c03602..259a1d3f46 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_destination_index_prefix.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_destination_index_prefix.go @@ -9,7 +9,7 @@ import ( // DestinationIndexPrefix struct for DestinationIndexPrefix type DestinationIndexPrefix struct { // The prefix of the final index name. - IndexPrefix string `json:"indexPrefix"` + IndexPrefix string `json:"indexPrefix" validate:"required"` } // NewDestinationIndexPrefix instantiates a new DestinationIndexPrefix object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_destination_input.go b/clients/algoliasearch-client-go/algolia/ingestion/model_destination_input.go index d38ee2b87b..67dfaf962b 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_destination_input.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_destination_input.go @@ -29,15 +29,14 @@ func DestinationIndexPrefixAsDestinationInput(v *DestinationIndexPrefix) Destina // Unmarshal JSON data into one of the pointers in the struct func (dst *DestinationInput) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into DestinationIndexName err = newStrictDecoder(data).Decode(&dst.DestinationIndexName) - if err == nil { + if err == nil && validateStruct(dst.DestinationIndexName) == nil { jsonDestinationIndexName, _ := json.Marshal(dst.DestinationIndexName) if string(jsonDestinationIndexName) == "{}" { // empty struct dst.DestinationIndexName = nil } else { - match++ + return nil } } else { dst.DestinationIndexName = nil @@ -45,28 +44,18 @@ func (dst *DestinationInput) UnmarshalJSON(data []byte) error { // try to unmarshal data into DestinationIndexPrefix err = newStrictDecoder(data).Decode(&dst.DestinationIndexPrefix) - if err == nil { + if err == nil && validateStruct(dst.DestinationIndexPrefix) == nil { jsonDestinationIndexPrefix, _ := json.Marshal(dst.DestinationIndexPrefix) if string(jsonDestinationIndexPrefix) == "{}" { // empty struct dst.DestinationIndexPrefix = nil } else { - match++ + return nil } } else { dst.DestinationIndexPrefix = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.DestinationIndexName = nil - dst.DestinationIndexPrefix = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(DestinationInput)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(DestinationInput)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(DestinationInput)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_destination_search.go b/clients/algoliasearch-client-go/algolia/ingestion/model_destination_search.go index f829459a3e..cd16cbedbc 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_destination_search.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_destination_search.go @@ -8,7 +8,7 @@ import ( // DestinationSearch Payload to search for multiple destinations, based on the given `destinationIDs`. type DestinationSearch struct { - DestinationIDs []string `json:"destinationIDs"` + DestinationIDs []string `json:"destinationIDs" validate:"required"` } // NewDestinationSearch instantiates a new DestinationSearch object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_destination_update_response.go b/clients/algoliasearch-client-go/algolia/ingestion/model_destination_update_response.go index 820c760e3c..1c6b879de3 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_destination_update_response.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_destination_update_response.go @@ -9,11 +9,11 @@ import ( // DestinationUpdateResponse Response from the API when the Destination is successfully updated. type DestinationUpdateResponse struct { // The destination UUID. - DestinationID string `json:"destinationID"` + DestinationID string `json:"destinationID" validate:"required"` // An human readable name describing the object. - Name string `json:"name"` + Name string `json:"name" validate:"required"` // Date of last update (RFC3339 format). - UpdatedAt string `json:"updatedAt"` + UpdatedAt string `json:"updatedAt" validate:"required"` } // NewDestinationUpdateResponse instantiates a new DestinationUpdateResponse object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_event.go b/clients/algoliasearch-client-go/algolia/ingestion/model_event.go index 35d9819e17..4df30b9845 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_event.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_event.go @@ -9,16 +9,16 @@ import ( // Event An event describe a step of the task execution flow.. type Event struct { // The event UUID. - EventID string `json:"eventID"` + EventID string `json:"eventID" validate:"required"` // The run UUID. - RunID string `json:"runID"` + RunID string `json:"runID" validate:"required"` // The parent event, the cause of this event. ParentID *string `json:"parentID,omitempty"` - Status EventStatus `json:"status"` - Type EventType `json:"type"` + Status EventStatus `json:"status" validate:"required"` + Type EventType `json:"type" validate:"required"` Data map[string]interface{} `json:"data,omitempty"` // Date of publish (RFC3339 format). - PublishedAt string `json:"publishedAt"` + PublishedAt string `json:"publishedAt" validate:"required"` } type EventOption func(f *Event) diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_list_authentications_response.go b/clients/algoliasearch-client-go/algolia/ingestion/model_list_authentications_response.go index 6e07626721..23b2727e79 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_list_authentications_response.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_list_authentications_response.go @@ -8,8 +8,8 @@ import ( // ListAuthenticationsResponse struct for ListAuthenticationsResponse type ListAuthenticationsResponse struct { - Authentications []Authentication `json:"authentications"` - Pagination Pagination `json:"pagination"` + Authentications []Authentication `json:"authentications" validate:"required"` + Pagination Pagination `json:"pagination" validate:"required"` } // NewListAuthenticationsResponse instantiates a new ListAuthenticationsResponse object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_list_destinations_response.go b/clients/algoliasearch-client-go/algolia/ingestion/model_list_destinations_response.go index 63b7d9e9dc..cc731a993a 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_list_destinations_response.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_list_destinations_response.go @@ -8,8 +8,8 @@ import ( // ListDestinationsResponse struct for ListDestinationsResponse type ListDestinationsResponse struct { - Destinations []Destination `json:"destinations"` - Pagination Pagination `json:"pagination"` + Destinations []Destination `json:"destinations" validate:"required"` + Pagination Pagination `json:"pagination" validate:"required"` } // NewListDestinationsResponse instantiates a new ListDestinationsResponse object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_list_events_response.go b/clients/algoliasearch-client-go/algolia/ingestion/model_list_events_response.go index fb1c8cf401..c693409a2e 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_list_events_response.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_list_events_response.go @@ -8,8 +8,8 @@ import ( // ListEventsResponse struct for ListEventsResponse type ListEventsResponse struct { - Events []Event `json:"events"` - Pagination Pagination `json:"pagination"` + Events []Event `json:"events" validate:"required"` + Pagination Pagination `json:"pagination" validate:"required"` } // NewListEventsResponse instantiates a new ListEventsResponse object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_list_sources_response.go b/clients/algoliasearch-client-go/algolia/ingestion/model_list_sources_response.go index a5adf93a13..72bfcf3efc 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_list_sources_response.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_list_sources_response.go @@ -8,8 +8,8 @@ import ( // ListSourcesResponse struct for ListSourcesResponse type ListSourcesResponse struct { - Sources []Source `json:"sources"` - Pagination Pagination `json:"pagination"` + Sources []Source `json:"sources" validate:"required"` + Pagination Pagination `json:"pagination" validate:"required"` } // NewListSourcesResponse instantiates a new ListSourcesResponse object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_list_tasks_response.go b/clients/algoliasearch-client-go/algolia/ingestion/model_list_tasks_response.go index d0b9bbb433..7ca22c9827 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_list_tasks_response.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_list_tasks_response.go @@ -8,8 +8,8 @@ import ( // ListTasksResponse A list of tasks with pagination details. type ListTasksResponse struct { - Tasks []Task `json:"tasks"` - Pagination Pagination `json:"pagination"` + Tasks []Task `json:"tasks" validate:"required"` + Pagination Pagination `json:"pagination" validate:"required"` } // NewListTasksResponse instantiates a new ListTasksResponse object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_on_demand_trigger.go b/clients/algoliasearch-client-go/algolia/ingestion/model_on_demand_trigger.go index 7b937d2f84..c4aa6901be 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_on_demand_trigger.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_on_demand_trigger.go @@ -8,7 +8,7 @@ import ( // OnDemandTrigger The trigger information of a task of type `onDemand`. type OnDemandTrigger struct { - Type OnDemandTriggerType `json:"type"` + Type OnDemandTriggerType `json:"type" validate:"required"` // The last time the scheduled task ran (RFC3339 format). LastRun *string `json:"lastRun,omitempty"` } diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_on_demand_trigger_input.go b/clients/algoliasearch-client-go/algolia/ingestion/model_on_demand_trigger_input.go index 82c045d508..965915a9d3 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_on_demand_trigger_input.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_on_demand_trigger_input.go @@ -8,7 +8,7 @@ import ( // OnDemandTriggerInput The trigger information of a task of type `onDemand`. type OnDemandTriggerInput struct { - Type OnDemandTriggerType `json:"type"` + Type OnDemandTriggerType `json:"type" validate:"required"` } // NewOnDemandTriggerInput instantiates a new OnDemandTriggerInput object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_pagination.go b/clients/algoliasearch-client-go/algolia/ingestion/model_pagination.go index e20e753e42..2adfd31328 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_pagination.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_pagination.go @@ -8,10 +8,10 @@ import ( // Pagination struct for Pagination type Pagination struct { - NbPages int32 `json:"nbPages"` - Page int32 `json:"page"` - NbItems int32 `json:"nbItems"` - ItemsPerPage int32 `json:"itemsPerPage"` + NbPages int32 `json:"nbPages" validate:"required"` + Page int32 `json:"page" validate:"required"` + NbItems int32 `json:"nbItems" validate:"required"` + ItemsPerPage int32 `json:"itemsPerPage" validate:"required"` } // NewPagination instantiates a new Pagination object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_platform_with_none.go b/clients/algoliasearch-client-go/algolia/ingestion/model_platform_with_none.go index 55d9e9ead8..dbb3a1f355 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_platform_with_none.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_platform_with_none.go @@ -29,15 +29,14 @@ func PlatformNoneAsPlatformWithNone(v *PlatformNone) PlatformWithNone { // Unmarshal JSON data into one of the pointers in the struct func (dst *PlatformWithNone) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into Platform err = newStrictDecoder(data).Decode(&dst.Platform) - if err == nil { + if err == nil && validateStruct(dst.Platform) == nil { jsonPlatform, _ := json.Marshal(dst.Platform) if string(jsonPlatform) == "{}" { // empty struct dst.Platform = nil } else { - match++ + return nil } } else { dst.Platform = nil @@ -45,28 +44,18 @@ func (dst *PlatformWithNone) UnmarshalJSON(data []byte) error { // try to unmarshal data into PlatformNone err = newStrictDecoder(data).Decode(&dst.PlatformNone) - if err == nil { + if err == nil && validateStruct(dst.PlatformNone) == nil { jsonPlatformNone, _ := json.Marshal(dst.PlatformNone) if string(jsonPlatformNone) == "{}" { // empty struct dst.PlatformNone = nil } else { - match++ + return nil } } else { dst.PlatformNone = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.Platform = nil - dst.PlatformNone = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(PlatformWithNone)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(PlatformWithNone)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(PlatformWithNone)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_run.go b/clients/algoliasearch-client-go/algolia/ingestion/model_run.go index ecf2913d5e..9f237030c2 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_run.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_run.go @@ -9,20 +9,20 @@ import ( // Run struct for Run type Run struct { // The run UUID. - RunID string `json:"runID"` - AppID string `json:"appID"` + RunID string `json:"runID" validate:"required"` + AppID string `json:"appID" validate:"required"` // The task UUID. - TaskID string `json:"taskID"` - Status RunStatus `json:"status"` + TaskID string `json:"taskID" validate:"required"` + Status RunStatus `json:"status" validate:"required"` Progress *RunProgress `json:"progress,omitempty"` Outcome *RunOutcome `json:"outcome,omitempty"` // Explains the result of outcome. Reason *string `json:"reason,omitempty"` - Type RunType `json:"type"` + Type RunType `json:"type" validate:"required"` // Date of creation (RFC3339 format). - CreatedAt string `json:"createdAt"` + CreatedAt string `json:"createdAt" validate:"required"` // Date of last update (RFC3339 format). - UpdatedAt string `json:"updatedAt"` + UpdatedAt string `json:"updatedAt" validate:"required"` // Date of start (RFC3339 format). StartedAt *string `json:"startedAt,omitempty"` // Date of finish (RFC3339 format). diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_run_list_response.go b/clients/algoliasearch-client-go/algolia/ingestion/model_run_list_response.go index 2ea36d8baf..d65f5e91d9 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_run_list_response.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_run_list_response.go @@ -8,8 +8,8 @@ import ( // RunListResponse struct for RunListResponse type RunListResponse struct { - Runs []Run `json:"runs"` - Pagination Pagination `json:"pagination"` + Runs []Run `json:"runs" validate:"required"` + Pagination Pagination `json:"pagination" validate:"required"` } // NewRunListResponse instantiates a new RunListResponse object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_run_response.go b/clients/algoliasearch-client-go/algolia/ingestion/model_run_response.go index acccb034fb..3b4cc47354 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_run_response.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_run_response.go @@ -9,9 +9,9 @@ import ( // RunResponse The response from the run task API, containing an Observability Run ID and the time it was created at. type RunResponse struct { // The run UUID. - RunID string `json:"runID"` + RunID string `json:"runID" validate:"required"` // Date of creation (RFC3339 format). - CreatedAt string `json:"createdAt"` + CreatedAt string `json:"createdAt" validate:"required"` } // NewRunResponse instantiates a new RunResponse object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_schedule_trigger.go b/clients/algoliasearch-client-go/algolia/ingestion/model_schedule_trigger.go index 730f5beb4e..00521b5fe0 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_schedule_trigger.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_schedule_trigger.go @@ -8,13 +8,13 @@ import ( // ScheduleTrigger The trigger information for a task of type 'schedule'. type ScheduleTrigger struct { - Type ScheduleTriggerType `json:"type"` + Type ScheduleTriggerType `json:"type" validate:"required"` // A cron expression that represent at which regularity the task should run. - Cron string `json:"cron"` + Cron string `json:"cron" validate:"required"` // The last time the scheduled task ran (RFC3339 format). LastRun *string `json:"lastRun,omitempty"` // The next scheduled run of the task (RFC3339 format). - NextRun string `json:"nextRun"` + NextRun string `json:"nextRun" validate:"required"` } type ScheduleTriggerOption func(f *ScheduleTrigger) diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_schedule_trigger_input.go b/clients/algoliasearch-client-go/algolia/ingestion/model_schedule_trigger_input.go index 7930c9a48e..3bc0e07965 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_schedule_trigger_input.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_schedule_trigger_input.go @@ -8,9 +8,9 @@ import ( // ScheduleTriggerInput The trigger input for a task of type 'schedule'. type ScheduleTriggerInput struct { - Type ScheduleTriggerType `json:"type"` + Type ScheduleTriggerType `json:"type" validate:"required"` // A cron expression that represent at which regularity the task should run. - Cron string `json:"cron"` + Cron string `json:"cron" validate:"required"` } // NewScheduleTriggerInput instantiates a new ScheduleTriggerInput object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_source.go b/clients/algoliasearch-client-go/algolia/ingestion/model_source.go index 9a6e5c49d3..28a414e8e0 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_source.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_source.go @@ -9,14 +9,14 @@ import ( // Source struct for Source type Source struct { // The source UUID. - SourceID string `json:"sourceID"` - Type SourceType `json:"type"` - Name string `json:"name"` - Input SourceInput `json:"input"` + SourceID string `json:"sourceID" validate:"required"` + Type SourceType `json:"type" validate:"required"` + Name string `json:"name" validate:"required"` + Input SourceInput `json:"input" validate:"required"` // The authentication UUID. AuthenticationID *string `json:"authenticationID,omitempty"` // Date of creation (RFC3339 format). - CreatedAt string `json:"createdAt"` + CreatedAt string `json:"createdAt" validate:"required"` // Date of last update (RFC3339 format). UpdatedAt *string `json:"updatedAt,omitempty"` } diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_source_big_query.go b/clients/algoliasearch-client-go/algolia/ingestion/model_source_big_query.go index 228c562f5b..e318e572ab 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_source_big_query.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_source_big_query.go @@ -9,9 +9,9 @@ import ( // SourceBigQuery struct for SourceBigQuery type SourceBigQuery struct { // Project ID of the BigQuery Source. - ProjectID string `json:"projectID"` + ProjectID string `json:"projectID" validate:"required"` // Dataset ID of the BigQuery Source. - DatasetID string `json:"datasetID"` + DatasetID string `json:"datasetID" validate:"required"` DataType *BigQueryDataType `json:"dataType,omitempty"` // Table name (for default BQ). Table *string `json:"table,omitempty"` diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_source_commercetools.go b/clients/algoliasearch-client-go/algolia/ingestion/model_source_commercetools.go index 3141a934f2..5d781a9622 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_source_commercetools.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_source_commercetools.go @@ -11,8 +11,8 @@ type SourceCommercetools struct { StoreKeys []string `json:"storeKeys,omitempty"` // Array of locales that must match the following pattern: ^[a-z]{2}(-[A-Z]{2})?$. For example [\"fr-FR\", \"en\"]. Locales []string `json:"locales,omitempty"` - Url string `json:"url"` - ProjectKey string `json:"projectKey"` + Url string `json:"url" validate:"required"` + ProjectKey string `json:"projectKey" validate:"required"` } type SourceCommercetoolsOption func(f *SourceCommercetools) diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_source_create.go b/clients/algoliasearch-client-go/algolia/ingestion/model_source_create.go index 72a26c8e7a..4c773cf7b9 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_source_create.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_source_create.go @@ -8,9 +8,9 @@ import ( // SourceCreate struct for SourceCreate type SourceCreate struct { - Type SourceType `json:"type"` - Name string `json:"name"` - Input SourceInput `json:"input"` + Type SourceType `json:"type" validate:"required"` + Name string `json:"name" validate:"required"` + Input SourceInput `json:"input" validate:"required"` // The authentication UUID. AuthenticationID *string `json:"authenticationID,omitempty"` } diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_source_create_response.go b/clients/algoliasearch-client-go/algolia/ingestion/model_source_create_response.go index 70083cf873..879351dd74 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_source_create_response.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_source_create_response.go @@ -9,10 +9,10 @@ import ( // SourceCreateResponse struct for SourceCreateResponse type SourceCreateResponse struct { // The source UUID. - SourceID string `json:"sourceID"` - Name string `json:"name"` + SourceID string `json:"sourceID" validate:"required"` + Name string `json:"name" validate:"required"` // Date of creation (RFC3339 format). - CreatedAt string `json:"createdAt"` + CreatedAt string `json:"createdAt" validate:"required"` } // NewSourceCreateResponse instantiates a new SourceCreateResponse object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_source_csv.go b/clients/algoliasearch-client-go/algolia/ingestion/model_source_csv.go index f2ced9cee0..ff97560980 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_source_csv.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_source_csv.go @@ -9,7 +9,7 @@ import ( // SourceCSV struct for SourceCSV type SourceCSV struct { // The URL of the file. - Url string `json:"url"` + Url string `json:"url" validate:"required"` // The name of the column that contains the unique ID, used as `objectID` in Algolia. UniqueIDColumn *string `json:"uniqueIDColumn,omitempty"` // Mapping of type for every column. For example {\"myColumn\": \"boolean\", \"myOtherColumn\": \"json\"}. diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_source_input.go b/clients/algoliasearch-client-go/algolia/ingestion/model_source_input.go index 9c3bc4cdde..f94d435d78 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_source_input.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_source_input.go @@ -53,15 +53,14 @@ func SourceJSONAsSourceInput(v *SourceJSON) SourceInput { // Unmarshal JSON data into one of the pointers in the struct func (dst *SourceInput) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into SourceBigCommerce err = newStrictDecoder(data).Decode(&dst.SourceBigCommerce) - if err == nil { + if err == nil && validateStruct(dst.SourceBigCommerce) == nil { jsonSourceBigCommerce, _ := json.Marshal(dst.SourceBigCommerce) if string(jsonSourceBigCommerce) == "{}" { // empty struct dst.SourceBigCommerce = nil } else { - match++ + return nil } } else { dst.SourceBigCommerce = nil @@ -69,12 +68,12 @@ func (dst *SourceInput) UnmarshalJSON(data []byte) error { // try to unmarshal data into SourceBigQuery err = newStrictDecoder(data).Decode(&dst.SourceBigQuery) - if err == nil { + if err == nil && validateStruct(dst.SourceBigQuery) == nil { jsonSourceBigQuery, _ := json.Marshal(dst.SourceBigQuery) if string(jsonSourceBigQuery) == "{}" { // empty struct dst.SourceBigQuery = nil } else { - match++ + return nil } } else { dst.SourceBigQuery = nil @@ -82,12 +81,12 @@ func (dst *SourceInput) UnmarshalJSON(data []byte) error { // try to unmarshal data into SourceCSV err = newStrictDecoder(data).Decode(&dst.SourceCSV) - if err == nil { + if err == nil && validateStruct(dst.SourceCSV) == nil { jsonSourceCSV, _ := json.Marshal(dst.SourceCSV) if string(jsonSourceCSV) == "{}" { // empty struct dst.SourceCSV = nil } else { - match++ + return nil } } else { dst.SourceCSV = nil @@ -95,12 +94,12 @@ func (dst *SourceInput) UnmarshalJSON(data []byte) error { // try to unmarshal data into SourceCommercetools err = newStrictDecoder(data).Decode(&dst.SourceCommercetools) - if err == nil { + if err == nil && validateStruct(dst.SourceCommercetools) == nil { jsonSourceCommercetools, _ := json.Marshal(dst.SourceCommercetools) if string(jsonSourceCommercetools) == "{}" { // empty struct dst.SourceCommercetools = nil } else { - match++ + return nil } } else { dst.SourceCommercetools = nil @@ -108,31 +107,18 @@ func (dst *SourceInput) UnmarshalJSON(data []byte) error { // try to unmarshal data into SourceJSON err = newStrictDecoder(data).Decode(&dst.SourceJSON) - if err == nil { + if err == nil && validateStruct(dst.SourceJSON) == nil { jsonSourceJSON, _ := json.Marshal(dst.SourceJSON) if string(jsonSourceJSON) == "{}" { // empty struct dst.SourceJSON = nil } else { - match++ + return nil } } else { dst.SourceJSON = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.SourceBigCommerce = nil - dst.SourceBigQuery = nil - dst.SourceCSV = nil - dst.SourceCommercetools = nil - dst.SourceJSON = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(SourceInput)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(SourceInput)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(SourceInput)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_source_json.go b/clients/algoliasearch-client-go/algolia/ingestion/model_source_json.go index cfca93ae4a..38391e56bd 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_source_json.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_source_json.go @@ -9,7 +9,7 @@ import ( // SourceJSON struct for SourceJSON type SourceJSON struct { // The URL of the file. - Url string `json:"url"` + Url string `json:"url" validate:"required"` // The name of the column that contains the unique ID, used as `objectID` in Algolia. UniqueIDColumn *string `json:"uniqueIDColumn,omitempty"` Method *MethodType `json:"method,omitempty"` diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_source_search.go b/clients/algoliasearch-client-go/algolia/ingestion/model_source_search.go index 15ed83913c..94311c4fef 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_source_search.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_source_search.go @@ -8,7 +8,7 @@ import ( // SourceSearch struct for SourceSearch type SourceSearch struct { - SourceIDs []string `json:"sourceIDs"` + SourceIDs []string `json:"sourceIDs" validate:"required"` } // NewSourceSearch instantiates a new SourceSearch object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_source_update_input.go b/clients/algoliasearch-client-go/algolia/ingestion/model_source_update_input.go index 2e87232fee..540345ce9d 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_source_update_input.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_source_update_input.go @@ -45,15 +45,14 @@ func SourceUpdateCommercetoolsAsSourceUpdateInput(v *SourceUpdateCommercetools) // Unmarshal JSON data into one of the pointers in the struct func (dst *SourceUpdateInput) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into SourceBigQuery err = newStrictDecoder(data).Decode(&dst.SourceBigQuery) - if err == nil { + if err == nil && validateStruct(dst.SourceBigQuery) == nil { jsonSourceBigQuery, _ := json.Marshal(dst.SourceBigQuery) if string(jsonSourceBigQuery) == "{}" { // empty struct dst.SourceBigQuery = nil } else { - match++ + return nil } } else { dst.SourceBigQuery = nil @@ -61,12 +60,12 @@ func (dst *SourceUpdateInput) UnmarshalJSON(data []byte) error { // try to unmarshal data into SourceCSV err = newStrictDecoder(data).Decode(&dst.SourceCSV) - if err == nil { + if err == nil && validateStruct(dst.SourceCSV) == nil { jsonSourceCSV, _ := json.Marshal(dst.SourceCSV) if string(jsonSourceCSV) == "{}" { // empty struct dst.SourceCSV = nil } else { - match++ + return nil } } else { dst.SourceCSV = nil @@ -74,12 +73,12 @@ func (dst *SourceUpdateInput) UnmarshalJSON(data []byte) error { // try to unmarshal data into SourceJSON err = newStrictDecoder(data).Decode(&dst.SourceJSON) - if err == nil { + if err == nil && validateStruct(dst.SourceJSON) == nil { jsonSourceJSON, _ := json.Marshal(dst.SourceJSON) if string(jsonSourceJSON) == "{}" { // empty struct dst.SourceJSON = nil } else { - match++ + return nil } } else { dst.SourceJSON = nil @@ -87,30 +86,18 @@ func (dst *SourceUpdateInput) UnmarshalJSON(data []byte) error { // try to unmarshal data into SourceUpdateCommercetools err = newStrictDecoder(data).Decode(&dst.SourceUpdateCommercetools) - if err == nil { + if err == nil && validateStruct(dst.SourceUpdateCommercetools) == nil { jsonSourceUpdateCommercetools, _ := json.Marshal(dst.SourceUpdateCommercetools) if string(jsonSourceUpdateCommercetools) == "{}" { // empty struct dst.SourceUpdateCommercetools = nil } else { - match++ + return nil } } else { dst.SourceUpdateCommercetools = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.SourceBigQuery = nil - dst.SourceCSV = nil - dst.SourceJSON = nil - dst.SourceUpdateCommercetools = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(SourceUpdateInput)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(SourceUpdateInput)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(SourceUpdateInput)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_source_update_response.go b/clients/algoliasearch-client-go/algolia/ingestion/model_source_update_response.go index 6fcab31e41..5606e6af01 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_source_update_response.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_source_update_response.go @@ -9,10 +9,10 @@ import ( // SourceUpdateResponse struct for SourceUpdateResponse type SourceUpdateResponse struct { // The source UUID. - SourceID string `json:"sourceID"` - Name string `json:"name"` + SourceID string `json:"sourceID" validate:"required"` + Name string `json:"name" validate:"required"` // Date of last update (RFC3339 format). - UpdatedAt string `json:"updatedAt"` + UpdatedAt string `json:"updatedAt" validate:"required"` } // NewSourceUpdateResponse instantiates a new SourceUpdateResponse object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_subscription_trigger.go b/clients/algoliasearch-client-go/algolia/ingestion/model_subscription_trigger.go index 328cb1c2d1..05c29d9ec1 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_subscription_trigger.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_subscription_trigger.go @@ -8,7 +8,7 @@ import ( // SubscriptionTrigger The trigger input for a task of type 'subscription'. type SubscriptionTrigger struct { - Type SubscriptionTriggerType `json:"type"` + Type SubscriptionTriggerType `json:"type" validate:"required"` } // NewSubscriptionTrigger instantiates a new SubscriptionTrigger object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_task.go b/clients/algoliasearch-client-go/algolia/ingestion/model_task.go index 2c51719841..891a8d40aa 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_task.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_task.go @@ -9,19 +9,19 @@ import ( // Task struct for Task type Task struct { // The task UUID. - TaskID string `json:"taskID"` + TaskID string `json:"taskID" validate:"required"` // The source UUID. - SourceID string `json:"sourceID"` + SourceID string `json:"sourceID" validate:"required"` // The destination UUID. - DestinationID string `json:"destinationID"` - Trigger Trigger `json:"trigger"` + DestinationID string `json:"destinationID" validate:"required"` + Trigger Trigger `json:"trigger" validate:"required"` // The input that holds information specific to the task. Input map[string]interface{} `json:"input,omitempty"` // Whether the task is enabled or not. - Enabled bool `json:"enabled"` - Action ActionType `json:"action"` + Enabled bool `json:"enabled" validate:"required"` + Action ActionType `json:"action" validate:"required"` // Date of creation (RFC3339 format). - CreatedAt string `json:"createdAt"` + CreatedAt string `json:"createdAt" validate:"required"` // Date of last update (RFC3339 format). UpdatedAt *string `json:"updatedAt,omitempty"` } diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_task_create.go b/clients/algoliasearch-client-go/algolia/ingestion/model_task_create.go index a3781ae0b3..01ec9d37cf 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_task_create.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_task_create.go @@ -9,11 +9,11 @@ import ( // TaskCreate The payload for a task creation. type TaskCreate struct { // The source UUID. - SourceID string `json:"sourceID"` + SourceID string `json:"sourceID" validate:"required"` // The destination UUID. - DestinationID string `json:"destinationID"` - Trigger TaskCreateTrigger `json:"trigger"` - Action ActionType `json:"action"` + DestinationID string `json:"destinationID" validate:"required"` + Trigger TaskCreateTrigger `json:"trigger" validate:"required"` + Action ActionType `json:"action" validate:"required"` // Whether the task is enabled or not. Enabled *bool `json:"enabled,omitempty"` } diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_task_create_response.go b/clients/algoliasearch-client-go/algolia/ingestion/model_task_create_response.go index 83d1736a44..5b9c97ece9 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_task_create_response.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_task_create_response.go @@ -9,9 +9,9 @@ import ( // TaskCreateResponse The response from the API after a task creation. type TaskCreateResponse struct { // The task UUID. - TaskID string `json:"taskID"` + TaskID string `json:"taskID" validate:"required"` // Date of creation (RFC3339 format). - CreatedAt string `json:"createdAt"` + CreatedAt string `json:"createdAt" validate:"required"` } // NewTaskCreateResponse instantiates a new TaskCreateResponse object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_task_create_trigger.go b/clients/algoliasearch-client-go/algolia/ingestion/model_task_create_trigger.go index 9a825c48d2..27fbee8a94 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_task_create_trigger.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_task_create_trigger.go @@ -37,15 +37,14 @@ func SubscriptionTriggerAsTaskCreateTrigger(v *SubscriptionTrigger) TaskCreateTr // Unmarshal JSON data into one of the pointers in the struct func (dst *TaskCreateTrigger) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into OnDemandTriggerInput err = newStrictDecoder(data).Decode(&dst.OnDemandTriggerInput) - if err == nil { + if err == nil && validateStruct(dst.OnDemandTriggerInput) == nil { jsonOnDemandTriggerInput, _ := json.Marshal(dst.OnDemandTriggerInput) if string(jsonOnDemandTriggerInput) == "{}" { // empty struct dst.OnDemandTriggerInput = nil } else { - match++ + return nil } } else { dst.OnDemandTriggerInput = nil @@ -53,12 +52,12 @@ func (dst *TaskCreateTrigger) UnmarshalJSON(data []byte) error { // try to unmarshal data into ScheduleTriggerInput err = newStrictDecoder(data).Decode(&dst.ScheduleTriggerInput) - if err == nil { + if err == nil && validateStruct(dst.ScheduleTriggerInput) == nil { jsonScheduleTriggerInput, _ := json.Marshal(dst.ScheduleTriggerInput) if string(jsonScheduleTriggerInput) == "{}" { // empty struct dst.ScheduleTriggerInput = nil } else { - match++ + return nil } } else { dst.ScheduleTriggerInput = nil @@ -66,29 +65,18 @@ func (dst *TaskCreateTrigger) UnmarshalJSON(data []byte) error { // try to unmarshal data into SubscriptionTrigger err = newStrictDecoder(data).Decode(&dst.SubscriptionTrigger) - if err == nil { + if err == nil && validateStruct(dst.SubscriptionTrigger) == nil { jsonSubscriptionTrigger, _ := json.Marshal(dst.SubscriptionTrigger) if string(jsonSubscriptionTrigger) == "{}" { // empty struct dst.SubscriptionTrigger = nil } else { - match++ + return nil } } else { dst.SubscriptionTrigger = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.OnDemandTriggerInput = nil - dst.ScheduleTriggerInput = nil - dst.SubscriptionTrigger = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(TaskCreateTrigger)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(TaskCreateTrigger)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(TaskCreateTrigger)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_task_search.go b/clients/algoliasearch-client-go/algolia/ingestion/model_task_search.go index c50f34ea58..982a890089 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_task_search.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_task_search.go @@ -8,7 +8,7 @@ import ( // TaskSearch struct for TaskSearch type TaskSearch struct { - TaskIDs []string `json:"taskIDs"` + TaskIDs []string `json:"taskIDs" validate:"required"` } // NewTaskSearch instantiates a new TaskSearch object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_task_update_response.go b/clients/algoliasearch-client-go/algolia/ingestion/model_task_update_response.go index ca2d00d17b..7dcb00c600 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_task_update_response.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_task_update_response.go @@ -9,9 +9,9 @@ import ( // TaskUpdateResponse The response from the API after a task update. type TaskUpdateResponse struct { // The task UUID. - TaskID string `json:"taskID"` + TaskID string `json:"taskID" validate:"required"` // Date of last update (RFC3339 format). - UpdatedAt string `json:"updatedAt"` + UpdatedAt string `json:"updatedAt" validate:"required"` } // NewTaskUpdateResponse instantiates a new TaskUpdateResponse object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_trigger.go b/clients/algoliasearch-client-go/algolia/ingestion/model_trigger.go index 2f73c0b952..1c5a13ec95 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_trigger.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_trigger.go @@ -37,15 +37,14 @@ func SubscriptionTriggerAsTrigger(v *SubscriptionTrigger) Trigger { // Unmarshal JSON data into one of the pointers in the struct func (dst *Trigger) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into OnDemandTrigger err = newStrictDecoder(data).Decode(&dst.OnDemandTrigger) - if err == nil { + if err == nil && validateStruct(dst.OnDemandTrigger) == nil { jsonOnDemandTrigger, _ := json.Marshal(dst.OnDemandTrigger) if string(jsonOnDemandTrigger) == "{}" { // empty struct dst.OnDemandTrigger = nil } else { - match++ + return nil } } else { dst.OnDemandTrigger = nil @@ -53,12 +52,12 @@ func (dst *Trigger) UnmarshalJSON(data []byte) error { // try to unmarshal data into ScheduleTrigger err = newStrictDecoder(data).Decode(&dst.ScheduleTrigger) - if err == nil { + if err == nil && validateStruct(dst.ScheduleTrigger) == nil { jsonScheduleTrigger, _ := json.Marshal(dst.ScheduleTrigger) if string(jsonScheduleTrigger) == "{}" { // empty struct dst.ScheduleTrigger = nil } else { - match++ + return nil } } else { dst.ScheduleTrigger = nil @@ -66,29 +65,18 @@ func (dst *Trigger) UnmarshalJSON(data []byte) error { // try to unmarshal data into SubscriptionTrigger err = newStrictDecoder(data).Decode(&dst.SubscriptionTrigger) - if err == nil { + if err == nil && validateStruct(dst.SubscriptionTrigger) == nil { jsonSubscriptionTrigger, _ := json.Marshal(dst.SubscriptionTrigger) if string(jsonSubscriptionTrigger) == "{}" { // empty struct dst.SubscriptionTrigger = nil } else { - match++ + return nil } } else { dst.SubscriptionTrigger = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.OnDemandTrigger = nil - dst.ScheduleTrigger = nil - dst.SubscriptionTrigger = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(Trigger)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(Trigger)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(Trigger)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/ingestion/model_trigger_input.go b/clients/algoliasearch-client-go/algolia/ingestion/model_trigger_input.go index baa88eb79e..16fa086e36 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/model_trigger_input.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/model_trigger_input.go @@ -8,7 +8,7 @@ import ( // TriggerInput The trigger input of a task. type TriggerInput struct { - Type TriggerType `json:"type"` + Type TriggerType `json:"type" validate:"required"` } // NewTriggerInput instantiates a new TriggerInput object diff --git a/clients/algoliasearch-client-go/algolia/ingestion/utils.go b/clients/algoliasearch-client-go/algolia/ingestion/utils.go index 0ca4dd10d9..3ad42785e9 100644 --- a/clients/algoliasearch-client-go/algolia/ingestion/utils.go +++ b/clients/algoliasearch-client-go/algolia/ingestion/utils.go @@ -336,6 +336,8 @@ func isNilorEmpty(i any) bool { switch reflect.TypeOf(i).Kind() { case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.UnsafePointer, reflect.Interface, reflect.Slice: return reflect.ValueOf(i).IsNil() + case reflect.Bool: + return false default: return reflect.ValueOf(i).IsZero() } diff --git a/clients/algoliasearch-client-go/algolia/insights/api_insights.go b/clients/algoliasearch-client-go/algolia/insights/api_insights.go index 00eb4d7d07..abbed78658 100644 --- a/clients/algoliasearch-client-go/algolia/insights/api_insights.go +++ b/clients/algoliasearch-client-go/algolia/insights/api_insights.go @@ -4,6 +4,7 @@ package insights import ( "bytes" "context" + "encoding/json" "io" "net/http" "net/url" @@ -29,7 +30,7 @@ func QueryParamOption(name string, val any) Option { func HeaderParamOption(name string, val any) Option { return Option{ optionType: "header", - name: "itemsPerPage", + name: name, value: parameterToString(val), } } @@ -39,6 +40,34 @@ type ApiDelRequest struct { parameters map[string]interface{} } +func (r *ApiDelRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + + return nil +} + // Query parameters to be applied to the current query. func (r ApiDelRequest) WithParameters(parameters map[string]interface{}) ApiDelRequest { r.parameters = parameters @@ -66,14 +95,16 @@ func (c *APIClient) Del(r ApiDelRequest, opts ...Option) (map[string]interface{} queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -155,6 +186,34 @@ type ApiGetRequest struct { parameters map[string]interface{} } +func (r *ApiGetRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + + return nil +} + // Query parameters to be applied to the current query. func (r ApiGetRequest) WithParameters(parameters map[string]interface{}) ApiGetRequest { r.parameters = parameters @@ -182,14 +241,16 @@ func (c *APIClient) Get(r ApiGetRequest, opts ...Option) (map[string]interface{} queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -272,6 +333,43 @@ type ApiPostRequest struct { body map[string]interface{} } +func (r *ApiPostRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + if v, ok := req["body"]; ok { //body + err = json.Unmarshal(v, &r.body) + if err != nil { + err = json.Unmarshal(b, &r.body) + if err != nil { + return err + } + } + } + + return nil +} + // Query parameters to be applied to the current query. func (r ApiPostRequest) WithParameters(parameters map[string]interface{}) ApiPostRequest { r.parameters = parameters @@ -305,21 +403,27 @@ func (c *APIClient) Post(r ApiPostRequest, opts ...Option) (map[string]interface queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } } // body params - postBody = r.body + if isNilorEmpty(r.body) { + postBody = "{}" + } else { + postBody = r.body + } req, err := c.prepareRequest(context.Background(), requestPath, http.MethodPost, postBody, headers, queryParams) if err != nil { return returnValue, err @@ -395,8 +499,32 @@ type ApiPushEventsRequest struct { insightEvents *InsightEvents } -func (r ApiPushEventsRequest) WithInsightEvents(insightEvents InsightEvents) ApiPushEventsRequest { - r.insightEvents = &insightEvents +func (r *ApiPushEventsRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["insightEvents"]; ok { //insightEvents + err = json.Unmarshal(v, &r.insightEvents) + if err != nil { + err = json.Unmarshal(b, &r.insightEvents) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.insightEvents) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiPushEventsRequest) WithInsightEvents(insightEvents *InsightEvents) ApiPushEventsRequest { + r.insightEvents = insightEvents return r } @@ -424,7 +552,7 @@ func (c *APIClient) PushEvents(r ApiPushEventsRequest, opts ...Option) (*PushEve for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -509,6 +637,43 @@ type ApiPutRequest struct { body map[string]interface{} } +func (r *ApiPutRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + if v, ok := req["body"]; ok { //body + err = json.Unmarshal(v, &r.body) + if err != nil { + err = json.Unmarshal(b, &r.body) + if err != nil { + return err + } + } + } + + return nil +} + // Query parameters to be applied to the current query. func (r ApiPutRequest) WithParameters(parameters map[string]interface{}) ApiPutRequest { r.parameters = parameters @@ -542,21 +707,27 @@ func (c *APIClient) Put(r ApiPutRequest, opts ...Option) (map[string]interface{} queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } } // body params - postBody = r.body + if isNilorEmpty(r.body) { + postBody = "{}" + } else { + postBody = r.body + } req, err := c.prepareRequest(context.Background(), requestPath, http.MethodPut, postBody, headers, queryParams) if err != nil { return returnValue, err diff --git a/clients/algoliasearch-client-go/algolia/insights/client.go b/clients/algoliasearch-client-go/algolia/insights/client.go index 45a5b8fc3e..03a40df63d 100644 --- a/clients/algoliasearch-client-go/algolia/insights/client.go +++ b/clients/algoliasearch-client-go/algolia/insights/client.go @@ -20,6 +20,8 @@ import ( "strings" "time" + "github.com/go-playground/validator/v10" + "github.com/algolia/algoliasearch-client-go/v4/algolia/call" "github.com/algolia/algoliasearch-client-go/v4/algolia/compression" "github.com/algolia/algoliasearch-client-go/v4/algolia/internal/transport" @@ -132,7 +134,7 @@ func typeCheckParameter(obj any, expected string, name string) error { // parameterToString convert any parameters to string. func parameterToString(obj any) string { if reflect.TypeOf(obj).Kind() == reflect.Slice { - return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", "", -1), "[]") + return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", ",", -1), "[]") } else if t, ok := obj.(time.Time); ok { return t.Format(time.RFC3339) } @@ -231,11 +233,9 @@ func (c *APIClient) prepareRequest( // add header parameters, if any if len(headerParams) > 0 { - headers := http.Header{} for h, v := range headerParams { - headers[h] = []string{v} + req.Header.Add(h, v) } - req.Header = headers } // Add the user agent to the request. @@ -294,6 +294,17 @@ func newStrictDecoder(data []byte) *json.Decoder { return dec } +// A wrapper for validating a struct, returns nil if value is not a struct +func validateStruct(v any) error { + err := validator.New().Struct(v) + validationErrors, ok := err.(validator.ValidationErrors) + if ok && len(validationErrors) > 0 { + return validationErrors + } + + return nil +} + // Set request body from an any func setBody(body any, contentType string, c compression.Compression) (bodyBuf *bytes.Buffer, err error) { if body == nil { diff --git a/clients/algoliasearch-client-go/algolia/insights/model_insight_event.go b/clients/algoliasearch-client-go/algolia/insights/model_insight_event.go index 905702cb00..b61cc38e7c 100644 --- a/clients/algoliasearch-client-go/algolia/insights/model_insight_event.go +++ b/clients/algoliasearch-client-go/algolia/insights/model_insight_event.go @@ -8,13 +8,13 @@ import ( // InsightEvent Insights event. type InsightEvent struct { - EventType EventType `json:"eventType"` + EventType EventType `json:"eventType" validate:"required"` // A user-defined string used to categorize events. - EventName string `json:"eventName"` + EventName string `json:"eventName" validate:"required"` // Name of the targeted index. - Index string `json:"index"` + Index string `json:"index" validate:"required"` // A user identifier. Depending if the user is logged-in or not, several strategies can be used from a sessionId to a technical identifier. You should always send pseudonymous or anonymous userTokens. - UserToken string `json:"userToken"` + UserToken string `json:"userToken" validate:"required"` // Time of the event expressed in milliseconds since the Unix epoch. Timestamp *int64 `json:"timestamp,omitempty"` // Algolia queryID. This is required when an event is tied to a search. diff --git a/clients/algoliasearch-client-go/algolia/insights/model_insight_events.go b/clients/algoliasearch-client-go/algolia/insights/model_insight_events.go index d6d557d28b..13c39329d4 100644 --- a/clients/algoliasearch-client-go/algolia/insights/model_insight_events.go +++ b/clients/algoliasearch-client-go/algolia/insights/model_insight_events.go @@ -9,7 +9,7 @@ import ( // InsightEvents Object containing the events sent. type InsightEvents struct { // Array of events sent. - Events []InsightEvent `json:"events"` + Events []InsightEvent `json:"events" validate:"required"` } // NewInsightEvents instantiates a new InsightEvents object diff --git a/clients/algoliasearch-client-go/algolia/insights/model_push_events_response.go b/clients/algoliasearch-client-go/algolia/insights/model_push_events_response.go index 9508283bec..0911d703b4 100644 --- a/clients/algoliasearch-client-go/algolia/insights/model_push_events_response.go +++ b/clients/algoliasearch-client-go/algolia/insights/model_push_events_response.go @@ -9,7 +9,7 @@ import ( // PushEventsResponse struct for PushEventsResponse type PushEventsResponse struct { // A message confirming the event push. - Message string `json:"message"` + Message string `json:"message" validate:"required"` } // NewPushEventsResponse instantiates a new PushEventsResponse object diff --git a/clients/algoliasearch-client-go/algolia/insights/utils.go b/clients/algoliasearch-client-go/algolia/insights/utils.go index c84decd20b..e0ff4d3cce 100644 --- a/clients/algoliasearch-client-go/algolia/insights/utils.go +++ b/clients/algoliasearch-client-go/algolia/insights/utils.go @@ -336,6 +336,8 @@ func isNilorEmpty(i any) bool { switch reflect.TypeOf(i).Kind() { case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.UnsafePointer, reflect.Interface, reflect.Slice: return reflect.ValueOf(i).IsNil() + case reflect.Bool: + return false default: return reflect.ValueOf(i).IsZero() } diff --git a/clients/algoliasearch-client-go/algolia/personalization/api_personalization.go b/clients/algoliasearch-client-go/algolia/personalization/api_personalization.go index f964bd85be..5785432555 100644 --- a/clients/algoliasearch-client-go/algolia/personalization/api_personalization.go +++ b/clients/algoliasearch-client-go/algolia/personalization/api_personalization.go @@ -4,6 +4,7 @@ package personalization import ( "bytes" "context" + "encoding/json" "io" "net/http" "net/url" @@ -29,7 +30,7 @@ func QueryParamOption(name string, val any) Option { func HeaderParamOption(name string, val any) Option { return Option{ optionType: "header", - name: "itemsPerPage", + name: name, value: parameterToString(val), } } @@ -39,6 +40,34 @@ type ApiDelRequest struct { parameters map[string]interface{} } +func (r *ApiDelRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + + return nil +} + // Query parameters to be applied to the current query. func (r ApiDelRequest) WithParameters(parameters map[string]interface{}) ApiDelRequest { r.parameters = parameters @@ -66,14 +95,16 @@ func (c *APIClient) Del(r ApiDelRequest, opts ...Option) (map[string]interface{} queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -154,6 +185,25 @@ type ApiDeleteUserProfileRequest struct { userToken string } +func (r *ApiDeleteUserProfileRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["userToken"]; ok { //userToken + err = json.Unmarshal(v, &r.userToken) + if err != nil { + err = json.Unmarshal(b, &r.userToken) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiDeleteUserProfileRequest func (c *APIClient) NewApiDeleteUserProfileRequest(userToken string) ApiDeleteUserProfileRequest { return ApiDeleteUserProfileRequest{ @@ -178,7 +228,7 @@ func (c *APIClient) DeleteUserProfile(r ApiDeleteUserProfileRequest, opts ...Opt for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -260,6 +310,34 @@ type ApiGetRequest struct { parameters map[string]interface{} } +func (r *ApiGetRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + + return nil +} + // Query parameters to be applied to the current query. func (r ApiGetRequest) WithParameters(parameters map[string]interface{}) ApiGetRequest { r.parameters = parameters @@ -287,14 +365,16 @@ func (c *APIClient) Get(r ApiGetRequest, opts ...Option) (map[string]interface{} queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -374,6 +454,16 @@ func (c *APIClient) Get(r ApiGetRequest, opts ...Option) (map[string]interface{} type ApiGetPersonalizationStrategyRequest struct { } +func (r *ApiGetPersonalizationStrategyRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + + return nil +} + // @return ApiGetPersonalizationStrategyRequest func (c *APIClient) NewApiGetPersonalizationStrategyRequest() ApiGetPersonalizationStrategyRequest { return ApiGetPersonalizationStrategyRequest{} @@ -395,7 +485,7 @@ func (c *APIClient) GetPersonalizationStrategy(r ApiGetPersonalizationStrategyRe for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -476,6 +566,25 @@ type ApiGetUserTokenProfileRequest struct { userToken string } +func (r *ApiGetUserTokenProfileRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["userToken"]; ok { //userToken + err = json.Unmarshal(v, &r.userToken) + if err != nil { + err = json.Unmarshal(b, &r.userToken) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiGetUserTokenProfileRequest func (c *APIClient) NewApiGetUserTokenProfileRequest(userToken string) ApiGetUserTokenProfileRequest { return ApiGetUserTokenProfileRequest{ @@ -500,7 +609,7 @@ func (c *APIClient) GetUserTokenProfile(r ApiGetUserTokenProfileRequest, opts .. for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -583,6 +692,43 @@ type ApiPostRequest struct { body map[string]interface{} } +func (r *ApiPostRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + if v, ok := req["body"]; ok { //body + err = json.Unmarshal(v, &r.body) + if err != nil { + err = json.Unmarshal(b, &r.body) + if err != nil { + return err + } + } + } + + return nil +} + // Query parameters to be applied to the current query. func (r ApiPostRequest) WithParameters(parameters map[string]interface{}) ApiPostRequest { r.parameters = parameters @@ -616,21 +762,27 @@ func (c *APIClient) Post(r ApiPostRequest, opts ...Option) (map[string]interface queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } } // body params - postBody = r.body + if isNilorEmpty(r.body) { + postBody = "{}" + } else { + postBody = r.body + } req, err := c.prepareRequest(context.Background(), requestPath, http.MethodPost, postBody, headers, queryParams) if err != nil { return returnValue, err @@ -708,6 +860,43 @@ type ApiPutRequest struct { body map[string]interface{} } +func (r *ApiPutRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + if v, ok := req["body"]; ok { //body + err = json.Unmarshal(v, &r.body) + if err != nil { + err = json.Unmarshal(b, &r.body) + if err != nil { + return err + } + } + } + + return nil +} + // Query parameters to be applied to the current query. func (r ApiPutRequest) WithParameters(parameters map[string]interface{}) ApiPutRequest { r.parameters = parameters @@ -741,21 +930,27 @@ func (c *APIClient) Put(r ApiPutRequest, opts ...Option) (map[string]interface{} queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } } // body params - postBody = r.body + if isNilorEmpty(r.body) { + postBody = "{}" + } else { + postBody = r.body + } req, err := c.prepareRequest(context.Background(), requestPath, http.MethodPut, postBody, headers, queryParams) if err != nil { return returnValue, err @@ -831,8 +1026,32 @@ type ApiSetPersonalizationStrategyRequest struct { personalizationStrategyParams *PersonalizationStrategyParams } -func (r ApiSetPersonalizationStrategyRequest) WithPersonalizationStrategyParams(personalizationStrategyParams PersonalizationStrategyParams) ApiSetPersonalizationStrategyRequest { - r.personalizationStrategyParams = &personalizationStrategyParams +func (r *ApiSetPersonalizationStrategyRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["personalizationStrategyParams"]; ok { //personalizationStrategyParams + err = json.Unmarshal(v, &r.personalizationStrategyParams) + if err != nil { + err = json.Unmarshal(b, &r.personalizationStrategyParams) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.personalizationStrategyParams) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiSetPersonalizationStrategyRequest) WithPersonalizationStrategyParams(personalizationStrategyParams *PersonalizationStrategyParams) ApiSetPersonalizationStrategyRequest { + r.personalizationStrategyParams = personalizationStrategyParams return r } @@ -860,7 +1079,7 @@ func (c *APIClient) SetPersonalizationStrategy(r ApiSetPersonalizationStrategyRe for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } diff --git a/clients/algoliasearch-client-go/algolia/personalization/client.go b/clients/algoliasearch-client-go/algolia/personalization/client.go index a650780b7e..ba2808af93 100644 --- a/clients/algoliasearch-client-go/algolia/personalization/client.go +++ b/clients/algoliasearch-client-go/algolia/personalization/client.go @@ -20,6 +20,8 @@ import ( "strings" "time" + "github.com/go-playground/validator/v10" + "github.com/algolia/algoliasearch-client-go/v4/algolia/call" "github.com/algolia/algoliasearch-client-go/v4/algolia/compression" "github.com/algolia/algoliasearch-client-go/v4/algolia/internal/transport" @@ -130,7 +132,7 @@ func typeCheckParameter(obj any, expected string, name string) error { // parameterToString convert any parameters to string. func parameterToString(obj any) string { if reflect.TypeOf(obj).Kind() == reflect.Slice { - return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", "", -1), "[]") + return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", ",", -1), "[]") } else if t, ok := obj.(time.Time); ok { return t.Format(time.RFC3339) } @@ -229,11 +231,9 @@ func (c *APIClient) prepareRequest( // add header parameters, if any if len(headerParams) > 0 { - headers := http.Header{} for h, v := range headerParams { - headers[h] = []string{v} + req.Header.Add(h, v) } - req.Header = headers } // Add the user agent to the request. @@ -292,6 +292,17 @@ func newStrictDecoder(data []byte) *json.Decoder { return dec } +// A wrapper for validating a struct, returns nil if value is not a struct +func validateStruct(v any) error { + err := validator.New().Struct(v) + validationErrors, ok := err.(validator.ValidationErrors) + if ok && len(validationErrors) > 0 { + return validationErrors + } + + return nil +} + // Set request body from an any func setBody(body any, contentType string, c compression.Compression) (bodyBuf *bytes.Buffer, err error) { if body == nil { diff --git a/clients/algoliasearch-client-go/algolia/personalization/model_delete_user_profile_response.go b/clients/algoliasearch-client-go/algolia/personalization/model_delete_user_profile_response.go index 25381ce829..2d498c07f0 100644 --- a/clients/algoliasearch-client-go/algolia/personalization/model_delete_user_profile_response.go +++ b/clients/algoliasearch-client-go/algolia/personalization/model_delete_user_profile_response.go @@ -9,9 +9,9 @@ import ( // DeleteUserProfileResponse struct for DeleteUserProfileResponse type DeleteUserProfileResponse struct { // userToken representing the user for which to fetch the Personalization profile. - UserToken string `json:"userToken"` + UserToken string `json:"userToken" validate:"required"` // A date until which the data can safely be considered as deleted for the given user. Any data received after the `deletedUntil` date will start building a new user profile. - DeletedUntil string `json:"deletedUntil"` + DeletedUntil string `json:"deletedUntil" validate:"required"` } // NewDeleteUserProfileResponse instantiates a new DeleteUserProfileResponse object diff --git a/clients/algoliasearch-client-go/algolia/personalization/model_event_scoring.go b/clients/algoliasearch-client-go/algolia/personalization/model_event_scoring.go index 2d5d4668dd..52303621f7 100644 --- a/clients/algoliasearch-client-go/algolia/personalization/model_event_scoring.go +++ b/clients/algoliasearch-client-go/algolia/personalization/model_event_scoring.go @@ -9,11 +9,11 @@ import ( // EventScoring struct for EventScoring type EventScoring struct { // The score for the event. - Score int32 `json:"score"` + Score int32 `json:"score" validate:"required"` // The name of the event. - EventName string `json:"eventName"` + EventName string `json:"eventName" validate:"required"` // The type of the event. - EventType string `json:"eventType"` + EventType string `json:"eventType" validate:"required"` } // NewEventScoring instantiates a new EventScoring object diff --git a/clients/algoliasearch-client-go/algolia/personalization/model_facet_scoring.go b/clients/algoliasearch-client-go/algolia/personalization/model_facet_scoring.go index 44990978c9..22c312d321 100644 --- a/clients/algoliasearch-client-go/algolia/personalization/model_facet_scoring.go +++ b/clients/algoliasearch-client-go/algolia/personalization/model_facet_scoring.go @@ -9,9 +9,9 @@ import ( // FacetScoring struct for FacetScoring type FacetScoring struct { // The score for the event. - Score int32 `json:"score"` + Score int32 `json:"score" validate:"required"` // The name of the facet. - FacetName string `json:"facetName"` + FacetName string `json:"facetName" validate:"required"` } // NewFacetScoring instantiates a new FacetScoring object diff --git a/clients/algoliasearch-client-go/algolia/personalization/model_get_user_token_response.go b/clients/algoliasearch-client-go/algolia/personalization/model_get_user_token_response.go index 4bee91b40b..ae5351ed35 100644 --- a/clients/algoliasearch-client-go/algolia/personalization/model_get_user_token_response.go +++ b/clients/algoliasearch-client-go/algolia/personalization/model_get_user_token_response.go @@ -9,11 +9,11 @@ import ( // GetUserTokenResponse struct for GetUserTokenResponse type GetUserTokenResponse struct { // userToken representing the user for which to fetch the Personalization profile. - UserToken string `json:"userToken"` + UserToken string `json:"userToken" validate:"required"` // Date of last event update. (ISO-8601 format). - LastEventAt string `json:"lastEventAt"` + LastEventAt string `json:"lastEventAt" validate:"required"` // The userToken scores. - Scores map[string]interface{} `json:"scores"` + Scores map[string]interface{} `json:"scores" validate:"required"` } // NewGetUserTokenResponse instantiates a new GetUserTokenResponse object diff --git a/clients/algoliasearch-client-go/algolia/personalization/model_personalization_strategy_params.go b/clients/algoliasearch-client-go/algolia/personalization/model_personalization_strategy_params.go index e5dbdef043..2b377d2911 100644 --- a/clients/algoliasearch-client-go/algolia/personalization/model_personalization_strategy_params.go +++ b/clients/algoliasearch-client-go/algolia/personalization/model_personalization_strategy_params.go @@ -9,11 +9,11 @@ import ( // PersonalizationStrategyParams struct for PersonalizationStrategyParams type PersonalizationStrategyParams struct { // Scores associated with the events. - EventScoring []EventScoring `json:"eventScoring"` + EventScoring []EventScoring `json:"eventScoring" validate:"required"` // Scores associated with the facets. - FacetScoring []FacetScoring `json:"facetScoring"` + FacetScoring []FacetScoring `json:"facetScoring" validate:"required"` // The impact that personalization has on search results: a number between 0 (personalization disabled) and 100 (personalization fully enabled). - PersonalizationImpact int32 `json:"personalizationImpact"` + PersonalizationImpact int32 `json:"personalizationImpact" validate:"required"` } // NewPersonalizationStrategyParams instantiates a new PersonalizationStrategyParams object diff --git a/clients/algoliasearch-client-go/algolia/personalization/model_set_personalization_strategy_response.go b/clients/algoliasearch-client-go/algolia/personalization/model_set_personalization_strategy_response.go index 38d1319ddb..7cf7947b98 100644 --- a/clients/algoliasearch-client-go/algolia/personalization/model_set_personalization_strategy_response.go +++ b/clients/algoliasearch-client-go/algolia/personalization/model_set_personalization_strategy_response.go @@ -9,7 +9,7 @@ import ( // SetPersonalizationStrategyResponse struct for SetPersonalizationStrategyResponse type SetPersonalizationStrategyResponse struct { // A message confirming the strategy update. - Message string `json:"message"` + Message string `json:"message" validate:"required"` } // NewSetPersonalizationStrategyResponse instantiates a new SetPersonalizationStrategyResponse object diff --git a/clients/algoliasearch-client-go/algolia/personalization/utils.go b/clients/algoliasearch-client-go/algolia/personalization/utils.go index 677bf22abf..dbfeda6dd7 100644 --- a/clients/algoliasearch-client-go/algolia/personalization/utils.go +++ b/clients/algoliasearch-client-go/algolia/personalization/utils.go @@ -336,6 +336,8 @@ func isNilorEmpty(i any) bool { switch reflect.TypeOf(i).Kind() { case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.UnsafePointer, reflect.Interface, reflect.Slice: return reflect.ValueOf(i).IsNil() + case reflect.Bool: + return false default: return reflect.ValueOf(i).IsZero() } diff --git a/clients/algoliasearch-client-go/algolia/predict/api_predict.go b/clients/algoliasearch-client-go/algolia/predict/api_predict.go index 0a16da5143..0f27a981e6 100644 --- a/clients/algoliasearch-client-go/algolia/predict/api_predict.go +++ b/clients/algoliasearch-client-go/algolia/predict/api_predict.go @@ -4,6 +4,7 @@ package predict import ( "bytes" "context" + "encoding/json" "io" "net/http" "net/url" @@ -29,7 +30,7 @@ func QueryParamOption(name string, val any) Option { func HeaderParamOption(name string, val any) Option { return Option{ optionType: "header", - name: "itemsPerPage", + name: name, value: parameterToString(val), } } @@ -38,8 +39,32 @@ type ApiActivateModelInstanceRequest struct { activateModelParams *ActivateModelParams } -func (r ApiActivateModelInstanceRequest) WithActivateModelParams(activateModelParams ActivateModelParams) ApiActivateModelInstanceRequest { - r.activateModelParams = &activateModelParams +func (r *ApiActivateModelInstanceRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["activateModelParams"]; ok { //activateModelParams + err = json.Unmarshal(v, &r.activateModelParams) + if err != nil { + err = json.Unmarshal(b, &r.activateModelParams) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.activateModelParams) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiActivateModelInstanceRequest) WithActivateModelParams(activateModelParams *ActivateModelParams) ApiActivateModelInstanceRequest { + r.activateModelParams = activateModelParams return r } @@ -67,7 +92,7 @@ func (c *APIClient) ActivateModelInstance(r ApiActivateModelInstanceRequest, opt for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -141,8 +166,32 @@ type ApiCreateSegmentRequest struct { createSegmentParams *CreateSegmentParams } -func (r ApiCreateSegmentRequest) WithCreateSegmentParams(createSegmentParams CreateSegmentParams) ApiCreateSegmentRequest { - r.createSegmentParams = &createSegmentParams +func (r *ApiCreateSegmentRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["createSegmentParams"]; ok { //createSegmentParams + err = json.Unmarshal(v, &r.createSegmentParams) + if err != nil { + err = json.Unmarshal(b, &r.createSegmentParams) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.createSegmentParams) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiCreateSegmentRequest) WithCreateSegmentParams(createSegmentParams *CreateSegmentParams) ApiCreateSegmentRequest { + r.createSegmentParams = createSegmentParams return r } @@ -170,7 +219,7 @@ func (c *APIClient) CreateSegment(r ApiCreateSegmentRequest, opts ...Option) (*C for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -254,6 +303,34 @@ type ApiDelRequest struct { parameters map[string]interface{} } +func (r *ApiDelRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + + return nil +} + // Query parameters to be applied to the current query. func (r ApiDelRequest) WithParameters(parameters map[string]interface{}) ApiDelRequest { r.parameters = parameters @@ -281,14 +358,16 @@ func (c *APIClient) Del(r ApiDelRequest, opts ...Option) (map[string]interface{} queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -369,6 +448,25 @@ type ApiDeleteModelInstanceRequest struct { modelID string } +func (r *ApiDeleteModelInstanceRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["modelID"]; ok { //modelID + err = json.Unmarshal(v, &r.modelID) + if err != nil { + err = json.Unmarshal(b, &r.modelID) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiDeleteModelInstanceRequest func (c *APIClient) NewApiDeleteModelInstanceRequest(modelID string) ApiDeleteModelInstanceRequest { return ApiDeleteModelInstanceRequest{ @@ -393,7 +491,7 @@ func (c *APIClient) DeleteModelInstance(r ApiDeleteModelInstanceRequest, opts .. for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -474,6 +572,25 @@ type ApiDeleteSegmentRequest struct { segmentID string } +func (r *ApiDeleteSegmentRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["segmentID"]; ok { //segmentID + err = json.Unmarshal(v, &r.segmentID) + if err != nil { + err = json.Unmarshal(b, &r.segmentID) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiDeleteSegmentRequest func (c *APIClient) NewApiDeleteSegmentRequest(segmentID string) ApiDeleteSegmentRequest { return ApiDeleteSegmentRequest{ @@ -498,7 +615,7 @@ func (c *APIClient) DeleteSegment(r ApiDeleteSegmentRequest, opts ...Option) (*D for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -579,6 +696,25 @@ type ApiDeleteUserProfileRequest struct { userID string } +func (r *ApiDeleteUserProfileRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["userID"]; ok { //userID + err = json.Unmarshal(v, &r.userID) + if err != nil { + err = json.Unmarshal(b, &r.userID) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiDeleteUserProfileRequest func (c *APIClient) NewApiDeleteUserProfileRequest(userID string) ApiDeleteUserProfileRequest { return ApiDeleteUserProfileRequest{ @@ -603,7 +739,7 @@ func (c *APIClient) DeleteUserProfile(r ApiDeleteUserProfileRequest, opts ...Opt for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -684,9 +820,28 @@ type ApiFetchAllSegmentsRequest struct { type_ *SegmentType } +func (r *ApiFetchAllSegmentsRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["type"]; ok { //type_ + err = json.Unmarshal(v, &r.type_) + if err != nil { + err = json.Unmarshal(b, &r.type_) + if err != nil { + return err + } + } + } + + return nil +} + // The type of segments to fetch. -func (r ApiFetchAllSegmentsRequest) WithType_(type_ SegmentType) ApiFetchAllSegmentsRequest { - r.type_ = &type_ +func (r ApiFetchAllSegmentsRequest) WithType_(type_ *SegmentType) ApiFetchAllSegmentsRequest { + r.type_ = type_ return r } @@ -708,14 +863,14 @@ func (c *APIClient) FetchAllSegments(r ApiFetchAllSegmentsRequest, opts ...Optio queryParams := url.Values{} if !isNilorEmpty(r.type_) { - queryParams.Add("type", parameterToString(*r.type_)) + queryParams.Set("type", parameterToString(*r.type_)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -787,8 +942,32 @@ type ApiFetchAllUserProfilesRequest struct { fetchAllUserProfilesParams *FetchAllUserProfilesParams } -func (r ApiFetchAllUserProfilesRequest) WithFetchAllUserProfilesParams(fetchAllUserProfilesParams FetchAllUserProfilesParams) ApiFetchAllUserProfilesRequest { - r.fetchAllUserProfilesParams = &fetchAllUserProfilesParams +func (r *ApiFetchAllUserProfilesRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["fetchAllUserProfilesParams"]; ok { //fetchAllUserProfilesParams + err = json.Unmarshal(v, &r.fetchAllUserProfilesParams) + if err != nil { + err = json.Unmarshal(b, &r.fetchAllUserProfilesParams) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.fetchAllUserProfilesParams) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiFetchAllUserProfilesRequest) WithFetchAllUserProfilesParams(fetchAllUserProfilesParams *FetchAllUserProfilesParams) ApiFetchAllUserProfilesRequest { + r.fetchAllUserProfilesParams = fetchAllUserProfilesParams return r } @@ -816,7 +995,7 @@ func (c *APIClient) FetchAllUserProfiles(r ApiFetchAllUserProfilesRequest, opts for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -899,6 +1078,25 @@ type ApiFetchSegmentRequest struct { segmentID string } +func (r *ApiFetchSegmentRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["segmentID"]; ok { //segmentID + err = json.Unmarshal(v, &r.segmentID) + if err != nil { + err = json.Unmarshal(b, &r.segmentID) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiFetchSegmentRequest func (c *APIClient) NewApiFetchSegmentRequest(segmentID string) ApiFetchSegmentRequest { return ApiFetchSegmentRequest{ @@ -923,7 +1121,7 @@ func (c *APIClient) FetchSegment(r ApiFetchSegmentRequest, opts ...Option) (*Seg for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -996,8 +1194,41 @@ type ApiFetchUserProfileRequest struct { params *Params } -func (r ApiFetchUserProfileRequest) WithParams(params Params) ApiFetchUserProfileRequest { - r.params = ¶ms +func (r *ApiFetchUserProfileRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["userID"]; ok { //userID + err = json.Unmarshal(v, &r.userID) + if err != nil { + err = json.Unmarshal(b, &r.userID) + if err != nil { + return err + } + } + } + if v, ok := req["params"]; ok { //params + err = json.Unmarshal(v, &r.params) + if err != nil { + err = json.Unmarshal(b, &r.params) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.params) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiFetchUserProfileRequest) WithParams(params *Params) ApiFetchUserProfileRequest { + r.params = params return r } @@ -1028,7 +1259,7 @@ func (c *APIClient) FetchUserProfile(r ApiFetchUserProfileRequest, opts ...Optio for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1103,6 +1334,34 @@ type ApiGetRequest struct { parameters map[string]interface{} } +func (r *ApiGetRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + + return nil +} + // Query parameters to be applied to the current query. func (r ApiGetRequest) WithParameters(parameters map[string]interface{}) ApiGetRequest { r.parameters = parameters @@ -1130,14 +1389,16 @@ func (c *APIClient) Get(r ApiGetRequest, opts ...Option) (map[string]interface{} queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1217,6 +1478,16 @@ func (c *APIClient) Get(r ApiGetRequest, opts ...Option) (map[string]interface{} type ApiGetAvailableModelTypesRequest struct { } +func (r *ApiGetAvailableModelTypesRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + + return nil +} + // @return ApiGetAvailableModelTypesRequest func (c *APIClient) NewApiGetAvailableModelTypesRequest() ApiGetAvailableModelTypesRequest { return ApiGetAvailableModelTypesRequest{} @@ -1238,7 +1509,7 @@ func (c *APIClient) GetAvailableModelTypes(r ApiGetAvailableModelTypesRequest, o for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1310,6 +1581,25 @@ type ApiGetModelInstanceConfigRequest struct { modelID string } +func (r *ApiGetModelInstanceConfigRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["modelID"]; ok { //modelID + err = json.Unmarshal(v, &r.modelID) + if err != nil { + err = json.Unmarshal(b, &r.modelID) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiGetModelInstanceConfigRequest func (c *APIClient) NewApiGetModelInstanceConfigRequest(modelID string) ApiGetModelInstanceConfigRequest { return ApiGetModelInstanceConfigRequest{ @@ -1334,7 +1624,7 @@ func (c *APIClient) GetModelInstanceConfig(r ApiGetModelInstanceConfigRequest, o for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1414,6 +1704,16 @@ func (c *APIClient) GetModelInstanceConfig(r ApiGetModelInstanceConfigRequest, o type ApiGetModelInstancesRequest struct { } +func (r *ApiGetModelInstancesRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + + return nil +} + // @return ApiGetModelInstancesRequest func (c *APIClient) NewApiGetModelInstancesRequest() ApiGetModelInstancesRequest { return ApiGetModelInstancesRequest{} @@ -1435,7 +1735,7 @@ func (c *APIClient) GetModelInstances(r ApiGetModelInstancesRequest, opts ...Opt for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1507,6 +1807,25 @@ type ApiGetModelMetricsRequest struct { modelID string } +func (r *ApiGetModelMetricsRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["modelID"]; ok { //modelID + err = json.Unmarshal(v, &r.modelID) + if err != nil { + err = json.Unmarshal(b, &r.modelID) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiGetModelMetricsRequest func (c *APIClient) NewApiGetModelMetricsRequest(modelID string) ApiGetModelMetricsRequest { return ApiGetModelMetricsRequest{ @@ -1531,7 +1850,7 @@ func (c *APIClient) GetModelMetrics(r ApiGetModelMetricsRequest, opts ...Option) for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1613,8 +1932,41 @@ type ApiGetSegmentUsersRequest struct { fetchAllUserProfilesParams *FetchAllUserProfilesParams } -func (r ApiGetSegmentUsersRequest) WithFetchAllUserProfilesParams(fetchAllUserProfilesParams FetchAllUserProfilesParams) ApiGetSegmentUsersRequest { - r.fetchAllUserProfilesParams = &fetchAllUserProfilesParams +func (r *ApiGetSegmentUsersRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["segmentID"]; ok { //segmentID + err = json.Unmarshal(v, &r.segmentID) + if err != nil { + err = json.Unmarshal(b, &r.segmentID) + if err != nil { + return err + } + } + } + if v, ok := req["fetchAllUserProfilesParams"]; ok { //fetchAllUserProfilesParams + err = json.Unmarshal(v, &r.fetchAllUserProfilesParams) + if err != nil { + err = json.Unmarshal(b, &r.fetchAllUserProfilesParams) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.fetchAllUserProfilesParams) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiGetSegmentUsersRequest) WithFetchAllUserProfilesParams(fetchAllUserProfilesParams *FetchAllUserProfilesParams) ApiGetSegmentUsersRequest { + r.fetchAllUserProfilesParams = fetchAllUserProfilesParams return r } @@ -1645,7 +1997,7 @@ func (c *APIClient) GetSegmentUsers(r ApiGetSegmentUsersRequest, opts ...Option) for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1739,6 +2091,43 @@ type ApiPostRequest struct { body map[string]interface{} } +func (r *ApiPostRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + if v, ok := req["body"]; ok { //body + err = json.Unmarshal(v, &r.body) + if err != nil { + err = json.Unmarshal(b, &r.body) + if err != nil { + return err + } + } + } + + return nil +} + // Query parameters to be applied to the current query. func (r ApiPostRequest) WithParameters(parameters map[string]interface{}) ApiPostRequest { r.parameters = parameters @@ -1772,21 +2161,27 @@ func (c *APIClient) Post(r ApiPostRequest, opts ...Option) (map[string]interface queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } } // body params - postBody = r.body + if isNilorEmpty(r.body) { + postBody = "{}" + } else { + postBody = r.body + } req, err := c.prepareRequest(context.Background(), requestPath, http.MethodPost, postBody, headers, queryParams) if err != nil { return returnValue, err @@ -1864,6 +2259,43 @@ type ApiPutRequest struct { body map[string]interface{} } +func (r *ApiPutRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + if v, ok := req["body"]; ok { //body + err = json.Unmarshal(v, &r.body) + if err != nil { + err = json.Unmarshal(b, &r.body) + if err != nil { + return err + } + } + } + + return nil +} + // Query parameters to be applied to the current query. func (r ApiPutRequest) WithParameters(parameters map[string]interface{}) ApiPutRequest { r.parameters = parameters @@ -1897,21 +2329,27 @@ func (c *APIClient) Put(r ApiPutRequest, opts ...Option) (map[string]interface{} queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } } // body params - postBody = r.body + if isNilorEmpty(r.body) { + postBody = "{}" + } else { + postBody = r.body + } req, err := c.prepareRequest(context.Background(), requestPath, http.MethodPut, postBody, headers, queryParams) if err != nil { return returnValue, err @@ -1988,8 +2426,41 @@ type ApiUpdateModelInstanceRequest struct { updateModelParams *UpdateModelParams } -func (r ApiUpdateModelInstanceRequest) WithUpdateModelParams(updateModelParams UpdateModelParams) ApiUpdateModelInstanceRequest { - r.updateModelParams = &updateModelParams +func (r *ApiUpdateModelInstanceRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["modelID"]; ok { //modelID + err = json.Unmarshal(v, &r.modelID) + if err != nil { + err = json.Unmarshal(b, &r.modelID) + if err != nil { + return err + } + } + } + if v, ok := req["updateModelParams"]; ok { //updateModelParams + err = json.Unmarshal(v, &r.updateModelParams) + if err != nil { + err = json.Unmarshal(b, &r.updateModelParams) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.updateModelParams) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiUpdateModelInstanceRequest) WithUpdateModelParams(updateModelParams *UpdateModelParams) ApiUpdateModelInstanceRequest { + r.updateModelParams = updateModelParams return r } @@ -2020,7 +2491,7 @@ func (c *APIClient) UpdateModelInstance(r ApiUpdateModelInstanceRequest, opts .. for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -2104,8 +2575,41 @@ type ApiUpdateSegmentRequest struct { updateSegmentParams *UpdateSegmentParams } -func (r ApiUpdateSegmentRequest) WithUpdateSegmentParams(updateSegmentParams UpdateSegmentParams) ApiUpdateSegmentRequest { - r.updateSegmentParams = &updateSegmentParams +func (r *ApiUpdateSegmentRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["segmentID"]; ok { //segmentID + err = json.Unmarshal(v, &r.segmentID) + if err != nil { + err = json.Unmarshal(b, &r.segmentID) + if err != nil { + return err + } + } + } + if v, ok := req["updateSegmentParams"]; ok { //updateSegmentParams + err = json.Unmarshal(v, &r.updateSegmentParams) + if err != nil { + err = json.Unmarshal(b, &r.updateSegmentParams) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.updateSegmentParams) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiUpdateSegmentRequest) WithUpdateSegmentParams(updateSegmentParams *UpdateSegmentParams) ApiUpdateSegmentRequest { + r.updateSegmentParams = updateSegmentParams return r } @@ -2136,7 +2640,7 @@ func (c *APIClient) UpdateSegment(r ApiUpdateSegmentRequest, opts ...Option) (*U for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } diff --git a/clients/algoliasearch-client-go/algolia/predict/client.go b/clients/algoliasearch-client-go/algolia/predict/client.go index 7fabccddd2..fbdfbc8e0f 100644 --- a/clients/algoliasearch-client-go/algolia/predict/client.go +++ b/clients/algoliasearch-client-go/algolia/predict/client.go @@ -20,6 +20,8 @@ import ( "strings" "time" + "github.com/go-playground/validator/v10" + "github.com/algolia/algoliasearch-client-go/v4/algolia/call" "github.com/algolia/algoliasearch-client-go/v4/algolia/compression" "github.com/algolia/algoliasearch-client-go/v4/algolia/internal/transport" @@ -130,7 +132,7 @@ func typeCheckParameter(obj any, expected string, name string) error { // parameterToString convert any parameters to string. func parameterToString(obj any) string { if reflect.TypeOf(obj).Kind() == reflect.Slice { - return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", "", -1), "[]") + return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", ",", -1), "[]") } else if t, ok := obj.(time.Time); ok { return t.Format(time.RFC3339) } @@ -229,11 +231,9 @@ func (c *APIClient) prepareRequest( // add header parameters, if any if len(headerParams) > 0 { - headers := http.Header{} for h, v := range headerParams { - headers[h] = []string{v} + req.Header.Add(h, v) } - req.Header = headers } // Add the user agent to the request. @@ -292,6 +292,17 @@ func newStrictDecoder(data []byte) *json.Decoder { return dec } +// A wrapper for validating a struct, returns nil if value is not a struct +func validateStruct(v any) error { + err := validator.New().Struct(v) + validationErrors, ok := err.(validator.ValidationErrors) + if ok && len(validationErrors) > 0 { + return validationErrors + } + + return nil +} + // Set request body from an any func setBody(body any, contentType string, c compression.Compression) (bodyBuf *bytes.Buffer, err error) { if body == nil { diff --git a/clients/algoliasearch-client-go/algolia/predict/model_activate_model_instance_response.go b/clients/algoliasearch-client-go/algolia/predict/model_activate_model_instance_response.go index 0934dc21c0..8088c91b6a 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_activate_model_instance_response.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_activate_model_instance_response.go @@ -9,9 +9,9 @@ import ( // ActivateModelInstanceResponse struct for ActivateModelInstanceResponse type ActivateModelInstanceResponse struct { // The ID of the model. - ModelID string `json:"modelID"` + ModelID string `json:"modelID" validate:"required"` // Date of last update (ISO-8601 format). - UpdatedAt string `json:"updatedAt"` + UpdatedAt string `json:"updatedAt" validate:"required"` } // NewActivateModelInstanceResponse instantiates a new ActivateModelInstanceResponse object diff --git a/clients/algoliasearch-client-go/algolia/predict/model_activate_model_params.go b/clients/algoliasearch-client-go/algolia/predict/model_activate_model_params.go index 5f20496da8..6d96a12067 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_activate_model_params.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_activate_model_params.go @@ -8,13 +8,13 @@ import ( // ActivateModelParams struct for ActivateModelParams type ActivateModelParams struct { - Type ModelsToRetrieve `json:"type"` + Type ModelsToRetrieve `json:"type" validate:"required"` // The model’s instance name. - Name string `json:"name"` + Name string `json:"name" validate:"required"` // The data source ID, as returned by the (external) sources API. - SourceID string `json:"sourceID"` + SourceID string `json:"sourceID" validate:"required"` // The index name. - Index string `json:"index"` + Index string `json:"index" validate:"required"` ModelAttributes []string `json:"modelAttributes,omitempty"` } diff --git a/clients/algoliasearch-client-go/algolia/predict/model_affinity.go b/clients/algoliasearch-client-go/algolia/predict/model_affinity.go index ece8c1dfb3..f815e8f09b 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_affinity.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_affinity.go @@ -8,9 +8,9 @@ import ( // Affinity struct for Affinity type Affinity struct { - Name string `json:"name"` - Value PredictionAffinityValue `json:"value"` - Probability float64 `json:"probability"` + Name string `json:"name" validate:"required"` + Value PredictionAffinityValue `json:"value" validate:"required"` + Probability float64 `json:"probability" validate:"required"` } // NewAffinity instantiates a new Affinity object diff --git a/clients/algoliasearch-client-go/algolia/predict/model_create_segment_params.go b/clients/algoliasearch-client-go/algolia/predict/model_create_segment_params.go index 18782780c6..65fb664348 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_create_segment_params.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_create_segment_params.go @@ -9,8 +9,8 @@ import ( // CreateSegmentParams struct for CreateSegmentParams type CreateSegmentParams struct { // The name or description of the segment. - Name string `json:"name"` - Conditions SegmentParentConditions `json:"conditions"` + Name string `json:"name" validate:"required"` + Conditions SegmentParentConditions `json:"conditions" validate:"required"` } // NewCreateSegmentParams instantiates a new CreateSegmentParams object diff --git a/clients/algoliasearch-client-go/algolia/predict/model_create_segment_response.go b/clients/algoliasearch-client-go/algolia/predict/model_create_segment_response.go index 322e4bf2f0..dd4205ca13 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_create_segment_response.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_create_segment_response.go @@ -9,11 +9,11 @@ import ( // CreateSegmentResponse struct for CreateSegmentResponse type CreateSegmentResponse struct { // The ID of the segment. - SegmentID string `json:"segmentID"` + SegmentID string `json:"segmentID" validate:"required"` // The approximate number of users that matched the segment conditions when it was created, last updated, or when model inference last ran. Size *float32 `json:"size,omitempty"` // The date and time at which the segment was updated (RFC3339). - UpdatedAt string `json:"updatedAt"` + UpdatedAt string `json:"updatedAt" validate:"required"` } type CreateSegmentResponseOption func(f *CreateSegmentResponse) diff --git a/clients/algoliasearch-client-go/algolia/predict/model_delete_model_instance_response.go b/clients/algoliasearch-client-go/algolia/predict/model_delete_model_instance_response.go index ab6215c13e..dfe7435a6a 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_delete_model_instance_response.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_delete_model_instance_response.go @@ -9,9 +9,9 @@ import ( // DeleteModelInstanceResponse struct for DeleteModelInstanceResponse type DeleteModelInstanceResponse struct { // The ID of the model. - ModelID string `json:"modelID"` + ModelID string `json:"modelID" validate:"required"` // The date until which you can safely consider the data as being deleted. - DeletedUntil string `json:"deletedUntil"` + DeletedUntil string `json:"deletedUntil" validate:"required"` } // NewDeleteModelInstanceResponse instantiates a new DeleteModelInstanceResponse object diff --git a/clients/algoliasearch-client-go/algolia/predict/model_delete_segment_response.go b/clients/algoliasearch-client-go/algolia/predict/model_delete_segment_response.go index e80dc5e1ee..5d5a4a483c 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_delete_segment_response.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_delete_segment_response.go @@ -9,9 +9,9 @@ import ( // DeleteSegmentResponse struct for DeleteSegmentResponse type DeleteSegmentResponse struct { // The ID of the segment. - SegmentID string `json:"segmentID"` + SegmentID string `json:"segmentID" validate:"required"` // The date and time at which the segment will be re-ingested. - DeletedUntil string `json:"deletedUntil"` + DeletedUntil string `json:"deletedUntil" validate:"required"` } // NewDeleteSegmentResponse instantiates a new DeleteSegmentResponse object diff --git a/clients/algoliasearch-client-go/algolia/predict/model_delete_user_profile_response.go b/clients/algoliasearch-client-go/algolia/predict/model_delete_user_profile_response.go index bf4c1bb991..04404f6db8 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_delete_user_profile_response.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_delete_user_profile_response.go @@ -9,9 +9,9 @@ import ( // DeleteUserProfileResponse struct for DeleteUserProfileResponse type DeleteUserProfileResponse struct { // The ID of the user that was deleted. - User string `json:"user"` + User string `json:"user" validate:"required"` // The time the same user ID will be imported again when the data is ingested. - DeletedUntil string `json:"deletedUntil"` + DeletedUntil string `json:"deletedUntil" validate:"required"` } // NewDeleteUserProfileResponse instantiates a new DeleteUserProfileResponse object diff --git a/clients/algoliasearch-client-go/algolia/predict/model_error.go b/clients/algoliasearch-client-go/algolia/predict/model_error.go index 43c5cad294..f3db57e87b 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_error.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_error.go @@ -8,7 +8,7 @@ import ( // ModelError The error when the model is not available. type ModelError struct { - Error string `json:"error"` + Error string `json:"error" validate:"required"` } // NewModelError instantiates a new ModelError object diff --git a/clients/algoliasearch-client-go/algolia/predict/model_fetch_all_user_profiles_params.go b/clients/algoliasearch-client-go/algolia/predict/model_fetch_all_user_profiles_params.go index 412ba36490..2c127a0e02 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_fetch_all_user_profiles_params.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_fetch_all_user_profiles_params.go @@ -53,15 +53,14 @@ func TypesToRetrieveParamAsFetchAllUserProfilesParams(v *TypesToRetrieveParam) F // Unmarshal JSON data into one of the pointers in the struct func (dst *FetchAllUserProfilesParams) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into LimitParam err = newStrictDecoder(data).Decode(&dst.LimitParam) - if err == nil { + if err == nil && validateStruct(dst.LimitParam) == nil { jsonLimitParam, _ := json.Marshal(dst.LimitParam) if string(jsonLimitParam) == "{}" { // empty struct dst.LimitParam = nil } else { - match++ + return nil } } else { dst.LimitParam = nil @@ -69,12 +68,12 @@ func (dst *FetchAllUserProfilesParams) UnmarshalJSON(data []byte) error { // try to unmarshal data into ModelsToRetrieveParam err = newStrictDecoder(data).Decode(&dst.ModelsToRetrieveParam) - if err == nil { + if err == nil && validateStruct(dst.ModelsToRetrieveParam) == nil { jsonModelsToRetrieveParam, _ := json.Marshal(dst.ModelsToRetrieveParam) if string(jsonModelsToRetrieveParam) == "{}" { // empty struct dst.ModelsToRetrieveParam = nil } else { - match++ + return nil } } else { dst.ModelsToRetrieveParam = nil @@ -82,12 +81,12 @@ func (dst *FetchAllUserProfilesParams) UnmarshalJSON(data []byte) error { // try to unmarshal data into NextPageTokenParam err = newStrictDecoder(data).Decode(&dst.NextPageTokenParam) - if err == nil { + if err == nil && validateStruct(dst.NextPageTokenParam) == nil { jsonNextPageTokenParam, _ := json.Marshal(dst.NextPageTokenParam) if string(jsonNextPageTokenParam) == "{}" { // empty struct dst.NextPageTokenParam = nil } else { - match++ + return nil } } else { dst.NextPageTokenParam = nil @@ -95,12 +94,12 @@ func (dst *FetchAllUserProfilesParams) UnmarshalJSON(data []byte) error { // try to unmarshal data into PreviousPageTokenParam err = newStrictDecoder(data).Decode(&dst.PreviousPageTokenParam) - if err == nil { + if err == nil && validateStruct(dst.PreviousPageTokenParam) == nil { jsonPreviousPageTokenParam, _ := json.Marshal(dst.PreviousPageTokenParam) if string(jsonPreviousPageTokenParam) == "{}" { // empty struct dst.PreviousPageTokenParam = nil } else { - match++ + return nil } } else { dst.PreviousPageTokenParam = nil @@ -108,31 +107,18 @@ func (dst *FetchAllUserProfilesParams) UnmarshalJSON(data []byte) error { // try to unmarshal data into TypesToRetrieveParam err = newStrictDecoder(data).Decode(&dst.TypesToRetrieveParam) - if err == nil { + if err == nil && validateStruct(dst.TypesToRetrieveParam) == nil { jsonTypesToRetrieveParam, _ := json.Marshal(dst.TypesToRetrieveParam) if string(jsonTypesToRetrieveParam) == "{}" { // empty struct dst.TypesToRetrieveParam = nil } else { - match++ + return nil } } else { dst.TypesToRetrieveParam = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.LimitParam = nil - dst.ModelsToRetrieveParam = nil - dst.NextPageTokenParam = nil - dst.PreviousPageTokenParam = nil - dst.TypesToRetrieveParam = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(FetchAllUserProfilesParams)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(FetchAllUserProfilesParams)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(FetchAllUserProfilesParams)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/predict/model_fetch_all_user_profiles_response.go b/clients/algoliasearch-client-go/algolia/predict/model_fetch_all_user_profiles_response.go index 7c2c686355..3c230a52cf 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_fetch_all_user_profiles_response.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_fetch_all_user_profiles_response.go @@ -8,7 +8,7 @@ import ( // FetchAllUserProfilesResponse struct for FetchAllUserProfilesResponse type FetchAllUserProfilesResponse struct { - Users []UserProfile `json:"users"` + Users []UserProfile `json:"users" validate:"required"` // The token is used to navigate backward in the user list. To navigate from the current user list to the previous page, the API generates the previous page token and it sends the token in the response, beside the current user list. NOTE: This body param cannot be used with `nextPageToken` at the same time. PreviousPageToken *string `json:"previousPageToken,omitempty"` // The token is used to navigate forward in the user list. To navigate from the current user list to the next page, the API generates the next page token and it sends the token in the response, beside the current user list. NOTE: This body param cannot be used with `previousPageToken` at the same time. diff --git a/clients/algoliasearch-client-go/algolia/predict/model_funnel_stage.go b/clients/algoliasearch-client-go/algolia/predict/model_funnel_stage.go index 181b8316bc..d10e1447fa 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_funnel_stage.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_funnel_stage.go @@ -8,8 +8,8 @@ import ( // FunnelStage struct for FunnelStage type FunnelStage struct { - Name string `json:"name"` - Probability float64 `json:"probability"` + Name string `json:"name" validate:"required"` + Probability float64 `json:"probability" validate:"required"` } // NewFunnelStage instantiates a new FunnelStage object diff --git a/clients/algoliasearch-client-go/algolia/predict/model_get_available_model_types_response_inner.go b/clients/algoliasearch-client-go/algolia/predict/model_get_available_model_types_response_inner.go index 04504937d4..a2c0f74eb5 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_get_available_model_types_response_inner.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_get_available_model_types_response_inner.go @@ -9,11 +9,11 @@ import ( // GetAvailableModelTypesResponseInner struct for GetAvailableModelTypesResponseInner type GetAvailableModelTypesResponseInner struct { // Name of the model. - Name string `json:"name"` + Name string `json:"name" validate:"required"` // Description of the model. - Type string `json:"type"` - CompatibleSources []CompatibleSources `json:"compatibleSources"` - DataRequirements GetAvailableModelTypesResponseInnerDataRequirements `json:"dataRequirements"` + Type string `json:"type" validate:"required"` + CompatibleSources []CompatibleSources `json:"compatibleSources" validate:"required"` + DataRequirements GetAvailableModelTypesResponseInnerDataRequirements `json:"dataRequirements" validate:"required"` } // NewGetAvailableModelTypesResponseInner instantiates a new GetAvailableModelTypesResponseInner object diff --git a/clients/algoliasearch-client-go/algolia/predict/model_get_available_model_types_response_inner_data_requirements.go b/clients/algoliasearch-client-go/algolia/predict/model_get_available_model_types_response_inner_data_requirements.go index e746d1ba01..fdc9ed21f2 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_get_available_model_types_response_inner_data_requirements.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_get_available_model_types_response_inner_data_requirements.go @@ -9,9 +9,9 @@ import ( // GetAvailableModelTypesResponseInnerDataRequirements struct for GetAvailableModelTypesResponseInnerDataRequirements type GetAvailableModelTypesResponseInnerDataRequirements struct { // Minimum number of users required for this model. - MinUsers int32 `json:"minUsers"` + MinUsers int32 `json:"minUsers" validate:"required"` // Minimum number of days model needs to run. - MinDays int32 `json:"minDays"` + MinDays int32 `json:"minDays" validate:"required"` } // NewGetAvailableModelTypesResponseInnerDataRequirements instantiates a new GetAvailableModelTypesResponseInnerDataRequirements object diff --git a/clients/algoliasearch-client-go/algolia/predict/model_get_model_metrics_response.go b/clients/algoliasearch-client-go/algolia/predict/model_get_model_metrics_response.go index 734b7f6bfd..c437e00f5f 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_get_model_metrics_response.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_get_model_metrics_response.go @@ -9,8 +9,8 @@ import ( // GetModelMetricsResponse struct for GetModelMetricsResponse type GetModelMetricsResponse struct { // The ID of the model. - ModelID string `json:"modelID"` - Metrics []ModelMetrics `json:"metrics"` + ModelID string `json:"modelID" validate:"required"` + Metrics []ModelMetrics `json:"metrics" validate:"required"` } // NewGetModelMetricsResponse instantiates a new GetModelMetricsResponse object diff --git a/clients/algoliasearch-client-go/algolia/predict/model_get_segment_users_response.go b/clients/algoliasearch-client-go/algolia/predict/model_get_segment_users_response.go index a2457fc29b..c84ae9ce06 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_get_segment_users_response.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_get_segment_users_response.go @@ -9,8 +9,8 @@ import ( // GetSegmentUsersResponse struct for GetSegmentUsersResponse type GetSegmentUsersResponse struct { // The ID of the segment. - SegmentID string `json:"segmentID"` - Users []UserProfile `json:"users"` + SegmentID string `json:"segmentID" validate:"required"` + Users []UserProfile `json:"users" validate:"required"` // The token is used to navigate backward in the user list. To navigate from the current user list to the previous page, the API generates the previous page token and it sends the token in the response, beside the current user list. NOTE: This body param cannot be used with `nextPageToken` at the same time. PreviousPageToken *string `json:"previousPageToken,omitempty"` // The token is used to navigate forward in the user list. To navigate from the current user list to the next page, the API generates the next page token and it sends the token in the response, beside the current user list. NOTE: This body param cannot be used with `previousPageToken` at the same time. diff --git a/clients/algoliasearch-client-go/algolia/predict/model_model_attributes.go b/clients/algoliasearch-client-go/algolia/predict/model_model_attributes.go index d15f1dd078..b85cadcbc0 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_model_attributes.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_model_attributes.go @@ -8,7 +8,7 @@ import ( // ModelAttributes struct for ModelAttributes type ModelAttributes struct { - Name string `json:"name"` + Name string `json:"name" validate:"required"` Values []string `json:"values,omitempty"` } diff --git a/clients/algoliasearch-client-go/algolia/predict/model_model_instance.go b/clients/algoliasearch-client-go/algolia/predict/model_model_instance.go index c876825afb..6fb42deda1 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_model_instance.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_model_instance.go @@ -9,19 +9,19 @@ import ( // ModelInstance struct for ModelInstance type ModelInstance struct { // ID of the model. - ModelID string `json:"modelID"` + ModelID string `json:"modelID" validate:"required"` // Name of model instance. - Name string `json:"name"` - Type ModelsToRetrieve `json:"type"` - SourceID string `json:"sourceID"` - Index string `json:"index"` + Name string `json:"name" validate:"required"` + Type ModelsToRetrieve `json:"type" validate:"required"` + SourceID string `json:"sourceID" validate:"required"` + Index string `json:"index" validate:"required"` ModelAttributes []ModelAttributes `json:"modelAttributes,omitempty"` // The date and time this model instance was last trained. - LastTrained string `json:"lastTrained"` + LastTrained string `json:"lastTrained" validate:"required"` // The date and time this model instance generated its last inference. - LastInference string `json:"lastInference"` + LastInference string `json:"lastInference" validate:"required"` ErrorMessage *string `json:"errorMessage,omitempty"` - ModelStatus GetModelInstanceConfigStatus `json:"modelStatus"` + ModelStatus GetModelInstanceConfigStatus `json:"modelStatus" validate:"required"` } type ModelInstanceOption func(f *ModelInstance) diff --git a/clients/algoliasearch-client-go/algolia/predict/model_params.go b/clients/algoliasearch-client-go/algolia/predict/model_params.go index 1c811da740..71d86990c8 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_params.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_params.go @@ -37,15 +37,14 @@ func TypesToRetrieveParamAsParams(v *TypesToRetrieveParam) Params { // Unmarshal JSON data into one of the pointers in the struct func (dst *Params) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into AllParams err = newStrictDecoder(data).Decode(&dst.AllParams) - if err == nil { + if err == nil && validateStruct(dst.AllParams) == nil { jsonAllParams, _ := json.Marshal(dst.AllParams) if string(jsonAllParams) == "{}" { // empty struct dst.AllParams = nil } else { - match++ + return nil } } else { dst.AllParams = nil @@ -53,12 +52,12 @@ func (dst *Params) UnmarshalJSON(data []byte) error { // try to unmarshal data into ModelsToRetrieveParam err = newStrictDecoder(data).Decode(&dst.ModelsToRetrieveParam) - if err == nil { + if err == nil && validateStruct(dst.ModelsToRetrieveParam) == nil { jsonModelsToRetrieveParam, _ := json.Marshal(dst.ModelsToRetrieveParam) if string(jsonModelsToRetrieveParam) == "{}" { // empty struct dst.ModelsToRetrieveParam = nil } else { - match++ + return nil } } else { dst.ModelsToRetrieveParam = nil @@ -66,29 +65,18 @@ func (dst *Params) UnmarshalJSON(data []byte) error { // try to unmarshal data into TypesToRetrieveParam err = newStrictDecoder(data).Decode(&dst.TypesToRetrieveParam) - if err == nil { + if err == nil && validateStruct(dst.TypesToRetrieveParam) == nil { jsonTypesToRetrieveParam, _ := json.Marshal(dst.TypesToRetrieveParam) if string(jsonTypesToRetrieveParam) == "{}" { // empty struct dst.TypesToRetrieveParam = nil } else { - match++ + return nil } } else { dst.TypesToRetrieveParam = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.AllParams = nil - dst.ModelsToRetrieveParam = nil - dst.TypesToRetrieveParam = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(Params)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(Params)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(Params)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/predict/model_prediction_affinity_value.go b/clients/algoliasearch-client-go/algolia/predict/model_prediction_affinity_value.go index 39b09746ca..6f58e599e4 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_prediction_affinity_value.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_prediction_affinity_value.go @@ -37,15 +37,14 @@ func StringAsPredictionAffinityValue(v *string) PredictionAffinityValue { // Unmarshal JSON data into one of the pointers in the struct func (dst *PredictionAffinityValue) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into Bool err = newStrictDecoder(data).Decode(&dst.Bool) - if err == nil { + if err == nil && validateStruct(dst.Bool) == nil { jsonBool, _ := json.Marshal(dst.Bool) if string(jsonBool) == "{}" { // empty struct dst.Bool = nil } else { - match++ + return nil } } else { dst.Bool = nil @@ -53,12 +52,12 @@ func (dst *PredictionAffinityValue) UnmarshalJSON(data []byte) error { // try to unmarshal data into Float64 err = newStrictDecoder(data).Decode(&dst.Float64) - if err == nil { + if err == nil && validateStruct(dst.Float64) == nil { jsonFloat64, _ := json.Marshal(dst.Float64) if string(jsonFloat64) == "{}" { // empty struct dst.Float64 = nil } else { - match++ + return nil } } else { dst.Float64 = nil @@ -66,29 +65,18 @@ func (dst *PredictionAffinityValue) UnmarshalJSON(data []byte) error { // try to unmarshal data into String err = newStrictDecoder(data).Decode(&dst.String) - if err == nil { + if err == nil && validateStruct(dst.String) == nil { jsonString, _ := json.Marshal(dst.String) if string(jsonString) == "{}" { // empty struct dst.String = nil } else { - match++ + return nil } } else { dst.String = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.Bool = nil - dst.Float64 = nil - dst.String = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(PredictionAffinityValue)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(PredictionAffinityValue)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(PredictionAffinityValue)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/predict/model_predictions_affinities.go b/clients/algoliasearch-client-go/algolia/predict/model_predictions_affinities.go index 539a6ea49f..1f39612ca5 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_predictions_affinities.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_predictions_affinities.go @@ -29,15 +29,14 @@ func PredictionsAffinitiesSuccessAsPredictionsAffinities(v *PredictionsAffinitie // Unmarshal JSON data into one of the pointers in the struct func (dst *PredictionsAffinities) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into ModelError err = newStrictDecoder(data).Decode(&dst.ModelError) - if err == nil { + if err == nil && validateStruct(dst.ModelError) == nil { jsonModelError, _ := json.Marshal(dst.ModelError) if string(jsonModelError) == "{}" { // empty struct dst.ModelError = nil } else { - match++ + return nil } } else { dst.ModelError = nil @@ -45,28 +44,18 @@ func (dst *PredictionsAffinities) UnmarshalJSON(data []byte) error { // try to unmarshal data into PredictionsAffinitiesSuccess err = newStrictDecoder(data).Decode(&dst.PredictionsAffinitiesSuccess) - if err == nil { + if err == nil && validateStruct(dst.PredictionsAffinitiesSuccess) == nil { jsonPredictionsAffinitiesSuccess, _ := json.Marshal(dst.PredictionsAffinitiesSuccess) if string(jsonPredictionsAffinitiesSuccess) == "{}" { // empty struct dst.PredictionsAffinitiesSuccess = nil } else { - match++ + return nil } } else { dst.PredictionsAffinitiesSuccess = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.ModelError = nil - dst.PredictionsAffinitiesSuccess = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(PredictionsAffinities)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(PredictionsAffinities)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(PredictionsAffinities)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/predict/model_predictions_affinities_success.go b/clients/algoliasearch-client-go/algolia/predict/model_predictions_affinities_success.go index d157dd1541..48c672ced1 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_predictions_affinities_success.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_predictions_affinities_success.go @@ -8,8 +8,8 @@ import ( // PredictionsAffinitiesSuccess Prediction for the **affinities** model. type PredictionsAffinitiesSuccess struct { - Value []Affinity `json:"value"` - LastUpdatedAt string `json:"lastUpdatedAt"` + Value []Affinity `json:"value" validate:"required"` + LastUpdatedAt string `json:"lastUpdatedAt" validate:"required"` } // NewPredictionsAffinitiesSuccess instantiates a new PredictionsAffinitiesSuccess object diff --git a/clients/algoliasearch-client-go/algolia/predict/model_predictions_funnel_stage.go b/clients/algoliasearch-client-go/algolia/predict/model_predictions_funnel_stage.go index 14b2aa44e8..281500d169 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_predictions_funnel_stage.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_predictions_funnel_stage.go @@ -29,15 +29,14 @@ func PredictionsFunnelStageSuccessAsPredictionsFunnelStage(v *PredictionsFunnelS // Unmarshal JSON data into one of the pointers in the struct func (dst *PredictionsFunnelStage) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into ModelError err = newStrictDecoder(data).Decode(&dst.ModelError) - if err == nil { + if err == nil && validateStruct(dst.ModelError) == nil { jsonModelError, _ := json.Marshal(dst.ModelError) if string(jsonModelError) == "{}" { // empty struct dst.ModelError = nil } else { - match++ + return nil } } else { dst.ModelError = nil @@ -45,28 +44,18 @@ func (dst *PredictionsFunnelStage) UnmarshalJSON(data []byte) error { // try to unmarshal data into PredictionsFunnelStageSuccess err = newStrictDecoder(data).Decode(&dst.PredictionsFunnelStageSuccess) - if err == nil { + if err == nil && validateStruct(dst.PredictionsFunnelStageSuccess) == nil { jsonPredictionsFunnelStageSuccess, _ := json.Marshal(dst.PredictionsFunnelStageSuccess) if string(jsonPredictionsFunnelStageSuccess) == "{}" { // empty struct dst.PredictionsFunnelStageSuccess = nil } else { - match++ + return nil } } else { dst.PredictionsFunnelStageSuccess = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.ModelError = nil - dst.PredictionsFunnelStageSuccess = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(PredictionsFunnelStage)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(PredictionsFunnelStage)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(PredictionsFunnelStage)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/predict/model_predictions_funnel_stage_success.go b/clients/algoliasearch-client-go/algolia/predict/model_predictions_funnel_stage_success.go index 44dd91f5ba..90e8767a55 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_predictions_funnel_stage_success.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_predictions_funnel_stage_success.go @@ -8,8 +8,8 @@ import ( // PredictionsFunnelStageSuccess Prediction for the **funnel_stage** model. type PredictionsFunnelStageSuccess struct { - Value []FunnelStage `json:"value"` - LastUpdatedAt string `json:"lastUpdatedAt"` + Value []FunnelStage `json:"value" validate:"required"` + LastUpdatedAt string `json:"lastUpdatedAt" validate:"required"` } // NewPredictionsFunnelStageSuccess instantiates a new PredictionsFunnelStageSuccess object diff --git a/clients/algoliasearch-client-go/algolia/predict/model_predictions_order_value.go b/clients/algoliasearch-client-go/algolia/predict/model_predictions_order_value.go index ae69f43b26..51b07d264d 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_predictions_order_value.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_predictions_order_value.go @@ -29,15 +29,14 @@ func PredictionsOrderValueSuccessAsPredictionsOrderValue(v *PredictionsOrderValu // Unmarshal JSON data into one of the pointers in the struct func (dst *PredictionsOrderValue) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into ModelError err = newStrictDecoder(data).Decode(&dst.ModelError) - if err == nil { + if err == nil && validateStruct(dst.ModelError) == nil { jsonModelError, _ := json.Marshal(dst.ModelError) if string(jsonModelError) == "{}" { // empty struct dst.ModelError = nil } else { - match++ + return nil } } else { dst.ModelError = nil @@ -45,28 +44,18 @@ func (dst *PredictionsOrderValue) UnmarshalJSON(data []byte) error { // try to unmarshal data into PredictionsOrderValueSuccess err = newStrictDecoder(data).Decode(&dst.PredictionsOrderValueSuccess) - if err == nil { + if err == nil && validateStruct(dst.PredictionsOrderValueSuccess) == nil { jsonPredictionsOrderValueSuccess, _ := json.Marshal(dst.PredictionsOrderValueSuccess) if string(jsonPredictionsOrderValueSuccess) == "{}" { // empty struct dst.PredictionsOrderValueSuccess = nil } else { - match++ + return nil } } else { dst.PredictionsOrderValueSuccess = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.ModelError = nil - dst.PredictionsOrderValueSuccess = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(PredictionsOrderValue)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(PredictionsOrderValue)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(PredictionsOrderValue)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/predict/model_predictions_order_value_success.go b/clients/algoliasearch-client-go/algolia/predict/model_predictions_order_value_success.go index 5f70f3d20b..65f275fe78 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_predictions_order_value_success.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_predictions_order_value_success.go @@ -8,8 +8,8 @@ import ( // PredictionsOrderValueSuccess Prediction for the **order_value** model. type PredictionsOrderValueSuccess struct { - Value float64 `json:"value"` - LastUpdatedAt string `json:"lastUpdatedAt"` + Value float64 `json:"value" validate:"required"` + LastUpdatedAt string `json:"lastUpdatedAt" validate:"required"` } // NewPredictionsOrderValueSuccess instantiates a new PredictionsOrderValueSuccess object diff --git a/clients/algoliasearch-client-go/algolia/predict/model_segment.go b/clients/algoliasearch-client-go/algolia/predict/model_segment.go index aa9c26ffdc..c7cd2edccd 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_segment.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_segment.go @@ -9,16 +9,16 @@ import ( // Segment struct for Segment type Segment struct { // The ID of the segment. - SegmentID string `json:"segmentID"` + SegmentID string `json:"segmentID" validate:"required"` // The name of the segment. - Name string `json:"name"` - Conditions SegmentParentConditions `json:"conditions"` + Name string `json:"name" validate:"required"` + Conditions SegmentParentConditions `json:"conditions" validate:"required"` // The approximate number of users that matched the segment conditions when it was created, last updated, or when model inference last ran. - Size float32 `json:"size"` - SegmentStatus SegmentStatus `json:"segmentStatus"` - Type SegmentType `json:"type"` + Size float32 `json:"size" validate:"required"` + SegmentStatus SegmentStatus `json:"segmentStatus" validate:"required"` + Type SegmentType `json:"type" validate:"required"` // The date and time at which the segment was last updated (RFC3339). - LastUpdatedAt string `json:"lastUpdatedAt"` + LastUpdatedAt string `json:"lastUpdatedAt" validate:"required"` ErrorMessage *string `json:"errorMessage,omitempty"` } diff --git a/clients/algoliasearch-client-go/algolia/predict/model_segment_affinity_filter.go b/clients/algoliasearch-client-go/algolia/predict/model_segment_affinity_filter.go index 5c459e5a54..c33457ec94 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_segment_affinity_filter.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_segment_affinity_filter.go @@ -8,8 +8,8 @@ import ( // SegmentAffinityFilter Filter for affinity model predictions. type SegmentAffinityFilter struct { - Operator SegmentFilterOperatorNumerical `json:"operator"` - Value SegmentAffinityFilterValue `json:"value"` + Operator SegmentFilterOperatorNumerical `json:"operator" validate:"required"` + Value SegmentAffinityFilterValue `json:"value" validate:"required"` Probability *SegmentFilterProbability `json:"probability,omitempty"` } diff --git a/clients/algoliasearch-client-go/algolia/predict/model_segment_affinity_filter_value.go b/clients/algoliasearch-client-go/algolia/predict/model_segment_affinity_filter_value.go index 01371b4b6e..37b4ab0884 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_segment_affinity_filter_value.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_segment_affinity_filter_value.go @@ -45,15 +45,14 @@ func StringAsSegmentAffinityFilterValue(v *string) SegmentAffinityFilterValue { // Unmarshal JSON data into one of the pointers in the struct func (dst *SegmentAffinityFilterValue) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into ArrayOfString err = newStrictDecoder(data).Decode(&dst.ArrayOfString) - if err == nil { + if err == nil && validateStruct(dst.ArrayOfString) == nil { jsonArrayOfString, _ := json.Marshal(dst.ArrayOfString) if string(jsonArrayOfString) == "{}" { // empty struct dst.ArrayOfString = nil } else { - match++ + return nil } } else { dst.ArrayOfString = nil @@ -61,12 +60,12 @@ func (dst *SegmentAffinityFilterValue) UnmarshalJSON(data []byte) error { // try to unmarshal data into Bool err = newStrictDecoder(data).Decode(&dst.Bool) - if err == nil { + if err == nil && validateStruct(dst.Bool) == nil { jsonBool, _ := json.Marshal(dst.Bool) if string(jsonBool) == "{}" { // empty struct dst.Bool = nil } else { - match++ + return nil } } else { dst.Bool = nil @@ -74,12 +73,12 @@ func (dst *SegmentAffinityFilterValue) UnmarshalJSON(data []byte) error { // try to unmarshal data into Float32 err = newStrictDecoder(data).Decode(&dst.Float32) - if err == nil { + if err == nil && validateStruct(dst.Float32) == nil { jsonFloat32, _ := json.Marshal(dst.Float32) if string(jsonFloat32) == "{}" { // empty struct dst.Float32 = nil } else { - match++ + return nil } } else { dst.Float32 = nil @@ -87,30 +86,18 @@ func (dst *SegmentAffinityFilterValue) UnmarshalJSON(data []byte) error { // try to unmarshal data into String err = newStrictDecoder(data).Decode(&dst.String) - if err == nil { + if err == nil && validateStruct(dst.String) == nil { jsonString, _ := json.Marshal(dst.String) if string(jsonString) == "{}" { // empty struct dst.String = nil } else { - match++ + return nil } } else { dst.String = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.ArrayOfString = nil - dst.Bool = nil - dst.Float32 = nil - dst.String = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(SegmentAffinityFilterValue)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(SegmentAffinityFilterValue)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(SegmentAffinityFilterValue)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/predict/model_segment_child_condition_operands.go b/clients/algoliasearch-client-go/algolia/predict/model_segment_child_condition_operands.go index 06fbf38fff..3fb9e2f19b 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_segment_child_condition_operands.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_segment_child_condition_operands.go @@ -45,15 +45,14 @@ func SegmentOperandPropertyAsSegmentChildConditionOperands(v *SegmentOperandProp // Unmarshal JSON data into one of the pointers in the struct func (dst *SegmentChildConditionOperands) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into SegmentOperandAffinity err = newStrictDecoder(data).Decode(&dst.SegmentOperandAffinity) - if err == nil { + if err == nil && validateStruct(dst.SegmentOperandAffinity) == nil { jsonSegmentOperandAffinity, _ := json.Marshal(dst.SegmentOperandAffinity) if string(jsonSegmentOperandAffinity) == "{}" { // empty struct dst.SegmentOperandAffinity = nil } else { - match++ + return nil } } else { dst.SegmentOperandAffinity = nil @@ -61,12 +60,12 @@ func (dst *SegmentChildConditionOperands) UnmarshalJSON(data []byte) error { // try to unmarshal data into SegmentOperandFunnelStage err = newStrictDecoder(data).Decode(&dst.SegmentOperandFunnelStage) - if err == nil { + if err == nil && validateStruct(dst.SegmentOperandFunnelStage) == nil { jsonSegmentOperandFunnelStage, _ := json.Marshal(dst.SegmentOperandFunnelStage) if string(jsonSegmentOperandFunnelStage) == "{}" { // empty struct dst.SegmentOperandFunnelStage = nil } else { - match++ + return nil } } else { dst.SegmentOperandFunnelStage = nil @@ -74,12 +73,12 @@ func (dst *SegmentChildConditionOperands) UnmarshalJSON(data []byte) error { // try to unmarshal data into SegmentOperandOrderValue err = newStrictDecoder(data).Decode(&dst.SegmentOperandOrderValue) - if err == nil { + if err == nil && validateStruct(dst.SegmentOperandOrderValue) == nil { jsonSegmentOperandOrderValue, _ := json.Marshal(dst.SegmentOperandOrderValue) if string(jsonSegmentOperandOrderValue) == "{}" { // empty struct dst.SegmentOperandOrderValue = nil } else { - match++ + return nil } } else { dst.SegmentOperandOrderValue = nil @@ -87,30 +86,18 @@ func (dst *SegmentChildConditionOperands) UnmarshalJSON(data []byte) error { // try to unmarshal data into SegmentOperandProperty err = newStrictDecoder(data).Decode(&dst.SegmentOperandProperty) - if err == nil { + if err == nil && validateStruct(dst.SegmentOperandProperty) == nil { jsonSegmentOperandProperty, _ := json.Marshal(dst.SegmentOperandProperty) if string(jsonSegmentOperandProperty) == "{}" { // empty struct dst.SegmentOperandProperty = nil } else { - match++ + return nil } } else { dst.SegmentOperandProperty = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.SegmentOperandAffinity = nil - dst.SegmentOperandFunnelStage = nil - dst.SegmentOperandOrderValue = nil - dst.SegmentOperandProperty = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(SegmentChildConditionOperands)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(SegmentChildConditionOperands)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(SegmentChildConditionOperands)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/predict/model_segment_child_conditions.go b/clients/algoliasearch-client-go/algolia/predict/model_segment_child_conditions.go index ff7223dad1..cb57847969 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_segment_child_conditions.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_segment_child_conditions.go @@ -8,8 +8,8 @@ import ( // SegmentChildConditions Nested segment conditions that only contain operands. type SegmentChildConditions struct { - Operator SegmentConditionOperator `json:"operator"` - Operands []SegmentChildConditionOperands `json:"operands"` + Operator SegmentConditionOperator `json:"operator" validate:"required"` + Operands []SegmentChildConditionOperands `json:"operands" validate:"required"` } // NewSegmentChildConditions instantiates a new SegmentChildConditions object diff --git a/clients/algoliasearch-client-go/algolia/predict/model_segment_funnel_stage_filter.go b/clients/algoliasearch-client-go/algolia/predict/model_segment_funnel_stage_filter.go index b1ebbd2c75..d9faa5b8a7 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_segment_funnel_stage_filter.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_segment_funnel_stage_filter.go @@ -9,8 +9,8 @@ import ( // SegmentFunnelStageFilter Filter for funnel stage model predictions. type SegmentFunnelStageFilter struct { Operator *SegmentFilterOperatorBoolean `json:"operator,omitempty"` - Value string `json:"value"` - Probability SegmentFilterProbability `json:"probability"` + Value string `json:"value" validate:"required"` + Probability SegmentFilterProbability `json:"probability" validate:"required"` } type SegmentFunnelStageFilterOption func(f *SegmentFunnelStageFilter) diff --git a/clients/algoliasearch-client-go/algolia/predict/model_segment_operand_affinity.go b/clients/algoliasearch-client-go/algolia/predict/model_segment_operand_affinity.go index dc37ac3119..626803ed6b 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_segment_operand_affinity.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_segment_operand_affinity.go @@ -8,8 +8,8 @@ import ( // SegmentOperandAffinity Operand for affinity model predictions. type SegmentOperandAffinity struct { - Name string `json:"name"` - Filters []SegmentAffinityFilter `json:"filters"` + Name string `json:"name" validate:"required"` + Filters []SegmentAffinityFilter `json:"filters" validate:"required"` } // NewSegmentOperandAffinity instantiates a new SegmentOperandAffinity object diff --git a/clients/algoliasearch-client-go/algolia/predict/model_segment_operand_funnel_stage.go b/clients/algoliasearch-client-go/algolia/predict/model_segment_operand_funnel_stage.go index 1a7c33a888..94e4e8a569 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_segment_operand_funnel_stage.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_segment_operand_funnel_stage.go @@ -8,8 +8,8 @@ import ( // SegmentOperandFunnelStage Operand for funnel stage model predictions. type SegmentOperandFunnelStage struct { - Name string `json:"name"` - Filters []SegmentFunnelStageFilter `json:"filters"` + Name string `json:"name" validate:"required"` + Filters []SegmentFunnelStageFilter `json:"filters" validate:"required"` } // NewSegmentOperandFunnelStage instantiates a new SegmentOperandFunnelStage object diff --git a/clients/algoliasearch-client-go/algolia/predict/model_segment_operand_order_value.go b/clients/algoliasearch-client-go/algolia/predict/model_segment_operand_order_value.go index 6981be545e..442a334732 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_segment_operand_order_value.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_segment_operand_order_value.go @@ -8,8 +8,8 @@ import ( // SegmentOperandOrderValue Operand for order value model predictions. type SegmentOperandOrderValue struct { - Name string `json:"name"` - Filters []SegmentOrderValueFilter `json:"filters"` + Name string `json:"name" validate:"required"` + Filters []SegmentOrderValueFilter `json:"filters" validate:"required"` } // NewSegmentOperandOrderValue instantiates a new SegmentOperandOrderValue object diff --git a/clients/algoliasearch-client-go/algolia/predict/model_segment_operand_property.go b/clients/algoliasearch-client-go/algolia/predict/model_segment_operand_property.go index 001830df41..c8d0e5b7ca 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_segment_operand_property.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_segment_operand_property.go @@ -8,8 +8,8 @@ import ( // SegmentOperandProperty Operand for user profile properties. type SegmentOperandProperty struct { - Name string `json:"name"` - Filters []SegmentPropertyFilter `json:"filters"` + Name string `json:"name" validate:"required"` + Filters []SegmentPropertyFilter `json:"filters" validate:"required"` } // NewSegmentOperandProperty instantiates a new SegmentOperandProperty object diff --git a/clients/algoliasearch-client-go/algolia/predict/model_segment_order_value_filter.go b/clients/algoliasearch-client-go/algolia/predict/model_segment_order_value_filter.go index 2db009aaf9..484fdd3647 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_segment_order_value_filter.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_segment_order_value_filter.go @@ -9,7 +9,7 @@ import ( // SegmentOrderValueFilter Filter for order value model predictions. type SegmentOrderValueFilter struct { Operator *SegmentFilterOperatorNumerical `json:"operator,omitempty"` - Value float32 `json:"value"` + Value float32 `json:"value" validate:"required"` } type SegmentOrderValueFilterOption func(f *SegmentOrderValueFilter) diff --git a/clients/algoliasearch-client-go/algolia/predict/model_segment_parent_condition_operands.go b/clients/algoliasearch-client-go/algolia/predict/model_segment_parent_condition_operands.go index 0c0c130d60..ab0fc59177 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_segment_parent_condition_operands.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_segment_parent_condition_operands.go @@ -53,15 +53,14 @@ func SegmentOperandPropertyAsSegmentParentConditionOperands(v *SegmentOperandPro // Unmarshal JSON data into one of the pointers in the struct func (dst *SegmentParentConditionOperands) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into SegmentChildConditions err = newStrictDecoder(data).Decode(&dst.SegmentChildConditions) - if err == nil { + if err == nil && validateStruct(dst.SegmentChildConditions) == nil { jsonSegmentChildConditions, _ := json.Marshal(dst.SegmentChildConditions) if string(jsonSegmentChildConditions) == "{}" { // empty struct dst.SegmentChildConditions = nil } else { - match++ + return nil } } else { dst.SegmentChildConditions = nil @@ -69,12 +68,12 @@ func (dst *SegmentParentConditionOperands) UnmarshalJSON(data []byte) error { // try to unmarshal data into SegmentOperandAffinity err = newStrictDecoder(data).Decode(&dst.SegmentOperandAffinity) - if err == nil { + if err == nil && validateStruct(dst.SegmentOperandAffinity) == nil { jsonSegmentOperandAffinity, _ := json.Marshal(dst.SegmentOperandAffinity) if string(jsonSegmentOperandAffinity) == "{}" { // empty struct dst.SegmentOperandAffinity = nil } else { - match++ + return nil } } else { dst.SegmentOperandAffinity = nil @@ -82,12 +81,12 @@ func (dst *SegmentParentConditionOperands) UnmarshalJSON(data []byte) error { // try to unmarshal data into SegmentOperandFunnelStage err = newStrictDecoder(data).Decode(&dst.SegmentOperandFunnelStage) - if err == nil { + if err == nil && validateStruct(dst.SegmentOperandFunnelStage) == nil { jsonSegmentOperandFunnelStage, _ := json.Marshal(dst.SegmentOperandFunnelStage) if string(jsonSegmentOperandFunnelStage) == "{}" { // empty struct dst.SegmentOperandFunnelStage = nil } else { - match++ + return nil } } else { dst.SegmentOperandFunnelStage = nil @@ -95,12 +94,12 @@ func (dst *SegmentParentConditionOperands) UnmarshalJSON(data []byte) error { // try to unmarshal data into SegmentOperandOrderValue err = newStrictDecoder(data).Decode(&dst.SegmentOperandOrderValue) - if err == nil { + if err == nil && validateStruct(dst.SegmentOperandOrderValue) == nil { jsonSegmentOperandOrderValue, _ := json.Marshal(dst.SegmentOperandOrderValue) if string(jsonSegmentOperandOrderValue) == "{}" { // empty struct dst.SegmentOperandOrderValue = nil } else { - match++ + return nil } } else { dst.SegmentOperandOrderValue = nil @@ -108,31 +107,18 @@ func (dst *SegmentParentConditionOperands) UnmarshalJSON(data []byte) error { // try to unmarshal data into SegmentOperandProperty err = newStrictDecoder(data).Decode(&dst.SegmentOperandProperty) - if err == nil { + if err == nil && validateStruct(dst.SegmentOperandProperty) == nil { jsonSegmentOperandProperty, _ := json.Marshal(dst.SegmentOperandProperty) if string(jsonSegmentOperandProperty) == "{}" { // empty struct dst.SegmentOperandProperty = nil } else { - match++ + return nil } } else { dst.SegmentOperandProperty = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.SegmentChildConditions = nil - dst.SegmentOperandAffinity = nil - dst.SegmentOperandFunnelStage = nil - dst.SegmentOperandOrderValue = nil - dst.SegmentOperandProperty = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(SegmentParentConditionOperands)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(SegmentParentConditionOperands)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(SegmentParentConditionOperands)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/predict/model_segment_parent_conditions.go b/clients/algoliasearch-client-go/algolia/predict/model_segment_parent_conditions.go index 31a041d15b..472e246ddb 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_segment_parent_conditions.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_segment_parent_conditions.go @@ -8,8 +8,8 @@ import ( // SegmentParentConditions The conditions that define which user profiles are included in the segment. Can contain operands and a maximum of 1 level of nested conditions. type SegmentParentConditions struct { - Operator SegmentConditionOperator `json:"operator"` - Operands []SegmentParentConditionOperands `json:"operands"` + Operator SegmentConditionOperator `json:"operator" validate:"required"` + Operands []SegmentParentConditionOperands `json:"operands" validate:"required"` } // NewSegmentParentConditions instantiates a new SegmentParentConditions object diff --git a/clients/algoliasearch-client-go/algolia/predict/model_segment_property_filter.go b/clients/algoliasearch-client-go/algolia/predict/model_segment_property_filter.go index efd291a18d..1a30b2dde3 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_segment_property_filter.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_segment_property_filter.go @@ -9,7 +9,7 @@ import ( // SegmentPropertyFilter Filter for user profile properties. type SegmentPropertyFilter struct { Operator *SegmentFilterOperatorNumerical `json:"operator,omitempty"` - Value SegmentPropertyFilterValue `json:"value"` + Value SegmentPropertyFilterValue `json:"value" validate:"required"` } type SegmentPropertyFilterOption func(f *SegmentPropertyFilter) diff --git a/clients/algoliasearch-client-go/algolia/predict/model_segments.go b/clients/algoliasearch-client-go/algolia/predict/model_segments.go index 0fa50c5b2d..33e04417b9 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_segments.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_segments.go @@ -9,9 +9,9 @@ import ( // Segments Segments that the user belongs to. type Segments struct { // List of computed segments IDs. - Computed []string `json:"computed"` + Computed []string `json:"computed" validate:"required"` // List of custom segments IDs. - Custom []string `json:"custom"` + Custom []string `json:"custom" validate:"required"` } // NewSegments instantiates a new Segments object diff --git a/clients/algoliasearch-client-go/algolia/predict/model_update_model_instance_response.go b/clients/algoliasearch-client-go/algolia/predict/model_update_model_instance_response.go index 2280fe66ae..e5c58ee38e 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_update_model_instance_response.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_update_model_instance_response.go @@ -9,9 +9,9 @@ import ( // UpdateModelInstanceResponse struct for UpdateModelInstanceResponse type UpdateModelInstanceResponse struct { // The ID of the model. - ModelID string `json:"modelID"` + ModelID string `json:"modelID" validate:"required"` // Date of last update (ISO-8601 format). - UpdatedAt string `json:"updatedAt"` + UpdatedAt string `json:"updatedAt" validate:"required"` } // NewUpdateModelInstanceResponse instantiates a new UpdateModelInstanceResponse object diff --git a/clients/algoliasearch-client-go/algolia/predict/model_update_segment_params.go b/clients/algoliasearch-client-go/algolia/predict/model_update_segment_params.go index 81e52849ca..ebc385d3f9 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_update_segment_params.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_update_segment_params.go @@ -37,15 +37,14 @@ func SegmentNameParamAsUpdateSegmentParams(v *SegmentNameParam) UpdateSegmentPar // Unmarshal JSON data into one of the pointers in the struct func (dst *UpdateSegmentParams) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into AllUpdateSegmentParams err = newStrictDecoder(data).Decode(&dst.AllUpdateSegmentParams) - if err == nil { + if err == nil && validateStruct(dst.AllUpdateSegmentParams) == nil { jsonAllUpdateSegmentParams, _ := json.Marshal(dst.AllUpdateSegmentParams) if string(jsonAllUpdateSegmentParams) == "{}" { // empty struct dst.AllUpdateSegmentParams = nil } else { - match++ + return nil } } else { dst.AllUpdateSegmentParams = nil @@ -53,12 +52,12 @@ func (dst *UpdateSegmentParams) UnmarshalJSON(data []byte) error { // try to unmarshal data into SegmentConditionsParam err = newStrictDecoder(data).Decode(&dst.SegmentConditionsParam) - if err == nil { + if err == nil && validateStruct(dst.SegmentConditionsParam) == nil { jsonSegmentConditionsParam, _ := json.Marshal(dst.SegmentConditionsParam) if string(jsonSegmentConditionsParam) == "{}" { // empty struct dst.SegmentConditionsParam = nil } else { - match++ + return nil } } else { dst.SegmentConditionsParam = nil @@ -66,29 +65,18 @@ func (dst *UpdateSegmentParams) UnmarshalJSON(data []byte) error { // try to unmarshal data into SegmentNameParam err = newStrictDecoder(data).Decode(&dst.SegmentNameParam) - if err == nil { + if err == nil && validateStruct(dst.SegmentNameParam) == nil { jsonSegmentNameParam, _ := json.Marshal(dst.SegmentNameParam) if string(jsonSegmentNameParam) == "{}" { // empty struct dst.SegmentNameParam = nil } else { - match++ + return nil } } else { dst.SegmentNameParam = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.AllUpdateSegmentParams = nil - dst.SegmentConditionsParam = nil - dst.SegmentNameParam = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(UpdateSegmentParams)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(UpdateSegmentParams)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(UpdateSegmentParams)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/predict/model_update_segment_response.go b/clients/algoliasearch-client-go/algolia/predict/model_update_segment_response.go index 67c307cd36..3ef5ac1267 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_update_segment_response.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_update_segment_response.go @@ -9,11 +9,11 @@ import ( // UpdateSegmentResponse struct for UpdateSegmentResponse type UpdateSegmentResponse struct { // The ID of the segment. - SegmentID string `json:"segmentID"` + SegmentID string `json:"segmentID" validate:"required"` // The approximate number of users that matched the segment conditions when it was created, last updated, or when model inference last ran. Size *float32 `json:"size,omitempty"` // The date and time at which the segment was updated (RFC3339). - UpdatedAt string `json:"updatedAt"` + UpdatedAt string `json:"updatedAt" validate:"required"` } type UpdateSegmentResponseOption func(f *UpdateSegmentResponse) diff --git a/clients/algoliasearch-client-go/algolia/predict/model_user_profile.go b/clients/algoliasearch-client-go/algolia/predict/model_user_profile.go index f2c1414211..196d7a6d5b 100644 --- a/clients/algoliasearch-client-go/algolia/predict/model_user_profile.go +++ b/clients/algoliasearch-client-go/algolia/predict/model_user_profile.go @@ -8,7 +8,7 @@ import ( // UserProfile struct for UserProfile type UserProfile struct { - User string `json:"user"` + User string `json:"user" validate:"required"` Predictions *Predictions `json:"predictions,omitempty"` Properties *Properties `json:"properties,omitempty"` Segments *Segments `json:"segments,omitempty"` diff --git a/clients/algoliasearch-client-go/algolia/predict/utils.go b/clients/algoliasearch-client-go/algolia/predict/utils.go index 2ef4759b0a..0e4f1ceb60 100644 --- a/clients/algoliasearch-client-go/algolia/predict/utils.go +++ b/clients/algoliasearch-client-go/algolia/predict/utils.go @@ -336,6 +336,8 @@ func isNilorEmpty(i any) bool { switch reflect.TypeOf(i).Kind() { case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.UnsafePointer, reflect.Interface, reflect.Slice: return reflect.ValueOf(i).IsNil() + case reflect.Bool: + return false default: return reflect.ValueOf(i).IsZero() } 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 04d50f4f87..c2aca25fe9 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 @@ -4,6 +4,7 @@ package suggestions import ( "bytes" "context" + "encoding/json" "io" "net/http" "net/url" @@ -29,7 +30,7 @@ func QueryParamOption(name string, val any) Option { func HeaderParamOption(name string, val any) Option { return Option{ optionType: "header", - name: "itemsPerPage", + name: name, value: parameterToString(val), } } @@ -38,8 +39,32 @@ type ApiCreateConfigRequest struct { querySuggestionsIndexWithIndexParam *QuerySuggestionsIndexWithIndexParam } -func (r ApiCreateConfigRequest) WithQuerySuggestionsIndexWithIndexParam(querySuggestionsIndexWithIndexParam QuerySuggestionsIndexWithIndexParam) ApiCreateConfigRequest { - r.querySuggestionsIndexWithIndexParam = &querySuggestionsIndexWithIndexParam +func (r *ApiCreateConfigRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["querySuggestionsIndexWithIndexParam"]; ok { //querySuggestionsIndexWithIndexParam + err = json.Unmarshal(v, &r.querySuggestionsIndexWithIndexParam) + if err != nil { + err = json.Unmarshal(b, &r.querySuggestionsIndexWithIndexParam) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.querySuggestionsIndexWithIndexParam) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiCreateConfigRequest) WithQuerySuggestionsIndexWithIndexParam(querySuggestionsIndexWithIndexParam *QuerySuggestionsIndexWithIndexParam) ApiCreateConfigRequest { + r.querySuggestionsIndexWithIndexParam = querySuggestionsIndexWithIndexParam return r } @@ -67,7 +92,7 @@ func (c *APIClient) CreateConfig(r ApiCreateConfigRequest, opts ...Option) (*Suc for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -160,6 +185,34 @@ type ApiDelRequest struct { parameters map[string]interface{} } +func (r *ApiDelRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + + return nil +} + // Query parameters to be applied to the current query. func (r ApiDelRequest) WithParameters(parameters map[string]interface{}) ApiDelRequest { r.parameters = parameters @@ -187,14 +240,16 @@ func (c *APIClient) Del(r ApiDelRequest, opts ...Option) (map[string]interface{} queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -275,6 +330,25 @@ type ApiDeleteConfigRequest struct { indexName string } +func (r *ApiDeleteConfigRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiDeleteConfigRequest func (c *APIClient) NewApiDeleteConfigRequest(indexName string) ApiDeleteConfigRequest { return ApiDeleteConfigRequest{ @@ -299,7 +373,7 @@ func (c *APIClient) DeleteConfig(r ApiDeleteConfigRequest, opts ...Option) (*Suc for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -372,6 +446,34 @@ type ApiGetRequest struct { parameters map[string]interface{} } +func (r *ApiGetRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + + return nil +} + // Query parameters to be applied to the current query. func (r ApiGetRequest) WithParameters(parameters map[string]interface{}) ApiGetRequest { r.parameters = parameters @@ -399,14 +501,16 @@ func (c *APIClient) Get(r ApiGetRequest, opts ...Option) (map[string]interface{} queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -486,6 +590,16 @@ func (c *APIClient) Get(r ApiGetRequest, opts ...Option) (map[string]interface{} type ApiGetAllConfigsRequest struct { } +func (r *ApiGetAllConfigsRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + + return nil +} + // @return ApiGetAllConfigsRequest func (c *APIClient) NewApiGetAllConfigsRequest() ApiGetAllConfigsRequest { return ApiGetAllConfigsRequest{} @@ -507,7 +621,7 @@ func (c *APIClient) GetAllConfigs(r ApiGetAllConfigsRequest, opts ...Option) ([] for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -588,6 +702,25 @@ type ApiGetConfigRequest struct { indexName string } +func (r *ApiGetConfigRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiGetConfigRequest func (c *APIClient) NewApiGetConfigRequest(indexName string) ApiGetConfigRequest { return ApiGetConfigRequest{ @@ -612,7 +745,7 @@ func (c *APIClient) GetConfig(r ApiGetConfigRequest, opts ...Option) (*QuerySugg for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -702,6 +835,25 @@ type ApiGetConfigStatusRequest struct { indexName string } +func (r *ApiGetConfigStatusRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiGetConfigStatusRequest func (c *APIClient) NewApiGetConfigStatusRequest(indexName string) ApiGetConfigStatusRequest { return ApiGetConfigStatusRequest{ @@ -726,7 +878,7 @@ func (c *APIClient) GetConfigStatus(r ApiGetConfigStatusRequest, opts ...Option) for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -798,6 +950,25 @@ type ApiGetLogFileRequest struct { indexName string } +func (r *ApiGetLogFileRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiGetLogFileRequest func (c *APIClient) NewApiGetLogFileRequest(indexName string) ApiGetLogFileRequest { return ApiGetLogFileRequest{ @@ -822,7 +993,7 @@ func (c *APIClient) GetLogFile(r ApiGetLogFileRequest, opts ...Option) ([]LogFil for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -905,6 +1076,43 @@ type ApiPostRequest struct { body map[string]interface{} } +func (r *ApiPostRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + if v, ok := req["body"]; ok { //body + err = json.Unmarshal(v, &r.body) + if err != nil { + err = json.Unmarshal(b, &r.body) + if err != nil { + return err + } + } + } + + return nil +} + // Query parameters to be applied to the current query. func (r ApiPostRequest) WithParameters(parameters map[string]interface{}) ApiPostRequest { r.parameters = parameters @@ -938,21 +1146,27 @@ func (c *APIClient) Post(r ApiPostRequest, opts ...Option) (map[string]interface queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } } // body params - postBody = r.body + if isNilorEmpty(r.body) { + postBody = "{}" + } else { + postBody = r.body + } req, err := c.prepareRequest(context.Background(), requestPath, http.MethodPost, postBody, headers, queryParams) if err != nil { return returnValue, err @@ -1030,6 +1244,43 @@ type ApiPutRequest struct { body map[string]interface{} } +func (r *ApiPutRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + if v, ok := req["body"]; ok { //body + err = json.Unmarshal(v, &r.body) + if err != nil { + err = json.Unmarshal(b, &r.body) + if err != nil { + return err + } + } + } + + return nil +} + // Query parameters to be applied to the current query. func (r ApiPutRequest) WithParameters(parameters map[string]interface{}) ApiPutRequest { r.parameters = parameters @@ -1063,21 +1314,27 @@ func (c *APIClient) Put(r ApiPutRequest, opts ...Option) (map[string]interface{} queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } } // body params - postBody = r.body + if isNilorEmpty(r.body) { + postBody = "{}" + } else { + postBody = r.body + } req, err := c.prepareRequest(context.Background(), requestPath, http.MethodPut, postBody, headers, queryParams) if err != nil { return returnValue, err @@ -1154,8 +1411,41 @@ type ApiUpdateConfigRequest struct { querySuggestionsIndexParam *QuerySuggestionsIndexParam } -func (r ApiUpdateConfigRequest) WithQuerySuggestionsIndexParam(querySuggestionsIndexParam QuerySuggestionsIndexParam) ApiUpdateConfigRequest { - r.querySuggestionsIndexParam = &querySuggestionsIndexParam +func (r *ApiUpdateConfigRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + if v, ok := req["querySuggestionsIndexParam"]; ok { //querySuggestionsIndexParam + err = json.Unmarshal(v, &r.querySuggestionsIndexParam) + if err != nil { + err = json.Unmarshal(b, &r.querySuggestionsIndexParam) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.querySuggestionsIndexParam) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiUpdateConfigRequest) WithQuerySuggestionsIndexParam(querySuggestionsIndexParam *QuerySuggestionsIndexParam) ApiUpdateConfigRequest { + r.querySuggestionsIndexParam = querySuggestionsIndexParam return r } @@ -1186,7 +1476,7 @@ func (c *APIClient) UpdateConfig(r ApiUpdateConfigRequest, opts ...Option) (*Suc for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } diff --git a/clients/algoliasearch-client-go/algolia/query-suggestions/client.go b/clients/algoliasearch-client-go/algolia/query-suggestions/client.go index a0eaf52157..f30db4cd9e 100644 --- a/clients/algoliasearch-client-go/algolia/query-suggestions/client.go +++ b/clients/algoliasearch-client-go/algolia/query-suggestions/client.go @@ -20,6 +20,8 @@ import ( "strings" "time" + "github.com/go-playground/validator/v10" + "github.com/algolia/algoliasearch-client-go/v4/algolia/call" "github.com/algolia/algoliasearch-client-go/v4/algolia/compression" "github.com/algolia/algoliasearch-client-go/v4/algolia/internal/transport" @@ -130,7 +132,7 @@ func typeCheckParameter(obj any, expected string, name string) error { // parameterToString convert any parameters to string. func parameterToString(obj any) string { if reflect.TypeOf(obj).Kind() == reflect.Slice { - return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", "", -1), "[]") + return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", ",", -1), "[]") } else if t, ok := obj.(time.Time); ok { return t.Format(time.RFC3339) } @@ -229,11 +231,9 @@ func (c *APIClient) prepareRequest( // add header parameters, if any if len(headerParams) > 0 { - headers := http.Header{} for h, v := range headerParams { - headers[h] = []string{v} + req.Header.Add(h, v) } - req.Header = headers } // Add the user agent to the request. @@ -292,6 +292,17 @@ func newStrictDecoder(data []byte) *json.Decoder { return dec } +// A wrapper for validating a struct, returns nil if value is not a struct +func validateStruct(v any) error { + err := validator.New().Struct(v) + validationErrors, ok := err.(validator.ValidationErrors) + if ok && len(validationErrors) > 0 { + return validationErrors + } + + return nil +} + // Set request body from an any func setBody(body any, contentType string, c compression.Compression) (bodyBuf *bytes.Buffer, err error) { if body == nil { diff --git a/clients/algoliasearch-client-go/algolia/query-suggestions/model_index_name.go b/clients/algoliasearch-client-go/algolia/query-suggestions/model_index_name.go index d799c24cd2..01bde0b7b8 100644 --- a/clients/algoliasearch-client-go/algolia/query-suggestions/model_index_name.go +++ b/clients/algoliasearch-client-go/algolia/query-suggestions/model_index_name.go @@ -9,7 +9,7 @@ import ( // IndexName struct for IndexName type IndexName struct { // Index name to target. - IndexName string `json:"indexName"` + IndexName string `json:"indexName" validate:"required"` } // NewIndexName instantiates a new IndexName object diff --git a/clients/algoliasearch-client-go/algolia/query-suggestions/model_log_file.go b/clients/algoliasearch-client-go/algolia/query-suggestions/model_log_file.go index ff2f012825..15adcb3b65 100644 --- a/clients/algoliasearch-client-go/algolia/query-suggestions/model_log_file.go +++ b/clients/algoliasearch-client-go/algolia/query-suggestions/model_log_file.go @@ -9,12 +9,12 @@ import ( // LogFile struct for LogFile type LogFile struct { // date and time of creation of the record. - Timestamp string `json:"timestamp"` - Level LogLevel `json:"level"` + Timestamp string `json:"timestamp" validate:"required"` + Level LogLevel `json:"level" validate:"required"` // detailed description of what happened. - Message string `json:"message"` + Message string `json:"message" validate:"required"` // indicates the hierarchy of the records. For example, a record with contextLevel=1 belongs to a preceding record with contextLevel=0. - ContextLevel int32 `json:"contextLevel"` + ContextLevel int32 `json:"contextLevel" validate:"required"` } // NewLogFile instantiates a new LogFile object diff --git a/clients/algoliasearch-client-go/algolia/query-suggestions/model_query_suggestions_index.go b/clients/algoliasearch-client-go/algolia/query-suggestions/model_query_suggestions_index.go index ae9252cb46..c4a31482b5 100644 --- a/clients/algoliasearch-client-go/algolia/query-suggestions/model_query_suggestions_index.go +++ b/clients/algoliasearch-client-go/algolia/query-suggestions/model_query_suggestions_index.go @@ -9,13 +9,13 @@ import ( // QuerySuggestionsIndex struct for QuerySuggestionsIndex type QuerySuggestionsIndex struct { // Index name to target. - IndexName string `json:"indexName"` + IndexName string `json:"indexName" validate:"required"` // List of source indices used to generate a Query Suggestions index. - SourceIndices []SourceIndexWithReplicas `json:"sourceIndices"` + SourceIndices []SourceIndexWithReplicas `json:"sourceIndices" validate:"required"` // De-duplicate singular and plural suggestions. For example, let's say your index contains English content, and that two suggestions “shoe” and “shoes” end up in your Query Suggestions index. If the English language is configured, only the most popular of those two suggestions would remain. - Languages []string `json:"languages"` + Languages []string `json:"languages" validate:"required"` // List of words and patterns to exclude from the Query Suggestions index. - Exclude []string `json:"exclude"` + Exclude []string `json:"exclude" validate:"required"` } // NewQuerySuggestionsIndex instantiates a new QuerySuggestionsIndex object diff --git a/clients/algoliasearch-client-go/algolia/query-suggestions/model_query_suggestions_index_param.go b/clients/algoliasearch-client-go/algolia/query-suggestions/model_query_suggestions_index_param.go index f65c163f85..727e59416b 100644 --- a/clients/algoliasearch-client-go/algolia/query-suggestions/model_query_suggestions_index_param.go +++ b/clients/algoliasearch-client-go/algolia/query-suggestions/model_query_suggestions_index_param.go @@ -9,7 +9,7 @@ import ( // QuerySuggestionsIndexParam struct for QuerySuggestionsIndexParam type QuerySuggestionsIndexParam struct { // List of source indices used to generate a Query Suggestions index. - SourceIndices []SourceIndex `json:"sourceIndices"` + SourceIndices []SourceIndex `json:"sourceIndices" validate:"required"` // De-duplicate singular and plural suggestions. For example, let's say your index contains English content, and that two suggestions “shoe” and “shoes” end up in your Query Suggestions index. If the English language is configured, only the most popular of those two suggestions would remain. Languages []string `json:"languages,omitempty"` // List of words and patterns to exclude from the Query Suggestions index. diff --git a/clients/algoliasearch-client-go/algolia/query-suggestions/model_query_suggestions_index_with_index_param.go b/clients/algoliasearch-client-go/algolia/query-suggestions/model_query_suggestions_index_with_index_param.go index 217d536dcb..0ba32ca078 100644 --- a/clients/algoliasearch-client-go/algolia/query-suggestions/model_query_suggestions_index_with_index_param.go +++ b/clients/algoliasearch-client-go/algolia/query-suggestions/model_query_suggestions_index_with_index_param.go @@ -9,13 +9,13 @@ import ( // QuerySuggestionsIndexWithIndexParam struct for QuerySuggestionsIndexWithIndexParam type QuerySuggestionsIndexWithIndexParam struct { // List of source indices used to generate a Query Suggestions index. - SourceIndices []SourceIndex `json:"sourceIndices"` + SourceIndices []SourceIndex `json:"sourceIndices" validate:"required"` // De-duplicate singular and plural suggestions. For example, let's say your index contains English content, and that two suggestions “shoe” and “shoes” end up in your Query Suggestions index. If the English language is configured, only the most popular of those two suggestions would remain. Languages []string `json:"languages,omitempty"` // List of words and patterns to exclude from the Query Suggestions index. Exclude []string `json:"exclude,omitempty"` // Index name to target. - IndexName string `json:"indexName"` + IndexName string `json:"indexName" validate:"required"` } type QuerySuggestionsIndexWithIndexParamOption func(f *QuerySuggestionsIndexWithIndexParam) diff --git a/clients/algoliasearch-client-go/algolia/query-suggestions/model_source_index.go b/clients/algoliasearch-client-go/algolia/query-suggestions/model_source_index.go index 6eabfaa870..0a58e8ae2a 100644 --- a/clients/algoliasearch-client-go/algolia/query-suggestions/model_source_index.go +++ b/clients/algoliasearch-client-go/algolia/query-suggestions/model_source_index.go @@ -9,7 +9,7 @@ import ( // SourceIndex struct for SourceIndex type SourceIndex struct { // Source index name. - IndexName string `json:"indexName"` + IndexName string `json:"indexName" validate:"required"` // List of analytics tags to filter the popular searches per tag. AnalyticsTags []string `json:"analyticsTags,omitempty"` // List of facets to define as categories for the query suggestions. diff --git a/clients/algoliasearch-client-go/algolia/query-suggestions/model_source_index_external.go b/clients/algoliasearch-client-go/algolia/query-suggestions/model_source_index_external.go index ead58b43f4..54dec459cc 100644 --- a/clients/algoliasearch-client-go/algolia/query-suggestions/model_source_index_external.go +++ b/clients/algoliasearch-client-go/algolia/query-suggestions/model_source_index_external.go @@ -9,9 +9,9 @@ import ( // SourceIndexExternal struct for SourceIndexExternal type SourceIndexExternal struct { // The suggestion you would like to add. - Query string `json:"query"` + Query string `json:"query" validate:"required"` // The measure of the suggestion relative popularity. - Count int32 `json:"count"` + Count int32 `json:"count" validate:"required"` } // NewSourceIndexExternal instantiates a new SourceIndexExternal object diff --git a/clients/algoliasearch-client-go/algolia/query-suggestions/model_source_index_with_replicas.go b/clients/algoliasearch-client-go/algolia/query-suggestions/model_source_index_with_replicas.go index 61b17cff79..004a1ecf20 100644 --- a/clients/algoliasearch-client-go/algolia/query-suggestions/model_source_index_with_replicas.go +++ b/clients/algoliasearch-client-go/algolia/query-suggestions/model_source_index_with_replicas.go @@ -9,21 +9,21 @@ import ( // SourceIndexWithReplicas Source index with replicas used to generate a Query Suggestions index. type SourceIndexWithReplicas struct { // true if the Query Suggestions index is a replicas. - Replicas bool `json:"replicas"` + Replicas bool `json:"replicas" validate:"required"` // Source index name. - IndexName string `json:"indexName"` + IndexName string `json:"indexName" validate:"required"` // List of analytics tags to filter the popular searches per tag. - AnalyticsTags []string `json:"analyticsTags"` + AnalyticsTags []string `json:"analyticsTags" validate:"required"` // List of facets to define as categories for the query suggestions. - Facets []map[string]interface{} `json:"facets"` + Facets []map[string]interface{} `json:"facets" validate:"required"` // Minimum number of hits (e.g., matching records in the source index) to generate a suggestions. - MinHits int32 `json:"minHits"` + MinHits int32 `json:"minHits" validate:"required"` // Minimum number of required letters for a suggestion to remain. - MinLetters int32 `json:"minLetters"` + MinLetters int32 `json:"minLetters" validate:"required"` // List of facet attributes used to generate Query Suggestions. The resulting suggestions are every combination of the facets in the nested list (e.g., (facetA and facetB) and facetC). - Generate [][]string `json:"generate"` + Generate [][]string `json:"generate" validate:"required"` // List of external indices to use to generate custom Query Suggestions. - External []SourceIndexExternal `json:"external"` + External []SourceIndexExternal `json:"external" validate:"required"` } // NewSourceIndexWithReplicas instantiates a new SourceIndexWithReplicas object diff --git a/clients/algoliasearch-client-go/algolia/query-suggestions/model_status.go b/clients/algoliasearch-client-go/algolia/query-suggestions/model_status.go index 71ce9311f1..39682fc3aa 100644 --- a/clients/algoliasearch-client-go/algolia/query-suggestions/model_status.go +++ b/clients/algoliasearch-client-go/algolia/query-suggestions/model_status.go @@ -9,11 +9,11 @@ import ( // Status struct for Status type Status struct { // The targeted index name. - IndexName string `json:"indexName"` + IndexName string `json:"indexName" validate:"required"` // true if the Query Suggestions index is running. - IsRunning bool `json:"isRunning"` + IsRunning bool `json:"isRunning" validate:"required"` // Date and time of the last build. - LastBuiltAt string `json:"lastBuiltAt"` + LastBuiltAt string `json:"lastBuiltAt" validate:"required"` } // NewStatus instantiates a new Status object diff --git a/clients/algoliasearch-client-go/algolia/query-suggestions/model_success_response.go b/clients/algoliasearch-client-go/algolia/query-suggestions/model_success_response.go index 2727de34ff..1e50a4ae47 100644 --- a/clients/algoliasearch-client-go/algolia/query-suggestions/model_success_response.go +++ b/clients/algoliasearch-client-go/algolia/query-suggestions/model_success_response.go @@ -9,9 +9,9 @@ import ( // SuccessResponse struct for SuccessResponse type SuccessResponse struct { // The status code. - Status int32 `json:"status"` + Status int32 `json:"status" validate:"required"` // Message of the response. - Message string `json:"message"` + Message string `json:"message" validate:"required"` } // NewSuccessResponse instantiates a new SuccessResponse object diff --git a/clients/algoliasearch-client-go/algolia/query-suggestions/utils.go b/clients/algoliasearch-client-go/algolia/query-suggestions/utils.go index f63326b1ce..1a4cdd63e2 100644 --- a/clients/algoliasearch-client-go/algolia/query-suggestions/utils.go +++ b/clients/algoliasearch-client-go/algolia/query-suggestions/utils.go @@ -336,6 +336,8 @@ func isNilorEmpty(i any) bool { switch reflect.TypeOf(i).Kind() { case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.UnsafePointer, reflect.Interface, reflect.Slice: return reflect.ValueOf(i).IsNil() + case reflect.Bool: + return false default: return reflect.ValueOf(i).IsZero() } diff --git a/clients/algoliasearch-client-go/algolia/recommend/api_recommend.go b/clients/algoliasearch-client-go/algolia/recommend/api_recommend.go index d679fa9576..d0bb929438 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/api_recommend.go +++ b/clients/algoliasearch-client-go/algolia/recommend/api_recommend.go @@ -4,6 +4,7 @@ package recommend import ( "bytes" "context" + "encoding/json" "io" "net/http" "net/url" @@ -29,7 +30,7 @@ func QueryParamOption(name string, val any) Option { func HeaderParamOption(name string, val any) Option { return Option{ optionType: "header", - name: "itemsPerPage", + name: name, value: parameterToString(val), } } @@ -39,6 +40,34 @@ type ApiDelRequest struct { parameters map[string]interface{} } +func (r *ApiDelRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + + return nil +} + // Query parameters to be applied to the current query. func (r ApiDelRequest) WithParameters(parameters map[string]interface{}) ApiDelRequest { r.parameters = parameters @@ -66,14 +95,16 @@ func (c *APIClient) Del(r ApiDelRequest, opts ...Option) (map[string]interface{} queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -155,6 +186,34 @@ type ApiGetRequest struct { parameters map[string]interface{} } +func (r *ApiGetRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + + return nil +} + // Query parameters to be applied to the current query. func (r ApiGetRequest) WithParameters(parameters map[string]interface{}) ApiGetRequest { r.parameters = parameters @@ -182,14 +241,16 @@ func (c *APIClient) Get(r ApiGetRequest, opts ...Option) (map[string]interface{} queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -270,8 +331,32 @@ type ApiGetRecommendationsRequest struct { getRecommendationsParams *GetRecommendationsParams } -func (r ApiGetRecommendationsRequest) WithGetRecommendationsParams(getRecommendationsParams GetRecommendationsParams) ApiGetRecommendationsRequest { - r.getRecommendationsParams = &getRecommendationsParams +func (r *ApiGetRecommendationsRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["getRecommendationsParams"]; ok { //getRecommendationsParams + err = json.Unmarshal(v, &r.getRecommendationsParams) + if err != nil { + err = json.Unmarshal(b, &r.getRecommendationsParams) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.getRecommendationsParams) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiGetRecommendationsRequest) WithGetRecommendationsParams(getRecommendationsParams *GetRecommendationsParams) ApiGetRecommendationsRequest { + r.getRecommendationsParams = getRecommendationsParams return r } @@ -299,7 +384,7 @@ func (c *APIClient) GetRecommendations(r ApiGetRecommendationsRequest, opts ...O for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -384,6 +469,43 @@ type ApiPostRequest struct { body map[string]interface{} } +func (r *ApiPostRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + if v, ok := req["body"]; ok { //body + err = json.Unmarshal(v, &r.body) + if err != nil { + err = json.Unmarshal(b, &r.body) + if err != nil { + return err + } + } + } + + return nil +} + // Query parameters to be applied to the current query. func (r ApiPostRequest) WithParameters(parameters map[string]interface{}) ApiPostRequest { r.parameters = parameters @@ -417,21 +539,27 @@ func (c *APIClient) Post(r ApiPostRequest, opts ...Option) (map[string]interface queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } } // body params - postBody = r.body + if isNilorEmpty(r.body) { + postBody = "{}" + } else { + postBody = r.body + } req, err := c.prepareRequest(context.Background(), requestPath, http.MethodPost, postBody, headers, queryParams) if err != nil { return returnValue, err @@ -509,6 +637,43 @@ type ApiPutRequest struct { body map[string]interface{} } +func (r *ApiPutRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + if v, ok := req["body"]; ok { //body + err = json.Unmarshal(v, &r.body) + if err != nil { + err = json.Unmarshal(b, &r.body) + if err != nil { + return err + } + } + } + + return nil +} + // Query parameters to be applied to the current query. func (r ApiPutRequest) WithParameters(parameters map[string]interface{}) ApiPutRequest { r.parameters = parameters @@ -542,21 +707,27 @@ func (c *APIClient) Put(r ApiPutRequest, opts ...Option) (map[string]interface{} queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } } // body params - postBody = r.body + if isNilorEmpty(r.body) { + postBody = "{}" + } else { + postBody = r.body + } req, err := c.prepareRequest(context.Background(), requestPath, http.MethodPut, postBody, headers, queryParams) if err != nil { return returnValue, err diff --git a/clients/algoliasearch-client-go/algolia/recommend/client.go b/clients/algoliasearch-client-go/algolia/recommend/client.go index 1811e76284..5266aba29f 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/client.go +++ b/clients/algoliasearch-client-go/algolia/recommend/client.go @@ -20,6 +20,8 @@ import ( "strings" "time" + "github.com/go-playground/validator/v10" + "github.com/algolia/algoliasearch-client-go/v4/algolia/call" "github.com/algolia/algoliasearch-client-go/v4/algolia/compression" "github.com/algolia/algoliasearch-client-go/v4/algolia/internal/transport" @@ -132,7 +134,7 @@ func typeCheckParameter(obj any, expected string, name string) error { // parameterToString convert any parameters to string. func parameterToString(obj any) string { if reflect.TypeOf(obj).Kind() == reflect.Slice { - return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", "", -1), "[]") + return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", ",", -1), "[]") } else if t, ok := obj.(time.Time); ok { return t.Format(time.RFC3339) } @@ -231,11 +233,9 @@ func (c *APIClient) prepareRequest( // add header parameters, if any if len(headerParams) > 0 { - headers := http.Header{} for h, v := range headerParams { - headers[h] = []string{v} + req.Header.Add(h, v) } - req.Header = headers } // Add the user agent to the request. @@ -294,6 +294,17 @@ func newStrictDecoder(data []byte) *json.Decoder { return dec } +// A wrapper for validating a struct, returns nil if value is not a struct +func validateStruct(v any) error { + err := validator.New().Struct(v) + validationErrors, ok := err.(validator.ValidationErrors) + if ok && len(validationErrors) > 0 { + return validationErrors + } + + return nil +} + // Set request body from an any func setBody(body any, contentType string, c compression.Compression) (bodyBuf *bytes.Buffer, err error) { if body == nil { diff --git a/clients/algoliasearch-client-go/algolia/recommend/model_around_radius.go b/clients/algoliasearch-client-go/algolia/recommend/model_around_radius.go index 68d75377ef..00566d2cca 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/model_around_radius.go +++ b/clients/algoliasearch-client-go/algolia/recommend/model_around_radius.go @@ -29,15 +29,14 @@ func Int32AsAroundRadius(v *int32) AroundRadius { // Unmarshal JSON data into one of the pointers in the struct func (dst *AroundRadius) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into AroundRadiusAll err = newStrictDecoder(data).Decode(&dst.AroundRadiusAll) - if err == nil { + if err == nil && validateStruct(dst.AroundRadiusAll) == nil { jsonAroundRadiusAll, _ := json.Marshal(dst.AroundRadiusAll) if string(jsonAroundRadiusAll) == "{}" { // empty struct dst.AroundRadiusAll = nil } else { - match++ + return nil } } else { dst.AroundRadiusAll = nil @@ -45,28 +44,18 @@ func (dst *AroundRadius) UnmarshalJSON(data []byte) error { // try to unmarshal data into Int32 err = newStrictDecoder(data).Decode(&dst.Int32) - if err == nil { + if err == nil && validateStruct(dst.Int32) == nil { jsonInt32, _ := json.Marshal(dst.Int32) if string(jsonInt32) == "{}" { // empty struct dst.Int32 = nil } else { - match++ + return nil } } else { dst.Int32 = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.AroundRadiusAll = nil - dst.Int32 = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(AroundRadius)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(AroundRadius)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(AroundRadius)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/recommend/model_base_recommend_request.go b/clients/algoliasearch-client-go/algolia/recommend/model_base_recommend_request.go index 4ea8dbb3d7..1a8963f160 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/model_base_recommend_request.go +++ b/clients/algoliasearch-client-go/algolia/recommend/model_base_recommend_request.go @@ -9,9 +9,9 @@ import ( // BaseRecommendRequest struct for BaseRecommendRequest type BaseRecommendRequest struct { // The Algolia index name. - IndexName string `json:"indexName"` + IndexName string `json:"indexName" validate:"required"` // The threshold to use when filtering recommendations by their score. - Threshold int32 `json:"threshold"` + Threshold int32 `json:"threshold" validate:"required"` // The max number of recommendations to retrieve. If it's set to 0, all the recommendations of the objectID may be returned. MaxRecommendations *int32 `json:"maxRecommendations,omitempty"` QueryParameters *SearchParamsObject `json:"queryParameters,omitempty"` diff --git a/clients/algoliasearch-client-go/algolia/recommend/model_base_recommendation_request.go b/clients/algoliasearch-client-go/algolia/recommend/model_base_recommendation_request.go index d4842df3f1..a6c761a854 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/model_base_recommendation_request.go +++ b/clients/algoliasearch-client-go/algolia/recommend/model_base_recommendation_request.go @@ -8,9 +8,9 @@ import ( // BaseRecommendationRequest struct for BaseRecommendationRequest type BaseRecommendationRequest struct { - Model RecommendationModels `json:"model"` + Model RecommendationModels `json:"model" validate:"required"` // Unique identifier of the object. - ObjectID string `json:"objectID"` + ObjectID string `json:"objectID" validate:"required"` } // NewBaseRecommendationRequest instantiates a new BaseRecommendationRequest object diff --git a/clients/algoliasearch-client-go/algolia/recommend/model_base_search_response.go b/clients/algoliasearch-client-go/algolia/recommend/model_base_search_response.go index 7e433a36fe..1b4b3b2db5 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/model_base_search_response.go +++ b/clients/algoliasearch-client-go/algolia/recommend/model_base_search_response.go @@ -19,7 +19,7 @@ type BaseSearchResponse struct { // Whether the facet count is exhaustive or approximate. ExhaustiveFacetsCount *bool `json:"exhaustiveFacetsCount,omitempty"` // Indicate if the nbHits count was exhaustive or approximate. - ExhaustiveNbHits bool `json:"exhaustiveNbHits"` + ExhaustiveNbHits bool `json:"exhaustiveNbHits" validate:"required"` // Indicate if the typo-tolerance search was exhaustive or approximate (only included when typo-tolerance is enabled). ExhaustiveTypo *bool `json:"exhaustiveTypo,omitempty"` // A mapping of each facet name to the corresponding facet counts. @@ -27,7 +27,7 @@ type BaseSearchResponse struct { // Statistics for numerical facets. FacetsStats *map[string]FacetsStats `json:"facets_stats,omitempty"` // Set the number of hits per page. - HitsPerPage int32 `json:"hitsPerPage"` + HitsPerPage int32 `json:"hitsPerPage" validate:"required"` // Index name used for the query. Index *string `json:"index,omitempty"` // Index name used for the query. In the case of an A/B test, the targeted index isn't always the index used by the query. @@ -35,22 +35,22 @@ type BaseSearchResponse struct { // Used to return warnings about the query. Message *string `json:"message,omitempty"` // Number of hits that the search query matched. - NbHits int32 `json:"nbHits"` + NbHits int32 `json:"nbHits" validate:"required"` // Number of pages available for the current query. - NbPages int32 `json:"nbPages"` + NbPages int32 `json:"nbPages" validate:"required"` // The number of hits selected and sorted by the relevant sort algorithm. NbSortedHits *int32 `json:"nbSortedHits,omitempty"` // Specify the page to retrieve. - Page int32 `json:"page"` + Page int32 `json:"page" validate:"required"` // A url-encoded string of all search parameters. - Params string `json:"params"` + Params string `json:"params" validate:"required"` Redirect *BaseSearchResponseRedirect `json:"redirect,omitempty"` // The query string that will be searched, after normalization. ParsedQuery *string `json:"parsedQuery,omitempty"` // Time the server took to process the request, in milliseconds. - ProcessingTimeMS int32 `json:"processingTimeMS"` + ProcessingTimeMS int32 `json:"processingTimeMS" validate:"required"` // The text to search in the index. - Query string `json:"query"` + Query string `json:"query" validate:"required"` // A markup text indicating which parts of the original query have been removed in order to retrieve a non-empty result set. QueryAfterRemoval *string `json:"queryAfterRemoval,omitempty"` // Actual host name of the server that processed the request. diff --git a/clients/algoliasearch-client-go/algolia/recommend/model_base_trending_request.go b/clients/algoliasearch-client-go/algolia/recommend/model_base_trending_request.go index c7ebafe99a..5b4f12c52e 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/model_base_trending_request.go +++ b/clients/algoliasearch-client-go/algolia/recommend/model_base_trending_request.go @@ -8,7 +8,7 @@ import ( // BaseTrendingRequest struct for BaseTrendingRequest type BaseTrendingRequest struct { - Model TrendingModels `json:"model"` + Model TrendingModels `json:"model" validate:"required"` // The facet name to use for trending models. FacetName *string `json:"facetName,omitempty"` // The facet value to use for trending models. diff --git a/clients/algoliasearch-client-go/algolia/recommend/model_distinct.go b/clients/algoliasearch-client-go/algolia/recommend/model_distinct.go index 89168cbeb0..aff69836a0 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/model_distinct.go +++ b/clients/algoliasearch-client-go/algolia/recommend/model_distinct.go @@ -29,15 +29,14 @@ func Int32AsDistinct(v *int32) Distinct { // Unmarshal JSON data into one of the pointers in the struct func (dst *Distinct) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into Bool err = newStrictDecoder(data).Decode(&dst.Bool) - if err == nil { + if err == nil && validateStruct(dst.Bool) == nil { jsonBool, _ := json.Marshal(dst.Bool) if string(jsonBool) == "{}" { // empty struct dst.Bool = nil } else { - match++ + return nil } } else { dst.Bool = nil @@ -45,28 +44,18 @@ func (dst *Distinct) UnmarshalJSON(data []byte) error { // try to unmarshal data into Int32 err = newStrictDecoder(data).Decode(&dst.Int32) - if err == nil { + if err == nil && validateStruct(dst.Int32) == nil { jsonInt32, _ := json.Marshal(dst.Int32) if string(jsonInt32) == "{}" { // empty struct dst.Int32 = nil } else { - match++ + return nil } } else { dst.Int32 = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.Bool = nil - dst.Int32 = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(Distinct)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(Distinct)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(Distinct)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/recommend/model_facet_filters.go b/clients/algoliasearch-client-go/algolia/recommend/model_facet_filters.go index 74732327df..2b81a3a50b 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/model_facet_filters.go +++ b/clients/algoliasearch-client-go/algolia/recommend/model_facet_filters.go @@ -29,15 +29,14 @@ func StringAsFacetFilters(v *string) FacetFilters { // Unmarshal JSON data into one of the pointers in the struct func (dst *FacetFilters) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into ArrayOfMixedSearchFilters err = newStrictDecoder(data).Decode(&dst.ArrayOfMixedSearchFilters) - if err == nil { + if err == nil && validateStruct(dst.ArrayOfMixedSearchFilters) == nil { jsonArrayOfMixedSearchFilters, _ := json.Marshal(dst.ArrayOfMixedSearchFilters) if string(jsonArrayOfMixedSearchFilters) == "{}" { // empty struct dst.ArrayOfMixedSearchFilters = nil } else { - match++ + return nil } } else { dst.ArrayOfMixedSearchFilters = nil @@ -45,28 +44,18 @@ func (dst *FacetFilters) UnmarshalJSON(data []byte) error { // try to unmarshal data into String err = newStrictDecoder(data).Decode(&dst.String) - if err == nil { + if err == nil && validateStruct(dst.String) == nil { jsonString, _ := json.Marshal(dst.String) if string(jsonString) == "{}" { // empty struct dst.String = nil } else { - match++ + return nil } } else { dst.String = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.ArrayOfMixedSearchFilters = nil - dst.String = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(FacetFilters)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(FacetFilters)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(FacetFilters)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/recommend/model_get_recommendations_params.go b/clients/algoliasearch-client-go/algolia/recommend/model_get_recommendations_params.go index 8a6e9967b8..6c900b2938 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/model_get_recommendations_params.go +++ b/clients/algoliasearch-client-go/algolia/recommend/model_get_recommendations_params.go @@ -9,7 +9,7 @@ import ( // GetRecommendationsParams The `getRecommendations` parameters. type GetRecommendationsParams struct { // The `getRecommendations` requests. - Requests []RecommendationsRequest `json:"requests"` + Requests []RecommendationsRequest `json:"requests" validate:"required"` } // NewGetRecommendationsParams instantiates a new GetRecommendationsParams object diff --git a/clients/algoliasearch-client-go/algolia/recommend/model_highlight_result.go b/clients/algoliasearch-client-go/algolia/recommend/model_highlight_result.go index fd0ae5508a..7e4780d789 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/model_highlight_result.go +++ b/clients/algoliasearch-client-go/algolia/recommend/model_highlight_result.go @@ -29,15 +29,14 @@ func ArrayOfHighlightResultOptionAsHighlightResult(v *[]HighlightResultOption) H // Unmarshal JSON data into one of the pointers in the struct func (dst *HighlightResult) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into HighlightResultOption err = newStrictDecoder(data).Decode(&dst.HighlightResultOption) - if err == nil { + if err == nil && validateStruct(dst.HighlightResultOption) == nil { jsonHighlightResultOption, _ := json.Marshal(dst.HighlightResultOption) if string(jsonHighlightResultOption) == "{}" { // empty struct dst.HighlightResultOption = nil } else { - match++ + return nil } } else { dst.HighlightResultOption = nil @@ -45,28 +44,18 @@ func (dst *HighlightResult) UnmarshalJSON(data []byte) error { // try to unmarshal data into ArrayOfHighlightResultOption err = newStrictDecoder(data).Decode(&dst.ArrayOfHighlightResultOption) - if err == nil { + if err == nil && validateStruct(dst.ArrayOfHighlightResultOption) == nil { jsonArrayOfHighlightResultOption, _ := json.Marshal(dst.ArrayOfHighlightResultOption) if string(jsonArrayOfHighlightResultOption) == "{}" { // empty struct dst.ArrayOfHighlightResultOption = nil } else { - match++ + return nil } } else { dst.ArrayOfHighlightResultOption = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.HighlightResultOption = nil - dst.ArrayOfHighlightResultOption = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(HighlightResult)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(HighlightResult)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(HighlightResult)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/recommend/model_highlight_result_option.go b/clients/algoliasearch-client-go/algolia/recommend/model_highlight_result_option.go index 298be9d726..f8903d7715 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/model_highlight_result_option.go +++ b/clients/algoliasearch-client-go/algolia/recommend/model_highlight_result_option.go @@ -9,10 +9,10 @@ import ( // HighlightResultOption Show highlighted section and words matched on a query. type HighlightResultOption struct { // Markup text with occurrences highlighted. - Value string `json:"value"` - MatchLevel MatchLevel `json:"matchLevel"` + Value string `json:"value" validate:"required"` + MatchLevel MatchLevel `json:"matchLevel" validate:"required"` // List of words from the query that matched the object. - MatchedWords []string `json:"matchedWords"` + MatchedWords []string `json:"matchedWords" validate:"required"` // Whether the entire attribute value is highlighted. FullyHighlighted *bool `json:"fullyHighlighted,omitempty"` } diff --git a/clients/algoliasearch-client-go/algolia/recommend/model_ignore_plurals.go b/clients/algoliasearch-client-go/algolia/recommend/model_ignore_plurals.go index 446677055c..7b11584307 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/model_ignore_plurals.go +++ b/clients/algoliasearch-client-go/algolia/recommend/model_ignore_plurals.go @@ -29,15 +29,14 @@ func BoolAsIgnorePlurals(v *bool) IgnorePlurals { // Unmarshal JSON data into one of the pointers in the struct func (dst *IgnorePlurals) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into ArrayOfString err = newStrictDecoder(data).Decode(&dst.ArrayOfString) - if err == nil { + if err == nil && validateStruct(dst.ArrayOfString) == nil { jsonArrayOfString, _ := json.Marshal(dst.ArrayOfString) if string(jsonArrayOfString) == "{}" { // empty struct dst.ArrayOfString = nil } else { - match++ + return nil } } else { dst.ArrayOfString = nil @@ -45,28 +44,18 @@ func (dst *IgnorePlurals) UnmarshalJSON(data []byte) error { // try to unmarshal data into Bool err = newStrictDecoder(data).Decode(&dst.Bool) - if err == nil { + if err == nil && validateStruct(dst.Bool) == nil { jsonBool, _ := json.Marshal(dst.Bool) if string(jsonBool) == "{}" { // empty struct dst.Bool = nil } else { - match++ + return nil } } else { dst.Bool = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.ArrayOfString = nil - dst.Bool = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(IgnorePlurals)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(IgnorePlurals)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(IgnorePlurals)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/recommend/model_mixed_search_filters.go b/clients/algoliasearch-client-go/algolia/recommend/model_mixed_search_filters.go index 5854cfc2d1..337015e1f3 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/model_mixed_search_filters.go +++ b/clients/algoliasearch-client-go/algolia/recommend/model_mixed_search_filters.go @@ -29,15 +29,14 @@ func StringAsMixedSearchFilters(v *string) MixedSearchFilters { // Unmarshal JSON data into one of the pointers in the struct func (dst *MixedSearchFilters) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into ArrayOfString err = newStrictDecoder(data).Decode(&dst.ArrayOfString) - if err == nil { + if err == nil && validateStruct(dst.ArrayOfString) == nil { jsonArrayOfString, _ := json.Marshal(dst.ArrayOfString) if string(jsonArrayOfString) == "{}" { // empty struct dst.ArrayOfString = nil } else { - match++ + return nil } } else { dst.ArrayOfString = nil @@ -45,28 +44,18 @@ func (dst *MixedSearchFilters) UnmarshalJSON(data []byte) error { // try to unmarshal data into String err = newStrictDecoder(data).Decode(&dst.String) - if err == nil { + if err == nil && validateStruct(dst.String) == nil { jsonString, _ := json.Marshal(dst.String) if string(jsonString) == "{}" { // empty struct dst.String = nil } else { - match++ + return nil } } else { dst.String = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.ArrayOfString = nil - dst.String = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(MixedSearchFilters)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(MixedSearchFilters)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(MixedSearchFilters)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/recommend/model_numeric_filters.go b/clients/algoliasearch-client-go/algolia/recommend/model_numeric_filters.go index cb4f4ea08a..e5c85dca88 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/model_numeric_filters.go +++ b/clients/algoliasearch-client-go/algolia/recommend/model_numeric_filters.go @@ -29,15 +29,14 @@ func StringAsNumericFilters(v *string) NumericFilters { // Unmarshal JSON data into one of the pointers in the struct func (dst *NumericFilters) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into ArrayOfMixedSearchFilters err = newStrictDecoder(data).Decode(&dst.ArrayOfMixedSearchFilters) - if err == nil { + if err == nil && validateStruct(dst.ArrayOfMixedSearchFilters) == nil { jsonArrayOfMixedSearchFilters, _ := json.Marshal(dst.ArrayOfMixedSearchFilters) if string(jsonArrayOfMixedSearchFilters) == "{}" { // empty struct dst.ArrayOfMixedSearchFilters = nil } else { - match++ + return nil } } else { dst.ArrayOfMixedSearchFilters = nil @@ -45,28 +44,18 @@ func (dst *NumericFilters) UnmarshalJSON(data []byte) error { // try to unmarshal data into String err = newStrictDecoder(data).Decode(&dst.String) - if err == nil { + if err == nil && validateStruct(dst.String) == nil { jsonString, _ := json.Marshal(dst.String) if string(jsonString) == "{}" { // empty struct dst.String = nil } else { - match++ + return nil } } else { dst.String = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.ArrayOfMixedSearchFilters = nil - dst.String = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(NumericFilters)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(NumericFilters)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(NumericFilters)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/recommend/model_optional_filters.go b/clients/algoliasearch-client-go/algolia/recommend/model_optional_filters.go index 2394d682c8..9d875b0a18 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/model_optional_filters.go +++ b/clients/algoliasearch-client-go/algolia/recommend/model_optional_filters.go @@ -29,15 +29,14 @@ func StringAsOptionalFilters(v *string) OptionalFilters { // Unmarshal JSON data into one of the pointers in the struct func (dst *OptionalFilters) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into ArrayOfMixedSearchFilters err = newStrictDecoder(data).Decode(&dst.ArrayOfMixedSearchFilters) - if err == nil { + if err == nil && validateStruct(dst.ArrayOfMixedSearchFilters) == nil { jsonArrayOfMixedSearchFilters, _ := json.Marshal(dst.ArrayOfMixedSearchFilters) if string(jsonArrayOfMixedSearchFilters) == "{}" { // empty struct dst.ArrayOfMixedSearchFilters = nil } else { - match++ + return nil } } else { dst.ArrayOfMixedSearchFilters = nil @@ -45,28 +44,18 @@ func (dst *OptionalFilters) UnmarshalJSON(data []byte) error { // try to unmarshal data into String err = newStrictDecoder(data).Decode(&dst.String) - if err == nil { + if err == nil && validateStruct(dst.String) == nil { jsonString, _ := json.Marshal(dst.String) if string(jsonString) == "{}" { // empty struct dst.String = nil } else { - match++ + return nil } } else { dst.String = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.ArrayOfMixedSearchFilters = nil - dst.String = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(OptionalFilters)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(OptionalFilters)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(OptionalFilters)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/recommend/model_ranking_info.go b/clients/algoliasearch-client-go/algolia/recommend/model_ranking_info.go index 9d66acdb53..8205593b11 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/model_ranking_info.go +++ b/clients/algoliasearch-client-go/algolia/recommend/model_ranking_info.go @@ -9,27 +9,27 @@ import ( // RankingInfo struct for RankingInfo type RankingInfo struct { // This field is reserved for advanced usage. - Filters int32 `json:"filters"` + Filters int32 `json:"filters" validate:"required"` // Position of the most important matched attribute in the attributes to index list. - FirstMatchedWord int32 `json:"firstMatchedWord"` + FirstMatchedWord int32 `json:"firstMatchedWord" validate:"required"` // Distance between the geo location in the search query and the best matching geo location in the record, divided by the geo precision (in meters). - GeoDistance int32 `json:"geoDistance"` + GeoDistance int32 `json:"geoDistance" validate:"required"` // Precision used when computing the geo distance, in meters. GeoPrecision *int32 `json:"geoPrecision,omitempty"` MatchedGeoLocation *MatchedGeoLocation `json:"matchedGeoLocation,omitempty"` Personalization *Personalization `json:"personalization,omitempty"` // Number of exactly matched words. - NbExactWords int32 `json:"nbExactWords"` + NbExactWords int32 `json:"nbExactWords" validate:"required"` // Number of typos encountered when matching the record. - NbTypos int32 `json:"nbTypos"` + NbTypos int32 `json:"nbTypos" validate:"required"` // Present and set to true if a Rule promoted the hit. - Promoted bool `json:"promoted"` + Promoted bool `json:"promoted" validate:"required"` // When the query contains more than one word, the sum of the distances between matched words (in meters). ProximityDistance *int32 `json:"proximityDistance,omitempty"` // Custom ranking for the object, expressed as a single integer value. - UserScore int32 `json:"userScore"` + UserScore int32 `json:"userScore" validate:"required"` // Number of matched words, including prefixes and typos. - Words int32 `json:"words"` + Words int32 `json:"words" validate:"required"` // Wether the record are promoted by the re-ranking strategy. PromotedByReRanking *bool `json:"promotedByReRanking,omitempty"` } diff --git a/clients/algoliasearch-client-go/algolia/recommend/model_re_ranking_apply_filter.go b/clients/algoliasearch-client-go/algolia/recommend/model_re_ranking_apply_filter.go index 62637e039e..ae36ff4d05 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/model_re_ranking_apply_filter.go +++ b/clients/algoliasearch-client-go/algolia/recommend/model_re_ranking_apply_filter.go @@ -34,15 +34,14 @@ func (dst *ReRankingApplyFilter) UnmarshalJSON(data []byte) error { return nil } - match := 0 // try to unmarshal data into ArrayOfMixedSearchFilters err = newStrictDecoder(data).Decode(&dst.ArrayOfMixedSearchFilters) - if err == nil { + if err == nil && validateStruct(dst.ArrayOfMixedSearchFilters) == nil { jsonArrayOfMixedSearchFilters, _ := json.Marshal(dst.ArrayOfMixedSearchFilters) if string(jsonArrayOfMixedSearchFilters) == "{}" { // empty struct dst.ArrayOfMixedSearchFilters = nil } else { - match++ + return nil } } else { dst.ArrayOfMixedSearchFilters = nil @@ -50,28 +49,18 @@ func (dst *ReRankingApplyFilter) UnmarshalJSON(data []byte) error { // try to unmarshal data into String err = newStrictDecoder(data).Decode(&dst.String) - if err == nil { + if err == nil && validateStruct(dst.String) == nil { jsonString, _ := json.Marshal(dst.String) if string(jsonString) == "{}" { // empty struct dst.String = nil } else { - match++ + return nil } } else { dst.String = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.ArrayOfMixedSearchFilters = nil - dst.String = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(ReRankingApplyFilter)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(ReRankingApplyFilter)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(ReRankingApplyFilter)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/recommend/model_recommend_hit.go b/clients/algoliasearch-client-go/algolia/recommend/model_recommend_hit.go index f946a2c6da..44dd38b339 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/model_recommend_hit.go +++ b/clients/algoliasearch-client-go/algolia/recommend/model_recommend_hit.go @@ -9,7 +9,7 @@ import ( // RecommendHit A Recommend hit. type RecommendHit struct { // Unique identifier of the object. - ObjectID string `json:"objectID"` + ObjectID string `json:"objectID" validate:"required"` // Show highlighted section and words matched on a query. HighlightResult *map[string]HighlightResult `json:"_highlightResult,omitempty"` // Snippeted attributes show parts of the matched attributes. Only returned when attributesToSnippet is non-empty. @@ -17,7 +17,7 @@ type RecommendHit struct { RankingInfo *RankingInfo `json:"_rankingInfo,omitempty"` DistinctSeqID *int32 `json:"_distinctSeqID,omitempty"` // The recommendation score. - Score float64 `json:"_score"` + Score float64 `json:"_score" validate:"required"` AdditionalProperties map[string]any } diff --git a/clients/algoliasearch-client-go/algolia/recommend/model_recommend_hits.go b/clients/algoliasearch-client-go/algolia/recommend/model_recommend_hits.go index ec567e71d6..af9830c6ee 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/model_recommend_hits.go +++ b/clients/algoliasearch-client-go/algolia/recommend/model_recommend_hits.go @@ -8,7 +8,7 @@ import ( // RecommendHits struct for RecommendHits type RecommendHits struct { - Hits []RecommendHit `json:"hits"` + Hits []RecommendHit `json:"hits" validate:"required"` } // NewRecommendHits instantiates a new RecommendHits object diff --git a/clients/algoliasearch-client-go/algolia/recommend/model_recommendation_request.go b/clients/algoliasearch-client-go/algolia/recommend/model_recommendation_request.go index 86562e224b..a2a326aa53 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/model_recommendation_request.go +++ b/clients/algoliasearch-client-go/algolia/recommend/model_recommendation_request.go @@ -8,13 +8,13 @@ import ( // RecommendationRequest struct for RecommendationRequest type RecommendationRequest struct { - Model RecommendationModels `json:"model"` + Model RecommendationModels `json:"model" validate:"required"` // Unique identifier of the object. - ObjectID string `json:"objectID"` + ObjectID string `json:"objectID" validate:"required"` // The Algolia index name. - IndexName string `json:"indexName"` + IndexName string `json:"indexName" validate:"required"` // The threshold to use when filtering recommendations by their score. - Threshold int32 `json:"threshold"` + Threshold int32 `json:"threshold" validate:"required"` // The max number of recommendations to retrieve. If it's set to 0, all the recommendations of the objectID may be returned. MaxRecommendations *int32 `json:"maxRecommendations,omitempty"` QueryParameters *SearchParamsObject `json:"queryParameters,omitempty"` diff --git a/clients/algoliasearch-client-go/algolia/recommend/model_recommendations_request.go b/clients/algoliasearch-client-go/algolia/recommend/model_recommendations_request.go index 20afc0d125..da0f3d5fe6 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/model_recommendations_request.go +++ b/clients/algoliasearch-client-go/algolia/recommend/model_recommendations_request.go @@ -29,15 +29,14 @@ func TrendingRequestAsRecommendationsRequest(v *TrendingRequest) Recommendations // Unmarshal JSON data into one of the pointers in the struct func (dst *RecommendationsRequest) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into RecommendationRequest err = newStrictDecoder(data).Decode(&dst.RecommendationRequest) - if err == nil { + if err == nil && validateStruct(dst.RecommendationRequest) == nil { jsonRecommendationRequest, _ := json.Marshal(dst.RecommendationRequest) if string(jsonRecommendationRequest) == "{}" { // empty struct dst.RecommendationRequest = nil } else { - match++ + return nil } } else { dst.RecommendationRequest = nil @@ -45,28 +44,18 @@ func (dst *RecommendationsRequest) UnmarshalJSON(data []byte) error { // try to unmarshal data into TrendingRequest err = newStrictDecoder(data).Decode(&dst.TrendingRequest) - if err == nil { + if err == nil && validateStruct(dst.TrendingRequest) == nil { jsonTrendingRequest, _ := json.Marshal(dst.TrendingRequest) if string(jsonTrendingRequest) == "{}" { // empty struct dst.TrendingRequest = nil } else { - match++ + return nil } } else { dst.TrendingRequest = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.RecommendationRequest = nil - dst.TrendingRequest = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(RecommendationsRequest)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(RecommendationsRequest)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(RecommendationsRequest)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/recommend/model_recommendations_response.go b/clients/algoliasearch-client-go/algolia/recommend/model_recommendations_response.go index 8e8450ebd2..f6d90489ac 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/model_recommendations_response.go +++ b/clients/algoliasearch-client-go/algolia/recommend/model_recommendations_response.go @@ -19,7 +19,7 @@ type RecommendationsResponse struct { // Whether the facet count is exhaustive or approximate. ExhaustiveFacetsCount *bool `json:"exhaustiveFacetsCount,omitempty"` // Indicate if the nbHits count was exhaustive or approximate. - ExhaustiveNbHits bool `json:"exhaustiveNbHits"` + ExhaustiveNbHits bool `json:"exhaustiveNbHits" validate:"required"` // Indicate if the typo-tolerance search was exhaustive or approximate (only included when typo-tolerance is enabled). ExhaustiveTypo *bool `json:"exhaustiveTypo,omitempty"` // A mapping of each facet name to the corresponding facet counts. @@ -27,7 +27,7 @@ type RecommendationsResponse struct { // Statistics for numerical facets. FacetsStats *map[string]FacetsStats `json:"facets_stats,omitempty"` // Set the number of hits per page. - HitsPerPage int32 `json:"hitsPerPage"` + HitsPerPage int32 `json:"hitsPerPage" validate:"required"` // Index name used for the query. Index *string `json:"index,omitempty"` // Index name used for the query. In the case of an A/B test, the targeted index isn't always the index used by the query. @@ -35,22 +35,22 @@ type RecommendationsResponse struct { // Used to return warnings about the query. Message *string `json:"message,omitempty"` // Number of hits that the search query matched. - NbHits int32 `json:"nbHits"` + NbHits int32 `json:"nbHits" validate:"required"` // Number of pages available for the current query. - NbPages int32 `json:"nbPages"` + NbPages int32 `json:"nbPages" validate:"required"` // The number of hits selected and sorted by the relevant sort algorithm. NbSortedHits *int32 `json:"nbSortedHits,omitempty"` // Specify the page to retrieve. - Page int32 `json:"page"` + Page int32 `json:"page" validate:"required"` // A url-encoded string of all search parameters. - Params string `json:"params"` + Params string `json:"params" validate:"required"` Redirect *BaseSearchResponseRedirect `json:"redirect,omitempty"` // The query string that will be searched, after normalization. ParsedQuery *string `json:"parsedQuery,omitempty"` // Time the server took to process the request, in milliseconds. - ProcessingTimeMS int32 `json:"processingTimeMS"` + ProcessingTimeMS int32 `json:"processingTimeMS" validate:"required"` // The text to search in the index. - Query string `json:"query"` + Query string `json:"query" validate:"required"` // A markup text indicating which parts of the original query have been removed in order to retrieve a non-empty result set. QueryAfterRemoval *string `json:"queryAfterRemoval,omitempty"` // Actual host name of the server that processed the request. @@ -58,7 +58,7 @@ type RecommendationsResponse struct { // Lets you store custom data in your indices. UserData map[string]interface{} `json:"userData,omitempty"` RenderingContent *RenderingContent `json:"renderingContent,omitempty"` - Hits []RecommendHit `json:"hits"` + Hits []RecommendHit `json:"hits" validate:"required"` } type RecommendationsResponseOption func(f *RecommendationsResponse) diff --git a/clients/algoliasearch-client-go/algolia/recommend/model_redirect_rule_index_metadata.go b/clients/algoliasearch-client-go/algolia/recommend/model_redirect_rule_index_metadata.go index 9f9221e1ff..2bd7861a36 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/model_redirect_rule_index_metadata.go +++ b/clients/algoliasearch-client-go/algolia/recommend/model_redirect_rule_index_metadata.go @@ -9,14 +9,14 @@ import ( // RedirectRuleIndexMetadata struct for RedirectRuleIndexMetadata type RedirectRuleIndexMetadata struct { // Source index for the redirect rule. - Source string `json:"source"` + Source string `json:"source" validate:"required"` // Destination index for the redirect rule. - Dest string `json:"dest"` + Dest string `json:"dest" validate:"required"` // Reason for the redirect rule. - Reason string `json:"reason"` + Reason string `json:"reason" validate:"required"` // Status for the redirect rule. - Succeed bool `json:"succeed"` - Data RedirectRuleIndexMetadataData `json:"data"` + Succeed bool `json:"succeed" validate:"required"` + Data RedirectRuleIndexMetadataData `json:"data" validate:"required"` } // NewRedirectRuleIndexMetadata instantiates a new RedirectRuleIndexMetadata object diff --git a/clients/algoliasearch-client-go/algolia/recommend/model_redirect_rule_index_metadata_data.go b/clients/algoliasearch-client-go/algolia/recommend/model_redirect_rule_index_metadata_data.go index 22ad1f5736..cc0fee0483 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/model_redirect_rule_index_metadata_data.go +++ b/clients/algoliasearch-client-go/algolia/recommend/model_redirect_rule_index_metadata_data.go @@ -8,7 +8,7 @@ import ( // RedirectRuleIndexMetadataData Data for the redirect rule. type RedirectRuleIndexMetadataData struct { - RuleObjectID string `json:"ruleObjectID"` + RuleObjectID string `json:"ruleObjectID" validate:"required"` } // NewRedirectRuleIndexMetadataData instantiates a new RedirectRuleIndexMetadataData object diff --git a/clients/algoliasearch-client-go/algolia/recommend/model_remove_stop_words.go b/clients/algoliasearch-client-go/algolia/recommend/model_remove_stop_words.go index ee0dadec3c..0e3b42b0eb 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/model_remove_stop_words.go +++ b/clients/algoliasearch-client-go/algolia/recommend/model_remove_stop_words.go @@ -29,15 +29,14 @@ func BoolAsRemoveStopWords(v *bool) RemoveStopWords { // Unmarshal JSON data into one of the pointers in the struct func (dst *RemoveStopWords) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into ArrayOfString err = newStrictDecoder(data).Decode(&dst.ArrayOfString) - if err == nil { + if err == nil && validateStruct(dst.ArrayOfString) == nil { jsonArrayOfString, _ := json.Marshal(dst.ArrayOfString) if string(jsonArrayOfString) == "{}" { // empty struct dst.ArrayOfString = nil } else { - match++ + return nil } } else { dst.ArrayOfString = nil @@ -45,28 +44,18 @@ func (dst *RemoveStopWords) UnmarshalJSON(data []byte) error { // try to unmarshal data into Bool err = newStrictDecoder(data).Decode(&dst.Bool) - if err == nil { + if err == nil && validateStruct(dst.Bool) == nil { jsonBool, _ := json.Marshal(dst.Bool) if string(jsonBool) == "{}" { // empty struct dst.Bool = nil } else { - match++ + return nil } } else { dst.Bool = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.ArrayOfString = nil - dst.Bool = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(RemoveStopWords)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(RemoveStopWords)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(RemoveStopWords)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/recommend/model_snippet_result.go b/clients/algoliasearch-client-go/algolia/recommend/model_snippet_result.go index 12cdda93b9..4fb49fb30c 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/model_snippet_result.go +++ b/clients/algoliasearch-client-go/algolia/recommend/model_snippet_result.go @@ -29,15 +29,14 @@ func ArrayOfSnippetResultOptionAsSnippetResult(v *[]SnippetResultOption) Snippet // Unmarshal JSON data into one of the pointers in the struct func (dst *SnippetResult) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into SnippetResultOption err = newStrictDecoder(data).Decode(&dst.SnippetResultOption) - if err == nil { + if err == nil && validateStruct(dst.SnippetResultOption) == nil { jsonSnippetResultOption, _ := json.Marshal(dst.SnippetResultOption) if string(jsonSnippetResultOption) == "{}" { // empty struct dst.SnippetResultOption = nil } else { - match++ + return nil } } else { dst.SnippetResultOption = nil @@ -45,28 +44,18 @@ func (dst *SnippetResult) UnmarshalJSON(data []byte) error { // try to unmarshal data into ArrayOfSnippetResultOption err = newStrictDecoder(data).Decode(&dst.ArrayOfSnippetResultOption) - if err == nil { + if err == nil && validateStruct(dst.ArrayOfSnippetResultOption) == nil { jsonArrayOfSnippetResultOption, _ := json.Marshal(dst.ArrayOfSnippetResultOption) if string(jsonArrayOfSnippetResultOption) == "{}" { // empty struct dst.ArrayOfSnippetResultOption = nil } else { - match++ + return nil } } else { dst.ArrayOfSnippetResultOption = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.SnippetResultOption = nil - dst.ArrayOfSnippetResultOption = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(SnippetResult)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(SnippetResult)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(SnippetResult)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/recommend/model_snippet_result_option.go b/clients/algoliasearch-client-go/algolia/recommend/model_snippet_result_option.go index 92fa9da2f0..0a5f573787 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/model_snippet_result_option.go +++ b/clients/algoliasearch-client-go/algolia/recommend/model_snippet_result_option.go @@ -9,8 +9,8 @@ import ( // SnippetResultOption Snippeted attributes show parts of the matched attributes. Only returned when attributesToSnippet is non-empty. type SnippetResultOption struct { // Markup text with occurrences highlighted. - Value string `json:"value"` - MatchLevel MatchLevel `json:"matchLevel"` + Value string `json:"value" validate:"required"` + MatchLevel MatchLevel `json:"matchLevel" validate:"required"` } // NewSnippetResultOption instantiates a new SnippetResultOption object diff --git a/clients/algoliasearch-client-go/algolia/recommend/model_tag_filters.go b/clients/algoliasearch-client-go/algolia/recommend/model_tag_filters.go index 932bfd8c46..ac587431e9 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/model_tag_filters.go +++ b/clients/algoliasearch-client-go/algolia/recommend/model_tag_filters.go @@ -29,15 +29,14 @@ func StringAsTagFilters(v *string) TagFilters { // Unmarshal JSON data into one of the pointers in the struct func (dst *TagFilters) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into ArrayOfMixedSearchFilters err = newStrictDecoder(data).Decode(&dst.ArrayOfMixedSearchFilters) - if err == nil { + if err == nil && validateStruct(dst.ArrayOfMixedSearchFilters) == nil { jsonArrayOfMixedSearchFilters, _ := json.Marshal(dst.ArrayOfMixedSearchFilters) if string(jsonArrayOfMixedSearchFilters) == "{}" { // empty struct dst.ArrayOfMixedSearchFilters = nil } else { - match++ + return nil } } else { dst.ArrayOfMixedSearchFilters = nil @@ -45,28 +44,18 @@ func (dst *TagFilters) UnmarshalJSON(data []byte) error { // try to unmarshal data into String err = newStrictDecoder(data).Decode(&dst.String) - if err == nil { + if err == nil && validateStruct(dst.String) == nil { jsonString, _ := json.Marshal(dst.String) if string(jsonString) == "{}" { // empty struct dst.String = nil } else { - match++ + return nil } } else { dst.String = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.ArrayOfMixedSearchFilters = nil - dst.String = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(TagFilters)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(TagFilters)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(TagFilters)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/recommend/model_trending_request.go b/clients/algoliasearch-client-go/algolia/recommend/model_trending_request.go index b6bd0b999b..c236bdd2d7 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/model_trending_request.go +++ b/clients/algoliasearch-client-go/algolia/recommend/model_trending_request.go @@ -8,15 +8,15 @@ import ( // TrendingRequest struct for TrendingRequest type TrendingRequest struct { - Model TrendingModels `json:"model"` + Model TrendingModels `json:"model" validate:"required"` // The facet name to use for trending models. FacetName *string `json:"facetName,omitempty"` // The facet value to use for trending models. FacetValue *string `json:"facetValue,omitempty"` // The Algolia index name. - IndexName string `json:"indexName"` + IndexName string `json:"indexName" validate:"required"` // The threshold to use when filtering recommendations by their score. - Threshold int32 `json:"threshold"` + Threshold int32 `json:"threshold" validate:"required"` // The max number of recommendations to retrieve. If it's set to 0, all the recommendations of the objectID may be returned. MaxRecommendations *int32 `json:"maxRecommendations,omitempty"` QueryParameters *SearchParamsObject `json:"queryParameters,omitempty"` diff --git a/clients/algoliasearch-client-go/algolia/recommend/model_typo_tolerance.go b/clients/algoliasearch-client-go/algolia/recommend/model_typo_tolerance.go index 9fc384c0ab..d90c173d25 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/model_typo_tolerance.go +++ b/clients/algoliasearch-client-go/algolia/recommend/model_typo_tolerance.go @@ -29,15 +29,14 @@ func BoolAsTypoTolerance(v *bool) TypoTolerance { // Unmarshal JSON data into one of the pointers in the struct func (dst *TypoTolerance) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into TypoToleranceEnum err = newStrictDecoder(data).Decode(&dst.TypoToleranceEnum) - if err == nil { + if err == nil && validateStruct(dst.TypoToleranceEnum) == nil { jsonTypoToleranceEnum, _ := json.Marshal(dst.TypoToleranceEnum) if string(jsonTypoToleranceEnum) == "{}" { // empty struct dst.TypoToleranceEnum = nil } else { - match++ + return nil } } else { dst.TypoToleranceEnum = nil @@ -45,28 +44,18 @@ func (dst *TypoTolerance) UnmarshalJSON(data []byte) error { // try to unmarshal data into Bool err = newStrictDecoder(data).Decode(&dst.Bool) - if err == nil { + if err == nil && validateStruct(dst.Bool) == nil { jsonBool, _ := json.Marshal(dst.Bool) if string(jsonBool) == "{}" { // empty struct dst.Bool = nil } else { - match++ + return nil } } else { dst.Bool = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.TypoToleranceEnum = nil - dst.Bool = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(TypoTolerance)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(TypoTolerance)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(TypoTolerance)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/recommend/utils.go b/clients/algoliasearch-client-go/algolia/recommend/utils.go index 926fa78f3a..f072a429ef 100644 --- a/clients/algoliasearch-client-go/algolia/recommend/utils.go +++ b/clients/algoliasearch-client-go/algolia/recommend/utils.go @@ -336,6 +336,8 @@ func isNilorEmpty(i any) bool { switch reflect.TypeOf(i).Kind() { case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.UnsafePointer, reflect.Interface, reflect.Slice: return reflect.ValueOf(i).IsNil() + case reflect.Bool: + return false default: return reflect.ValueOf(i).IsZero() } diff --git a/clients/algoliasearch-client-go/algolia/search/api_search.go b/clients/algoliasearch-client-go/algolia/search/api_search.go index 736b5302c5..82344588b5 100644 --- a/clients/algoliasearch-client-go/algolia/search/api_search.go +++ b/clients/algoliasearch-client-go/algolia/search/api_search.go @@ -4,6 +4,7 @@ package search import ( "bytes" "context" + "encoding/json" "io" "net/http" "net/url" @@ -29,7 +30,7 @@ func QueryParamOption(name string, val any) Option { func HeaderParamOption(name string, val any) Option { return Option{ optionType: "header", - name: "itemsPerPage", + name: name, value: parameterToString(val), } } @@ -38,8 +39,32 @@ type ApiAddApiKeyRequest struct { apiKey *ApiKey } -func (r ApiAddApiKeyRequest) WithApiKey(apiKey ApiKey) ApiAddApiKeyRequest { - r.apiKey = &apiKey +func (r *ApiAddApiKeyRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["apiKey"]; ok { //apiKey + err = json.Unmarshal(v, &r.apiKey) + if err != nil { + err = json.Unmarshal(b, &r.apiKey) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.apiKey) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiAddApiKeyRequest) WithApiKey(apiKey *ApiKey) ApiAddApiKeyRequest { + r.apiKey = apiKey return r } @@ -67,7 +92,7 @@ func (c *APIClient) AddApiKey(r ApiAddApiKeyRequest, opts ...Option) (*AddApiKey for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -152,6 +177,48 @@ type ApiAddOrUpdateObjectRequest struct { body map[string]interface{} } +func (r *ApiAddOrUpdateObjectRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + if v, ok := req["objectID"]; ok { //objectID + err = json.Unmarshal(v, &r.objectID) + if err != nil { + err = json.Unmarshal(b, &r.objectID) + if err != nil { + return err + } + } + } + if v, ok := req["body"]; ok { //body + err = json.Unmarshal(v, &r.body) + if err != nil { + err = json.Unmarshal(b, &r.body) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.body) + if err != nil { + return err + } + } + + return nil +} + // The Algolia object. func (r ApiAddOrUpdateObjectRequest) WithBody(body map[string]interface{}) ApiAddOrUpdateObjectRequest { r.body = body @@ -184,7 +251,7 @@ func (c *APIClient) AddOrUpdateObject(r ApiAddOrUpdateObjectRequest, opts ...Opt for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -267,9 +334,33 @@ type ApiAppendSourceRequest struct { source *Source } +func (r *ApiAppendSourceRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["source"]; ok { //source + err = json.Unmarshal(v, &r.source) + if err != nil { + err = json.Unmarshal(b, &r.source) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.source) + if err != nil { + return err + } + } + + return nil +} + // The source to add. -func (r ApiAppendSourceRequest) WithSource(source Source) ApiAppendSourceRequest { - r.source = &source +func (r ApiAppendSourceRequest) WithSource(source *Source) ApiAppendSourceRequest { + r.source = source return r } @@ -297,7 +388,7 @@ func (c *APIClient) AppendSource(r ApiAppendSourceRequest, opts ...Option) (*Cre for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -381,14 +472,47 @@ type ApiAssignUserIdRequest struct { assignUserIdParams *AssignUserIdParams } +func (r *ApiAssignUserIdRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["xAlgoliaUserID"]; ok { //xAlgoliaUserID + err = json.Unmarshal(v, &r.xAlgoliaUserID) + if err != nil { + err = json.Unmarshal(b, &r.xAlgoliaUserID) + if err != nil { + return err + } + } + } + if v, ok := req["assignUserIdParams"]; ok { //assignUserIdParams + err = json.Unmarshal(v, &r.assignUserIdParams) + if err != nil { + err = json.Unmarshal(b, &r.assignUserIdParams) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.assignUserIdParams) + if err != nil { + return err + } + } + + return nil +} + // userID to assign. func (r ApiAssignUserIdRequest) WithXAlgoliaUserID(xAlgoliaUserID string) ApiAssignUserIdRequest { r.xAlgoliaUserID = xAlgoliaUserID return r } -func (r ApiAssignUserIdRequest) WithAssignUserIdParams(assignUserIdParams AssignUserIdParams) ApiAssignUserIdRequest { - r.assignUserIdParams = &assignUserIdParams +func (r ApiAssignUserIdRequest) WithAssignUserIdParams(assignUserIdParams *AssignUserIdParams) ApiAssignUserIdRequest { + r.assignUserIdParams = assignUserIdParams return r } @@ -421,7 +545,7 @@ func (c *APIClient) AssignUserId(r ApiAssignUserIdRequest, opts ...Option) (*Cre for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -505,8 +629,41 @@ type ApiBatchRequest struct { batchWriteParams *BatchWriteParams } -func (r ApiBatchRequest) WithBatchWriteParams(batchWriteParams BatchWriteParams) ApiBatchRequest { - r.batchWriteParams = &batchWriteParams +func (r *ApiBatchRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + if v, ok := req["batchWriteParams"]; ok { //batchWriteParams + err = json.Unmarshal(v, &r.batchWriteParams) + if err != nil { + err = json.Unmarshal(b, &r.batchWriteParams) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.batchWriteParams) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiBatchRequest) WithBatchWriteParams(batchWriteParams *BatchWriteParams) ApiBatchRequest { + r.batchWriteParams = batchWriteParams return r } @@ -537,7 +694,7 @@ func (c *APIClient) Batch(r ApiBatchRequest, opts ...Option) (*BatchResponse, er for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -621,14 +778,47 @@ type ApiBatchAssignUserIdsRequest struct { batchAssignUserIdsParams *BatchAssignUserIdsParams } +func (r *ApiBatchAssignUserIdsRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["xAlgoliaUserID"]; ok { //xAlgoliaUserID + err = json.Unmarshal(v, &r.xAlgoliaUserID) + if err != nil { + err = json.Unmarshal(b, &r.xAlgoliaUserID) + if err != nil { + return err + } + } + } + if v, ok := req["batchAssignUserIdsParams"]; ok { //batchAssignUserIdsParams + err = json.Unmarshal(v, &r.batchAssignUserIdsParams) + if err != nil { + err = json.Unmarshal(b, &r.batchAssignUserIdsParams) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.batchAssignUserIdsParams) + if err != nil { + return err + } + } + + return nil +} + // userID to assign. func (r ApiBatchAssignUserIdsRequest) WithXAlgoliaUserID(xAlgoliaUserID string) ApiBatchAssignUserIdsRequest { r.xAlgoliaUserID = xAlgoliaUserID return r } -func (r ApiBatchAssignUserIdsRequest) WithBatchAssignUserIdsParams(batchAssignUserIdsParams BatchAssignUserIdsParams) ApiBatchAssignUserIdsRequest { - r.batchAssignUserIdsParams = &batchAssignUserIdsParams +func (r ApiBatchAssignUserIdsRequest) WithBatchAssignUserIdsParams(batchAssignUserIdsParams *BatchAssignUserIdsParams) ApiBatchAssignUserIdsRequest { + r.batchAssignUserIdsParams = batchAssignUserIdsParams return r } @@ -661,7 +851,7 @@ func (c *APIClient) BatchAssignUserIds(r ApiBatchAssignUserIdsRequest, opts ...O for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -745,8 +935,41 @@ type ApiBatchDictionaryEntriesRequest struct { batchDictionaryEntriesParams *BatchDictionaryEntriesParams } -func (r ApiBatchDictionaryEntriesRequest) WithBatchDictionaryEntriesParams(batchDictionaryEntriesParams BatchDictionaryEntriesParams) ApiBatchDictionaryEntriesRequest { - r.batchDictionaryEntriesParams = &batchDictionaryEntriesParams +func (r *ApiBatchDictionaryEntriesRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["dictionaryName"]; ok { //dictionaryName + err = json.Unmarshal(v, &r.dictionaryName) + if err != nil { + err = json.Unmarshal(b, &r.dictionaryName) + if err != nil { + return err + } + } + } + if v, ok := req["batchDictionaryEntriesParams"]; ok { //batchDictionaryEntriesParams + err = json.Unmarshal(v, &r.batchDictionaryEntriesParams) + if err != nil { + err = json.Unmarshal(b, &r.batchDictionaryEntriesParams) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.batchDictionaryEntriesParams) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiBatchDictionaryEntriesRequest) WithBatchDictionaryEntriesParams(batchDictionaryEntriesParams *BatchDictionaryEntriesParams) ApiBatchDictionaryEntriesRequest { + r.batchDictionaryEntriesParams = batchDictionaryEntriesParams return r } @@ -777,7 +1000,7 @@ func (c *APIClient) BatchDictionaryEntries(r ApiBatchDictionaryEntriesRequest, o for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -861,8 +1084,36 @@ type ApiBrowseRequest struct { browseParams *BrowseParams } -func (r ApiBrowseRequest) WithBrowseParams(browseParams BrowseParams) ApiBrowseRequest { - r.browseParams = &browseParams +func (r *ApiBrowseRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + if v, ok := req["browseParams"]; ok { //browseParams + err = json.Unmarshal(v, &r.browseParams) + if err != nil { + err = json.Unmarshal(b, &r.browseParams) + if err != nil { + return err + } + } + } + + return nil +} + +func (r ApiBrowseRequest) WithBrowseParams(browseParams *BrowseParams) ApiBrowseRequest { + r.browseParams = browseParams return r } @@ -890,14 +1141,18 @@ func (c *APIClient) Browse(r ApiBrowseRequest, opts ...Option) (*BrowseResponse, for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } } // body params - postBody = r.browseParams + if isNilorEmpty(r.browseParams) { + postBody = "{}" + } else { + postBody = r.browseParams + } req, err := c.prepareRequest(context.Background(), requestPath, http.MethodPost, postBody, headers, queryParams) if err != nil { return returnValue, err @@ -974,6 +1229,34 @@ type ApiClearAllSynonymsRequest struct { forwardToReplicas bool } +func (r *ApiClearAllSynonymsRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + if v, ok := req["forwardToReplicas"]; ok { //forwardToReplicas + err = json.Unmarshal(v, &r.forwardToReplicas) + if err != nil { + err = json.Unmarshal(b, &r.forwardToReplicas) + if err != nil { + return err + } + } + } + + return nil +} + // When true, changes are also propagated to replicas of the given indexName. func (r ApiClearAllSynonymsRequest) WithForwardToReplicas(forwardToReplicas bool) ApiClearAllSynonymsRequest { r.forwardToReplicas = forwardToReplicas @@ -1001,14 +1284,14 @@ func (c *APIClient) ClearAllSynonyms(r ApiClearAllSynonymsRequest, opts ...Optio queryParams := url.Values{} if !isNilorEmpty(r.forwardToReplicas) { - queryParams.Add("forwardToReplicas", parameterToString(r.forwardToReplicas)) + queryParams.Set("forwardToReplicas", parameterToString(r.forwardToReplicas)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1089,6 +1372,25 @@ type ApiClearObjectsRequest struct { indexName string } +func (r *ApiClearObjectsRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiClearObjectsRequest func (c *APIClient) NewApiClearObjectsRequest(indexName string) ApiClearObjectsRequest { return ApiClearObjectsRequest{ @@ -1113,7 +1415,7 @@ func (c *APIClient) ClearObjects(r ApiClearObjectsRequest, opts ...Option) (*Upd for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1195,6 +1497,34 @@ type ApiClearRulesRequest struct { forwardToReplicas bool } +func (r *ApiClearRulesRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + if v, ok := req["forwardToReplicas"]; ok { //forwardToReplicas + err = json.Unmarshal(v, &r.forwardToReplicas) + if err != nil { + err = json.Unmarshal(b, &r.forwardToReplicas) + if err != nil { + return err + } + } + } + + return nil +} + // When true, changes are also propagated to replicas of the given indexName. func (r ApiClearRulesRequest) WithForwardToReplicas(forwardToReplicas bool) ApiClearRulesRequest { r.forwardToReplicas = forwardToReplicas @@ -1222,14 +1552,14 @@ func (c *APIClient) ClearRules(r ApiClearRulesRequest, opts ...Option) (*Updated queryParams := url.Values{} if !isNilorEmpty(r.forwardToReplicas) { - queryParams.Add("forwardToReplicas", parameterToString(r.forwardToReplicas)) + queryParams.Set("forwardToReplicas", parameterToString(r.forwardToReplicas)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1311,6 +1641,34 @@ type ApiDelRequest struct { parameters map[string]interface{} } +func (r *ApiDelRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + + return nil +} + // Query parameters to be applied to the current query. func (r ApiDelRequest) WithParameters(parameters map[string]interface{}) ApiDelRequest { r.parameters = parameters @@ -1338,14 +1696,16 @@ func (c *APIClient) Del(r ApiDelRequest, opts ...Option) (map[string]interface{} queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1426,6 +1786,25 @@ type ApiDeleteApiKeyRequest struct { key string } +func (r *ApiDeleteApiKeyRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["key"]; ok { //key + err = json.Unmarshal(v, &r.key) + if err != nil { + err = json.Unmarshal(b, &r.key) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiDeleteApiKeyRequest func (c *APIClient) NewApiDeleteApiKeyRequest(key string) ApiDeleteApiKeyRequest { return ApiDeleteApiKeyRequest{ @@ -1450,7 +1829,7 @@ func (c *APIClient) DeleteApiKey(r ApiDeleteApiKeyRequest, opts ...Option) (*Del for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1532,8 +1911,41 @@ type ApiDeleteByRequest struct { deleteByParams *DeleteByParams } -func (r ApiDeleteByRequest) WithDeleteByParams(deleteByParams DeleteByParams) ApiDeleteByRequest { - r.deleteByParams = &deleteByParams +func (r *ApiDeleteByRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + if v, ok := req["deleteByParams"]; ok { //deleteByParams + err = json.Unmarshal(v, &r.deleteByParams) + if err != nil { + err = json.Unmarshal(b, &r.deleteByParams) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.deleteByParams) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiDeleteByRequest) WithDeleteByParams(deleteByParams *DeleteByParams) ApiDeleteByRequest { + r.deleteByParams = deleteByParams return r } @@ -1564,7 +1976,7 @@ func (c *APIClient) DeleteBy(r ApiDeleteByRequest, opts ...Option) (*DeletedAtRe for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1647,6 +2059,25 @@ type ApiDeleteIndexRequest struct { indexName string } +func (r *ApiDeleteIndexRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiDeleteIndexRequest func (c *APIClient) NewApiDeleteIndexRequest(indexName string) ApiDeleteIndexRequest { return ApiDeleteIndexRequest{ @@ -1671,7 +2102,7 @@ func (c *APIClient) DeleteIndex(r ApiDeleteIndexRequest, opts ...Option) (*Delet for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1753,6 +2184,34 @@ type ApiDeleteObjectRequest struct { objectID string } +func (r *ApiDeleteObjectRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + if v, ok := req["objectID"]; ok { //objectID + err = json.Unmarshal(v, &r.objectID) + if err != nil { + err = json.Unmarshal(b, &r.objectID) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiDeleteObjectRequest func (c *APIClient) NewApiDeleteObjectRequest(indexName string, objectID string) ApiDeleteObjectRequest { return ApiDeleteObjectRequest{ @@ -1779,7 +2238,7 @@ func (c *APIClient) DeleteObject(r ApiDeleteObjectRequest, opts ...Option) (*Del for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1862,6 +2321,43 @@ type ApiDeleteRuleRequest struct { forwardToReplicas bool } +func (r *ApiDeleteRuleRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + if v, ok := req["objectID"]; ok { //objectID + err = json.Unmarshal(v, &r.objectID) + if err != nil { + err = json.Unmarshal(b, &r.objectID) + if err != nil { + return err + } + } + } + if v, ok := req["forwardToReplicas"]; ok { //forwardToReplicas + err = json.Unmarshal(v, &r.forwardToReplicas) + if err != nil { + err = json.Unmarshal(b, &r.forwardToReplicas) + if err != nil { + return err + } + } + } + + return nil +} + // When true, changes are also propagated to replicas of the given indexName. func (r ApiDeleteRuleRequest) WithForwardToReplicas(forwardToReplicas bool) ApiDeleteRuleRequest { r.forwardToReplicas = forwardToReplicas @@ -1891,14 +2387,14 @@ func (c *APIClient) DeleteRule(r ApiDeleteRuleRequest, opts ...Option) (*Updated queryParams := url.Values{} if !isNilorEmpty(r.forwardToReplicas) { - queryParams.Add("forwardToReplicas", parameterToString(r.forwardToReplicas)) + queryParams.Set("forwardToReplicas", parameterToString(r.forwardToReplicas)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -1979,6 +2475,25 @@ type ApiDeleteSourceRequest struct { source string } +func (r *ApiDeleteSourceRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["source"]; ok { //source + err = json.Unmarshal(v, &r.source) + if err != nil { + err = json.Unmarshal(b, &r.source) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiDeleteSourceRequest func (c *APIClient) NewApiDeleteSourceRequest(source string) ApiDeleteSourceRequest { return ApiDeleteSourceRequest{ @@ -2003,7 +2518,7 @@ func (c *APIClient) DeleteSource(r ApiDeleteSourceRequest, opts ...Option) (*Del for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -2086,6 +2601,43 @@ type ApiDeleteSynonymRequest struct { forwardToReplicas bool } +func (r *ApiDeleteSynonymRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + if v, ok := req["objectID"]; ok { //objectID + err = json.Unmarshal(v, &r.objectID) + if err != nil { + err = json.Unmarshal(b, &r.objectID) + if err != nil { + return err + } + } + } + if v, ok := req["forwardToReplicas"]; ok { //forwardToReplicas + err = json.Unmarshal(v, &r.forwardToReplicas) + if err != nil { + err = json.Unmarshal(b, &r.forwardToReplicas) + if err != nil { + return err + } + } + } + + return nil +} + // When true, changes are also propagated to replicas of the given indexName. func (r ApiDeleteSynonymRequest) WithForwardToReplicas(forwardToReplicas bool) ApiDeleteSynonymRequest { r.forwardToReplicas = forwardToReplicas @@ -2115,14 +2667,14 @@ func (c *APIClient) DeleteSynonym(r ApiDeleteSynonymRequest, opts ...Option) (*D queryParams := url.Values{} if !isNilorEmpty(r.forwardToReplicas) { - queryParams.Add("forwardToReplicas", parameterToString(r.forwardToReplicas)) + queryParams.Set("forwardToReplicas", parameterToString(r.forwardToReplicas)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -2204,16 +2756,44 @@ type ApiGetRequest struct { parameters map[string]interface{} } -// Query parameters to be applied to the current query. -func (r ApiGetRequest) WithParameters(parameters map[string]interface{}) ApiGetRequest { - r.parameters = parameters - return r -} - -// @return ApiGetRequest -func (c *APIClient) NewApiGetRequest(path string) ApiGetRequest { - return ApiGetRequest{ - path: path, +func (r *ApiGetRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + + return nil +} + +// Query parameters to be applied to the current query. +func (r ApiGetRequest) WithParameters(parameters map[string]interface{}) ApiGetRequest { + r.parameters = parameters + return r +} + +// @return ApiGetRequest +func (c *APIClient) NewApiGetRequest(path string) ApiGetRequest { + return ApiGetRequest{ + path: path, } } @@ -2231,14 +2811,16 @@ func (c *APIClient) Get(r ApiGetRequest, opts ...Option) (map[string]interface{} queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -2319,6 +2901,25 @@ type ApiGetApiKeyRequest struct { key string } +func (r *ApiGetApiKeyRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["key"]; ok { //key + err = json.Unmarshal(v, &r.key) + if err != nil { + err = json.Unmarshal(b, &r.key) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiGetApiKeyRequest func (c *APIClient) NewApiGetApiKeyRequest(key string) ApiGetApiKeyRequest { return ApiGetApiKeyRequest{ @@ -2343,7 +2944,7 @@ func (c *APIClient) GetApiKey(r ApiGetApiKeyRequest, opts ...Option) (*GetApiKey for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -2423,6 +3024,16 @@ func (c *APIClient) GetApiKey(r ApiGetApiKeyRequest, opts ...Option) (*GetApiKey type ApiGetDictionaryLanguagesRequest struct { } +func (r *ApiGetDictionaryLanguagesRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + + return nil +} + // @return ApiGetDictionaryLanguagesRequest func (c *APIClient) NewApiGetDictionaryLanguagesRequest() ApiGetDictionaryLanguagesRequest { return ApiGetDictionaryLanguagesRequest{} @@ -2444,7 +3055,7 @@ func (c *APIClient) GetDictionaryLanguages(r ApiGetDictionaryLanguagesRequest, o for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -2524,6 +3135,16 @@ func (c *APIClient) GetDictionaryLanguages(r ApiGetDictionaryLanguagesRequest, o type ApiGetDictionarySettingsRequest struct { } +func (r *ApiGetDictionarySettingsRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + + return nil +} + // @return ApiGetDictionarySettingsRequest func (c *APIClient) NewApiGetDictionarySettingsRequest() ApiGetDictionarySettingsRequest { return ApiGetDictionarySettingsRequest{} @@ -2545,7 +3166,7 @@ func (c *APIClient) GetDictionarySettings(r ApiGetDictionarySettingsRequest, opt for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -2629,6 +3250,52 @@ type ApiGetLogsRequest struct { type_ *LogType } +func (r *ApiGetLogsRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["offset"]; ok { //offset + err = json.Unmarshal(v, &r.offset) + if err != nil { + err = json.Unmarshal(b, &r.offset) + if err != nil { + return err + } + } + } + if v, ok := req["length"]; ok { //length + err = json.Unmarshal(v, &r.length) + if err != nil { + err = json.Unmarshal(b, &r.length) + if err != nil { + return err + } + } + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + if v, ok := req["type"]; ok { //type_ + err = json.Unmarshal(v, &r.type_) + if err != nil { + err = json.Unmarshal(b, &r.type_) + if err != nil { + return err + } + } + } + + return nil +} + // First entry to retrieve (zero-based). Log entries are sorted by decreasing date, therefore 0 designates the most recent log entry. func (r ApiGetLogsRequest) WithOffset(offset int32) ApiGetLogsRequest { r.offset = offset @@ -2648,8 +3315,8 @@ func (r ApiGetLogsRequest) WithIndexName(indexName string) ApiGetLogsRequest { } // Type of log entries to retrieve. When omitted, all log entries are retrieved. -func (r ApiGetLogsRequest) WithType_(type_ LogType) ApiGetLogsRequest { - r.type_ = &type_ +func (r ApiGetLogsRequest) WithType_(type_ *LogType) ApiGetLogsRequest { + r.type_ = type_ return r } @@ -2671,23 +3338,23 @@ func (c *APIClient) GetLogs(r ApiGetLogsRequest, opts ...Option) (*GetLogsRespon queryParams := url.Values{} if !isNilorEmpty(r.offset) { - queryParams.Add("offset", parameterToString(r.offset)) + queryParams.Set("offset", parameterToString(r.offset)) } if !isNilorEmpty(r.length) { - queryParams.Add("length", parameterToString(r.length)) + queryParams.Set("length", parameterToString(r.length)) } if !isNilorEmpty(r.indexName) { - queryParams.Add("indexName", parameterToString(r.indexName)) + queryParams.Set("indexName", parameterToString(r.indexName)) } if !isNilorEmpty(r.type_) { - queryParams.Add("type", parameterToString(*r.type_)) + queryParams.Set("type", parameterToString(*r.type_)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -2767,12 +3434,49 @@ func (c *APIClient) GetLogs(r ApiGetLogsRequest, opts ...Option) (*GetLogsRespon type ApiGetObjectRequest struct { indexName string objectID string - attributesToRetrieve *[]string + attributesToRetrieve []string +} + +func (r *ApiGetObjectRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + if v, ok := req["objectID"]; ok { //objectID + err = json.Unmarshal(v, &r.objectID) + if err != nil { + err = json.Unmarshal(b, &r.objectID) + if err != nil { + return err + } + } + } + if v, ok := req["attributesToRetrieve"]; ok { //attributesToRetrieve + err = json.Unmarshal(v, &r.attributesToRetrieve) + if err != nil { + err = json.Unmarshal(b, &r.attributesToRetrieve) + if err != nil { + return err + } + } + } + + return nil } // List of attributes to retrieve. If not specified, all retrievable attributes are returned. func (r ApiGetObjectRequest) WithAttributesToRetrieve(attributesToRetrieve []string) ApiGetObjectRequest { - r.attributesToRetrieve = &attributesToRetrieve + r.attributesToRetrieve = attributesToRetrieve return r } @@ -2799,14 +3503,14 @@ func (c *APIClient) GetObject(r ApiGetObjectRequest, opts ...Option) (map[string queryParams := url.Values{} if !isNilorEmpty(r.attributesToRetrieve) { - queryParams.Add("attributesToRetrieve", parameterToString(*r.attributesToRetrieve)) + queryParams.Set("attributesToRetrieve", parameterToString(r.attributesToRetrieve)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -2887,9 +3591,33 @@ type ApiGetObjectsRequest struct { getObjectsParams *GetObjectsParams } +func (r *ApiGetObjectsRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["getObjectsParams"]; ok { //getObjectsParams + err = json.Unmarshal(v, &r.getObjectsParams) + if err != nil { + err = json.Unmarshal(b, &r.getObjectsParams) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.getObjectsParams) + if err != nil { + return err + } + } + + return nil +} + // The Algolia object. -func (r ApiGetObjectsRequest) WithGetObjectsParams(getObjectsParams GetObjectsParams) ApiGetObjectsRequest { - r.getObjectsParams = &getObjectsParams +func (r ApiGetObjectsRequest) WithGetObjectsParams(getObjectsParams *GetObjectsParams) ApiGetObjectsRequest { + r.getObjectsParams = getObjectsParams return r } @@ -2917,7 +3645,7 @@ func (c *APIClient) GetObjects(r ApiGetObjectsRequest, opts ...Option) (*GetObje for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -3001,6 +3729,34 @@ type ApiGetRuleRequest struct { objectID string } +func (r *ApiGetRuleRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + if v, ok := req["objectID"]; ok { //objectID + err = json.Unmarshal(v, &r.objectID) + if err != nil { + err = json.Unmarshal(b, &r.objectID) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiGetRuleRequest func (c *APIClient) NewApiGetRuleRequest(indexName string, objectID string) ApiGetRuleRequest { return ApiGetRuleRequest{ @@ -3027,7 +3783,7 @@ func (c *APIClient) GetRule(r ApiGetRuleRequest, opts ...Option) (*Rule, error) for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -3108,6 +3864,25 @@ type ApiGetSettingsRequest struct { indexName string } +func (r *ApiGetSettingsRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiGetSettingsRequest func (c *APIClient) NewApiGetSettingsRequest(indexName string) ApiGetSettingsRequest { return ApiGetSettingsRequest{ @@ -3132,7 +3907,7 @@ func (c *APIClient) GetSettings(r ApiGetSettingsRequest, opts ...Option) (*Index for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -3212,6 +3987,16 @@ func (c *APIClient) GetSettings(r ApiGetSettingsRequest, opts ...Option) (*Index type ApiGetSourcesRequest struct { } +func (r *ApiGetSourcesRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + + return nil +} + // @return ApiGetSourcesRequest func (c *APIClient) NewApiGetSourcesRequest() ApiGetSourcesRequest { return ApiGetSourcesRequest{} @@ -3233,7 +4018,7 @@ func (c *APIClient) GetSources(r ApiGetSourcesRequest, opts ...Option) ([]Source for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -3315,6 +4100,34 @@ type ApiGetSynonymRequest struct { objectID string } +func (r *ApiGetSynonymRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + if v, ok := req["objectID"]; ok { //objectID + err = json.Unmarshal(v, &r.objectID) + if err != nil { + err = json.Unmarshal(b, &r.objectID) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiGetSynonymRequest func (c *APIClient) NewApiGetSynonymRequest(indexName string, objectID string) ApiGetSynonymRequest { return ApiGetSynonymRequest{ @@ -3341,7 +4154,7 @@ func (c *APIClient) GetSynonym(r ApiGetSynonymRequest, opts ...Option) (*Synonym for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -3423,6 +4236,34 @@ type ApiGetTaskRequest struct { taskID int64 } +func (r *ApiGetTaskRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + if v, ok := req["taskID"]; ok { //taskID + err = json.Unmarshal(v, &r.taskID) + if err != nil { + err = json.Unmarshal(b, &r.taskID) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiGetTaskRequest func (c *APIClient) NewApiGetTaskRequest(indexName string, taskID int64) ApiGetTaskRequest { return ApiGetTaskRequest{ @@ -3449,7 +4290,7 @@ func (c *APIClient) GetTask(r ApiGetTaskRequest, opts ...Option) (*GetTaskRespon for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -3529,6 +4370,16 @@ func (c *APIClient) GetTask(r ApiGetTaskRequest, opts ...Option) (*GetTaskRespon type ApiGetTopUserIdsRequest struct { } +func (r *ApiGetTopUserIdsRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + + return nil +} + // @return ApiGetTopUserIdsRequest func (c *APIClient) NewApiGetTopUserIdsRequest() ApiGetTopUserIdsRequest { return ApiGetTopUserIdsRequest{} @@ -3550,7 +4401,7 @@ func (c *APIClient) GetTopUserIds(r ApiGetTopUserIdsRequest, opts ...Option) (*G for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -3631,6 +4482,25 @@ type ApiGetUserIdRequest struct { userID string } +func (r *ApiGetUserIdRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["userID"]; ok { //userID + err = json.Unmarshal(v, &r.userID) + if err != nil { + err = json.Unmarshal(b, &r.userID) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiGetUserIdRequest func (c *APIClient) NewApiGetUserIdRequest(userID string) ApiGetUserIdRequest { return ApiGetUserIdRequest{ @@ -3655,7 +4525,7 @@ func (c *APIClient) GetUserId(r ApiGetUserIdRequest, opts ...Option) (*UserId, e for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -3736,6 +4606,25 @@ type ApiHasPendingMappingsRequest struct { getClusters bool } +func (r *ApiHasPendingMappingsRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["getClusters"]; ok { //getClusters + err = json.Unmarshal(v, &r.getClusters) + if err != nil { + err = json.Unmarshal(b, &r.getClusters) + if err != nil { + return err + } + } + } + + return nil +} + // If the clusters pending mapping state should be on the response. func (r ApiHasPendingMappingsRequest) WithGetClusters(getClusters bool) ApiHasPendingMappingsRequest { r.getClusters = getClusters @@ -3760,14 +4649,14 @@ func (c *APIClient) HasPendingMappings(r ApiHasPendingMappingsRequest, opts ...O queryParams := url.Values{} if !isNilorEmpty(r.getClusters) { - queryParams.Add("getClusters", parameterToString(r.getClusters)) + queryParams.Set("getClusters", parameterToString(r.getClusters)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -3847,6 +4736,16 @@ func (c *APIClient) HasPendingMappings(r ApiHasPendingMappingsRequest, opts ...O type ApiListApiKeysRequest struct { } +func (r *ApiListApiKeysRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + + return nil +} + // @return ApiListApiKeysRequest func (c *APIClient) NewApiListApiKeysRequest() ApiListApiKeysRequest { return ApiListApiKeysRequest{} @@ -3868,7 +4767,7 @@ func (c *APIClient) ListApiKeys(r ApiListApiKeysRequest, opts ...Option) (*ListA for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -3948,6 +4847,16 @@ func (c *APIClient) ListApiKeys(r ApiListApiKeysRequest, opts ...Option) (*ListA type ApiListClustersRequest struct { } +func (r *ApiListClustersRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + + return nil +} + // @return ApiListClustersRequest func (c *APIClient) NewApiListClustersRequest() ApiListClustersRequest { return ApiListClustersRequest{} @@ -3969,7 +4878,7 @@ func (c *APIClient) ListClusters(r ApiListClustersRequest, opts ...Option) (*Lis for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -4050,6 +4959,25 @@ type ApiListIndicesRequest struct { page int32 } +func (r *ApiListIndicesRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["page"]; ok { //page + err = json.Unmarshal(v, &r.page) + if err != nil { + err = json.Unmarshal(b, &r.page) + if err != nil { + return err + } + } + } + + return nil +} + // Requested page (zero-based). When specified, will retrieve a specific page; the page size is implicitly set to 100. When null, will retrieve all indices (no pagination). func (r ApiListIndicesRequest) WithPage(page int32) ApiListIndicesRequest { r.page = page @@ -4074,14 +5002,14 @@ func (c *APIClient) ListIndices(r ApiListIndicesRequest, opts ...Option) (*ListI queryParams := url.Values{} if !isNilorEmpty(r.page) { - queryParams.Add("page", parameterToString(r.page)) + queryParams.Set("page", parameterToString(r.page)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -4163,6 +5091,34 @@ type ApiListUserIdsRequest struct { hitsPerPage int32 } +func (r *ApiListUserIdsRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["page"]; ok { //page + err = json.Unmarshal(v, &r.page) + if err != nil { + err = json.Unmarshal(b, &r.page) + if err != nil { + return err + } + } + } + if v, ok := req["hitsPerPage"]; ok { //hitsPerPage + err = json.Unmarshal(v, &r.hitsPerPage) + if err != nil { + err = json.Unmarshal(b, &r.hitsPerPage) + if err != nil { + return err + } + } + } + + return nil +} + // Requested page (zero-based). When specified, will retrieve a specific page; the page size is implicitly set to 100. When null, will retrieve all indices (no pagination). func (r ApiListUserIdsRequest) WithPage(page int32) ApiListUserIdsRequest { r.page = page @@ -4193,17 +5149,17 @@ func (c *APIClient) ListUserIds(r ApiListUserIdsRequest, opts ...Option) (*ListU queryParams := url.Values{} if !isNilorEmpty(r.page) { - queryParams.Add("page", parameterToString(r.page)) + queryParams.Set("page", parameterToString(r.page)) } if !isNilorEmpty(r.hitsPerPage) { - queryParams.Add("hitsPerPage", parameterToString(r.hitsPerPage)) + queryParams.Set("hitsPerPage", parameterToString(r.hitsPerPage)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -4284,8 +5240,32 @@ type ApiMultipleBatchRequest struct { batchParams *BatchParams } -func (r ApiMultipleBatchRequest) WithBatchParams(batchParams BatchParams) ApiMultipleBatchRequest { - r.batchParams = &batchParams +func (r *ApiMultipleBatchRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["batchParams"]; ok { //batchParams + err = json.Unmarshal(v, &r.batchParams) + if err != nil { + err = json.Unmarshal(b, &r.batchParams) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.batchParams) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiMultipleBatchRequest) WithBatchParams(batchParams *BatchParams) ApiMultipleBatchRequest { + r.batchParams = batchParams return r } @@ -4313,7 +5293,7 @@ func (c *APIClient) MultipleBatch(r ApiMultipleBatchRequest, opts ...Option) (*M for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -4397,8 +5377,41 @@ type ApiOperationIndexRequest struct { operationIndexParams *OperationIndexParams } -func (r ApiOperationIndexRequest) WithOperationIndexParams(operationIndexParams OperationIndexParams) ApiOperationIndexRequest { - r.operationIndexParams = &operationIndexParams +func (r *ApiOperationIndexRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + if v, ok := req["operationIndexParams"]; ok { //operationIndexParams + err = json.Unmarshal(v, &r.operationIndexParams) + if err != nil { + err = json.Unmarshal(b, &r.operationIndexParams) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.operationIndexParams) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiOperationIndexRequest) WithOperationIndexParams(operationIndexParams *OperationIndexParams) ApiOperationIndexRequest { + r.operationIndexParams = operationIndexParams return r } @@ -4429,7 +5442,7 @@ func (c *APIClient) OperationIndex(r ApiOperationIndexRequest, opts ...Option) ( for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -4515,9 +5528,60 @@ type ApiPartialUpdateObjectRequest struct { createIfNotExists bool } +func (r *ApiPartialUpdateObjectRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + if v, ok := req["objectID"]; ok { //objectID + err = json.Unmarshal(v, &r.objectID) + if err != nil { + err = json.Unmarshal(b, &r.objectID) + if err != nil { + return err + } + } + } + if v, ok := req["attributesToUpdate"]; ok { //attributesToUpdate + err = json.Unmarshal(v, &r.attributesToUpdate) + if err != nil { + err = json.Unmarshal(b, &r.attributesToUpdate) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.attributesToUpdate) + if err != nil { + return err + } + } + if v, ok := req["createIfNotExists"]; ok { //createIfNotExists + err = json.Unmarshal(v, &r.createIfNotExists) + if err != nil { + err = json.Unmarshal(b, &r.createIfNotExists) + if err != nil { + return err + } + } + } + + return nil +} + // Map of attribute(s) to update. -func (r ApiPartialUpdateObjectRequest) WithAttributesToUpdate(attributesToUpdate map[string]AttributeToUpdate) ApiPartialUpdateObjectRequest { - r.attributesToUpdate = &attributesToUpdate +func (r ApiPartialUpdateObjectRequest) WithAttributesToUpdate(attributesToUpdate *map[string]AttributeToUpdate) ApiPartialUpdateObjectRequest { + r.attributesToUpdate = attributesToUpdate return r } @@ -4553,14 +5617,14 @@ func (c *APIClient) PartialUpdateObject(r ApiPartialUpdateObjectRequest, opts .. } if !isNilorEmpty(r.createIfNotExists) { - queryParams.Add("createIfNotExists", parameterToString(r.createIfNotExists)) + queryParams.Set("createIfNotExists", parameterToString(r.createIfNotExists)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -4645,17 +5709,54 @@ type ApiPostRequest struct { body map[string]interface{} } -// Query parameters to be applied to the current query. -func (r ApiPostRequest) WithParameters(parameters map[string]interface{}) ApiPostRequest { - r.parameters = parameters - return r -} - -// The parameters to send with the custom request. -func (r ApiPostRequest) WithBody(body map[string]interface{}) ApiPostRequest { - r.body = body - return r -} +func (r *ApiPostRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + if v, ok := req["body"]; ok { //body + err = json.Unmarshal(v, &r.body) + if err != nil { + err = json.Unmarshal(b, &r.body) + if err != nil { + return err + } + } + } + + return nil +} + +// Query parameters to be applied to the current query. +func (r ApiPostRequest) WithParameters(parameters map[string]interface{}) ApiPostRequest { + r.parameters = parameters + return r +} + +// The parameters to send with the custom request. +func (r ApiPostRequest) WithBody(body map[string]interface{}) ApiPostRequest { + r.body = body + return r +} // @return ApiPostRequest func (c *APIClient) NewApiPostRequest(path string) ApiPostRequest { @@ -4678,21 +5779,27 @@ func (c *APIClient) Post(r ApiPostRequest, opts ...Option) (map[string]interface queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } } // body params - postBody = r.body + if isNilorEmpty(r.body) { + postBody = "{}" + } else { + postBody = r.body + } req, err := c.prepareRequest(context.Background(), requestPath, http.MethodPost, postBody, headers, queryParams) if err != nil { return returnValue, err @@ -4770,6 +5877,43 @@ type ApiPutRequest struct { body map[string]interface{} } +func (r *ApiPutRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["path"]; ok { //path + err = json.Unmarshal(v, &r.path) + if err != nil { + err = json.Unmarshal(b, &r.path) + if err != nil { + return err + } + } + } + if v, ok := req["parameters"]; ok { //parameters + err = json.Unmarshal(v, &r.parameters) + if err != nil { + err = json.Unmarshal(b, &r.parameters) + if err != nil { + return err + } + } + } + if v, ok := req["body"]; ok { //body + err = json.Unmarshal(v, &r.body) + if err != nil { + err = json.Unmarshal(b, &r.body) + if err != nil { + return err + } + } + } + + return nil +} + // Query parameters to be applied to the current query. func (r ApiPutRequest) WithParameters(parameters map[string]interface{}) ApiPutRequest { r.parameters = parameters @@ -4803,21 +5947,27 @@ func (c *APIClient) Put(r ApiPutRequest, opts ...Option) (map[string]interface{} queryParams := url.Values{} if !isNilorEmpty(r.parameters) { - queryParams.Add("parameters", parameterToString(r.parameters)) + for k, v := range r.parameters { + queryParams.Set(k, parameterToString(v)) + } } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } } // body params - postBody = r.body + if isNilorEmpty(r.body) { + postBody = "{}" + } else { + postBody = r.body + } req, err := c.prepareRequest(context.Background(), requestPath, http.MethodPut, postBody, headers, queryParams) if err != nil { return returnValue, err @@ -4893,6 +6043,25 @@ type ApiRemoveUserIdRequest struct { userID string } +func (r *ApiRemoveUserIdRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["userID"]; ok { //userID + err = json.Unmarshal(v, &r.userID) + if err != nil { + err = json.Unmarshal(b, &r.userID) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiRemoveUserIdRequest func (c *APIClient) NewApiRemoveUserIdRequest(userID string) ApiRemoveUserIdRequest { return ApiRemoveUserIdRequest{ @@ -4917,7 +6086,7 @@ func (c *APIClient) RemoveUserId(r ApiRemoveUserIdRequest, opts ...Option) (*Rem for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -4995,12 +6164,36 @@ func (c *APIClient) RemoveUserId(r ApiRemoveUserIdRequest, opts ...Option) (*Rem } type ApiReplaceSourcesRequest struct { - source *[]Source + source []Source +} + +func (r *ApiReplaceSourcesRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["source"]; ok { //source + err = json.Unmarshal(v, &r.source) + if err != nil { + err = json.Unmarshal(b, &r.source) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.source) + if err != nil { + return err + } + } + + return nil } // The sources to allow. func (r ApiReplaceSourcesRequest) WithSource(source []Source) ApiReplaceSourcesRequest { - r.source = &source + r.source = source return r } @@ -5028,7 +6221,7 @@ func (c *APIClient) ReplaceSources(r ApiReplaceSourcesRequest, opts ...Option) ( for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -5111,6 +6304,25 @@ type ApiRestoreApiKeyRequest struct { key string } +func (r *ApiRestoreApiKeyRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["key"]; ok { //key + err = json.Unmarshal(v, &r.key) + if err != nil { + err = json.Unmarshal(b, &r.key) + if err != nil { + return err + } + } + } + + return nil +} + // @return ApiRestoreApiKeyRequest func (c *APIClient) NewApiRestoreApiKeyRequest(key string) ApiRestoreApiKeyRequest { return ApiRestoreApiKeyRequest{ @@ -5135,7 +6347,7 @@ func (c *APIClient) RestoreApiKey(r ApiRestoreApiKeyRequest, opts ...Option) (*A for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -5217,6 +6429,39 @@ type ApiSaveObjectRequest struct { body map[string]interface{} } +func (r *ApiSaveObjectRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + if v, ok := req["body"]; ok { //body + err = json.Unmarshal(v, &r.body) + if err != nil { + err = json.Unmarshal(b, &r.body) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.body) + if err != nil { + return err + } + } + + return nil +} + // The Algolia record. func (r ApiSaveObjectRequest) WithBody(body map[string]interface{}) ApiSaveObjectRequest { r.body = body @@ -5247,7 +6492,7 @@ func (c *APIClient) SaveObject(r ApiSaveObjectRequest, opts ...Option) (*SaveObj for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -5333,8 +6578,59 @@ type ApiSaveRuleRequest struct { forwardToReplicas bool } -func (r ApiSaveRuleRequest) WithRule(rule Rule) ApiSaveRuleRequest { - r.rule = &rule +func (r *ApiSaveRuleRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + if v, ok := req["objectID"]; ok { //objectID + err = json.Unmarshal(v, &r.objectID) + if err != nil { + err = json.Unmarshal(b, &r.objectID) + if err != nil { + return err + } + } + } + if v, ok := req["rule"]; ok { //rule + err = json.Unmarshal(v, &r.rule) + if err != nil { + err = json.Unmarshal(b, &r.rule) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.rule) + if err != nil { + return err + } + } + if v, ok := req["forwardToReplicas"]; ok { //forwardToReplicas + err = json.Unmarshal(v, &r.forwardToReplicas) + if err != nil { + err = json.Unmarshal(b, &r.forwardToReplicas) + if err != nil { + return err + } + } + } + + return nil +} + +func (r ApiSaveRuleRequest) WithRule(rule *Rule) ApiSaveRuleRequest { + r.rule = rule return r } @@ -5370,14 +6666,14 @@ func (c *APIClient) SaveRule(r ApiSaveRuleRequest, opts ...Option) (*UpdatedRule } if !isNilorEmpty(r.forwardToReplicas) { - queryParams.Add("forwardToReplicas", parameterToString(r.forwardToReplicas)) + queryParams.Set("forwardToReplicas", parameterToString(r.forwardToReplicas)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -5458,13 +6754,64 @@ func (c *APIClient) SaveRule(r ApiSaveRuleRequest, opts ...Option) (*UpdatedRule type ApiSaveRulesRequest struct { indexName string - rules *[]Rule + rules []Rule forwardToReplicas bool clearExistingRules bool } +func (r *ApiSaveRulesRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + if v, ok := req["rules"]; ok { //rules + err = json.Unmarshal(v, &r.rules) + if err != nil { + err = json.Unmarshal(b, &r.rules) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.rules) + if err != nil { + return err + } + } + if v, ok := req["forwardToReplicas"]; ok { //forwardToReplicas + err = json.Unmarshal(v, &r.forwardToReplicas) + if err != nil { + err = json.Unmarshal(b, &r.forwardToReplicas) + if err != nil { + return err + } + } + } + if v, ok := req["clearExistingRules"]; ok { //clearExistingRules + err = json.Unmarshal(v, &r.clearExistingRules) + if err != nil { + err = json.Unmarshal(b, &r.clearExistingRules) + if err != nil { + return err + } + } + } + + return nil +} + func (r ApiSaveRulesRequest) WithRules(rules []Rule) ApiSaveRulesRequest { - r.rules = &rules + r.rules = rules return r } @@ -5504,17 +6851,17 @@ func (c *APIClient) SaveRules(r ApiSaveRulesRequest, opts ...Option) (*UpdatedAt } if !isNilorEmpty(r.forwardToReplicas) { - queryParams.Add("forwardToReplicas", parameterToString(r.forwardToReplicas)) + queryParams.Set("forwardToReplicas", parameterToString(r.forwardToReplicas)) } if !isNilorEmpty(r.clearExistingRules) { - queryParams.Add("clearExistingRules", parameterToString(r.clearExistingRules)) + queryParams.Set("clearExistingRules", parameterToString(r.clearExistingRules)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -5600,8 +6947,59 @@ type ApiSaveSynonymRequest struct { forwardToReplicas bool } -func (r ApiSaveSynonymRequest) WithSynonymHit(synonymHit SynonymHit) ApiSaveSynonymRequest { - r.synonymHit = &synonymHit +func (r *ApiSaveSynonymRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + if v, ok := req["objectID"]; ok { //objectID + err = json.Unmarshal(v, &r.objectID) + if err != nil { + err = json.Unmarshal(b, &r.objectID) + if err != nil { + return err + } + } + } + if v, ok := req["synonymHit"]; ok { //synonymHit + err = json.Unmarshal(v, &r.synonymHit) + if err != nil { + err = json.Unmarshal(b, &r.synonymHit) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.synonymHit) + if err != nil { + return err + } + } + if v, ok := req["forwardToReplicas"]; ok { //forwardToReplicas + err = json.Unmarshal(v, &r.forwardToReplicas) + if err != nil { + err = json.Unmarshal(b, &r.forwardToReplicas) + if err != nil { + return err + } + } + } + + return nil +} + +func (r ApiSaveSynonymRequest) WithSynonymHit(synonymHit *SynonymHit) ApiSaveSynonymRequest { + r.synonymHit = synonymHit return r } @@ -5637,14 +7035,14 @@ func (c *APIClient) SaveSynonym(r ApiSaveSynonymRequest, opts ...Option) (*SaveS } if !isNilorEmpty(r.forwardToReplicas) { - queryParams.Add("forwardToReplicas", parameterToString(r.forwardToReplicas)) + queryParams.Set("forwardToReplicas", parameterToString(r.forwardToReplicas)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -5725,13 +7123,64 @@ func (c *APIClient) SaveSynonym(r ApiSaveSynonymRequest, opts ...Option) (*SaveS type ApiSaveSynonymsRequest struct { indexName string - synonymHit *[]SynonymHit + synonymHit []SynonymHit forwardToReplicas bool replaceExistingSynonyms bool } +func (r *ApiSaveSynonymsRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + if v, ok := req["synonymHit"]; ok { //synonymHit + err = json.Unmarshal(v, &r.synonymHit) + if err != nil { + err = json.Unmarshal(b, &r.synonymHit) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.synonymHit) + if err != nil { + return err + } + } + if v, ok := req["forwardToReplicas"]; ok { //forwardToReplicas + err = json.Unmarshal(v, &r.forwardToReplicas) + if err != nil { + err = json.Unmarshal(b, &r.forwardToReplicas) + if err != nil { + return err + } + } + } + if v, ok := req["replaceExistingSynonyms"]; ok { //replaceExistingSynonyms + err = json.Unmarshal(v, &r.replaceExistingSynonyms) + if err != nil { + err = json.Unmarshal(b, &r.replaceExistingSynonyms) + if err != nil { + return err + } + } + } + + return nil +} + func (r ApiSaveSynonymsRequest) WithSynonymHit(synonymHit []SynonymHit) ApiSaveSynonymsRequest { - r.synonymHit = &synonymHit + r.synonymHit = synonymHit return r } @@ -5771,17 +7220,17 @@ func (c *APIClient) SaveSynonyms(r ApiSaveSynonymsRequest, opts ...Option) (*Upd } if !isNilorEmpty(r.forwardToReplicas) { - queryParams.Add("forwardToReplicas", parameterToString(r.forwardToReplicas)) + queryParams.Set("forwardToReplicas", parameterToString(r.forwardToReplicas)) } if !isNilorEmpty(r.replaceExistingSynonyms) { - queryParams.Add("replaceExistingSynonyms", parameterToString(r.replaceExistingSynonyms)) + queryParams.Set("replaceExistingSynonyms", parameterToString(r.replaceExistingSynonyms)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -5864,9 +7313,33 @@ type ApiSearchRequest struct { searchMethodParams *SearchMethodParams } +func (r *ApiSearchRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["searchMethodParams"]; ok { //searchMethodParams + err = json.Unmarshal(v, &r.searchMethodParams) + if err != nil { + err = json.Unmarshal(b, &r.searchMethodParams) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.searchMethodParams) + if err != nil { + return err + } + } + + return nil +} + // The `search` requests and strategy. -func (r ApiSearchRequest) WithSearchMethodParams(searchMethodParams SearchMethodParams) ApiSearchRequest { - r.searchMethodParams = &searchMethodParams +func (r ApiSearchRequest) WithSearchMethodParams(searchMethodParams *SearchMethodParams) ApiSearchRequest { + r.searchMethodParams = searchMethodParams return r } @@ -5894,7 +7367,7 @@ func (c *APIClient) Search(r ApiSearchRequest, opts ...Option) (*SearchResponses for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -5978,8 +7451,41 @@ type ApiSearchDictionaryEntriesRequest struct { searchDictionaryEntriesParams *SearchDictionaryEntriesParams } -func (r ApiSearchDictionaryEntriesRequest) WithSearchDictionaryEntriesParams(searchDictionaryEntriesParams SearchDictionaryEntriesParams) ApiSearchDictionaryEntriesRequest { - r.searchDictionaryEntriesParams = &searchDictionaryEntriesParams +func (r *ApiSearchDictionaryEntriesRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["dictionaryName"]; ok { //dictionaryName + err = json.Unmarshal(v, &r.dictionaryName) + if err != nil { + err = json.Unmarshal(b, &r.dictionaryName) + if err != nil { + return err + } + } + } + if v, ok := req["searchDictionaryEntriesParams"]; ok { //searchDictionaryEntriesParams + err = json.Unmarshal(v, &r.searchDictionaryEntriesParams) + if err != nil { + err = json.Unmarshal(b, &r.searchDictionaryEntriesParams) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.searchDictionaryEntriesParams) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiSearchDictionaryEntriesRequest) WithSearchDictionaryEntriesParams(searchDictionaryEntriesParams *SearchDictionaryEntriesParams) ApiSearchDictionaryEntriesRequest { + r.searchDictionaryEntriesParams = searchDictionaryEntriesParams return r } @@ -6010,7 +7516,7 @@ func (c *APIClient) SearchDictionaryEntries(r ApiSearchDictionaryEntriesRequest, for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -6095,8 +7601,45 @@ type ApiSearchForFacetValuesRequest struct { searchForFacetValuesRequest *SearchForFacetValuesRequest } -func (r ApiSearchForFacetValuesRequest) WithSearchForFacetValuesRequest(searchForFacetValuesRequest SearchForFacetValuesRequest) ApiSearchForFacetValuesRequest { - r.searchForFacetValuesRequest = &searchForFacetValuesRequest +func (r *ApiSearchForFacetValuesRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + if v, ok := req["facetName"]; ok { //facetName + err = json.Unmarshal(v, &r.facetName) + if err != nil { + err = json.Unmarshal(b, &r.facetName) + if err != nil { + return err + } + } + } + if v, ok := req["searchForFacetValuesRequest"]; ok { //searchForFacetValuesRequest + err = json.Unmarshal(v, &r.searchForFacetValuesRequest) + if err != nil { + err = json.Unmarshal(b, &r.searchForFacetValuesRequest) + if err != nil { + return err + } + } + } + + return nil +} + +func (r ApiSearchForFacetValuesRequest) WithSearchForFacetValuesRequest(searchForFacetValuesRequest *SearchForFacetValuesRequest) ApiSearchForFacetValuesRequest { + r.searchForFacetValuesRequest = searchForFacetValuesRequest return r } @@ -6126,14 +7669,18 @@ func (c *APIClient) SearchForFacetValues(r ApiSearchForFacetValuesRequest, opts for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } } // body params - postBody = r.searchForFacetValuesRequest + if isNilorEmpty(r.searchForFacetValuesRequest) { + postBody = "{}" + } else { + postBody = r.searchForFacetValuesRequest + } req, err := c.prepareRequest(context.Background(), requestPath, http.MethodPost, postBody, headers, queryParams) if err != nil { return returnValue, err @@ -6210,8 +7757,36 @@ type ApiSearchRulesRequest struct { searchRulesParams *SearchRulesParams } -func (r ApiSearchRulesRequest) WithSearchRulesParams(searchRulesParams SearchRulesParams) ApiSearchRulesRequest { - r.searchRulesParams = &searchRulesParams +func (r *ApiSearchRulesRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + if v, ok := req["searchRulesParams"]; ok { //searchRulesParams + err = json.Unmarshal(v, &r.searchRulesParams) + if err != nil { + err = json.Unmarshal(b, &r.searchRulesParams) + if err != nil { + return err + } + } + } + + return nil +} + +func (r ApiSearchRulesRequest) WithSearchRulesParams(searchRulesParams *SearchRulesParams) ApiSearchRulesRequest { + r.searchRulesParams = searchRulesParams return r } @@ -6239,14 +7814,18 @@ func (c *APIClient) SearchRules(r ApiSearchRulesRequest, opts ...Option) (*Searc for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } } // body params - postBody = r.searchRulesParams + if isNilorEmpty(r.searchRulesParams) { + postBody = "{}" + } else { + postBody = r.searchRulesParams + } req, err := c.prepareRequest(context.Background(), requestPath, http.MethodPost, postBody, headers, queryParams) if err != nil { return returnValue, err @@ -6323,8 +7902,36 @@ type ApiSearchSingleIndexRequest struct { searchParams *SearchParams } -func (r ApiSearchSingleIndexRequest) WithSearchParams(searchParams SearchParams) ApiSearchSingleIndexRequest { - r.searchParams = &searchParams +func (r *ApiSearchSingleIndexRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + if v, ok := req["searchParams"]; ok { //searchParams + err = json.Unmarshal(v, &r.searchParams) + if err != nil { + err = json.Unmarshal(b, &r.searchParams) + if err != nil { + return err + } + } + } + + return nil +} + +func (r ApiSearchSingleIndexRequest) WithSearchParams(searchParams *SearchParams) ApiSearchSingleIndexRequest { + r.searchParams = searchParams return r } @@ -6352,14 +7959,18 @@ func (c *APIClient) SearchSingleIndex(r ApiSearchSingleIndexRequest, opts ...Opt for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } } // body params - postBody = r.searchParams + if isNilorEmpty(r.searchParams) { + postBody = "{}" + } else { + postBody = r.searchParams + } req, err := c.prepareRequest(context.Background(), requestPath, http.MethodPost, postBody, headers, queryParams) if err != nil { return returnValue, err @@ -6439,9 +8050,64 @@ type ApiSearchSynonymsRequest struct { searchSynonymsParams *SearchSynonymsParams } +func (r *ApiSearchSynonymsRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + if v, ok := req["type"]; ok { //type_ + err = json.Unmarshal(v, &r.type_) + if err != nil { + err = json.Unmarshal(b, &r.type_) + if err != nil { + return err + } + } + } + if v, ok := req["page"]; ok { //page + err = json.Unmarshal(v, &r.page) + if err != nil { + err = json.Unmarshal(b, &r.page) + if err != nil { + return err + } + } + } + if v, ok := req["hitsPerPage"]; ok { //hitsPerPage + err = json.Unmarshal(v, &r.hitsPerPage) + if err != nil { + err = json.Unmarshal(b, &r.hitsPerPage) + if err != nil { + return err + } + } + } + if v, ok := req["searchSynonymsParams"]; ok { //searchSynonymsParams + err = json.Unmarshal(v, &r.searchSynonymsParams) + if err != nil { + err = json.Unmarshal(b, &r.searchSynonymsParams) + if err != nil { + return err + } + } + } + + return nil +} + // Only search for specific types of synonyms. -func (r ApiSearchSynonymsRequest) WithType_(type_ SynonymType) ApiSearchSynonymsRequest { - r.type_ = &type_ +func (r ApiSearchSynonymsRequest) WithType_(type_ *SynonymType) ApiSearchSynonymsRequest { + r.type_ = type_ return r } @@ -6458,8 +8124,8 @@ func (r ApiSearchSynonymsRequest) WithHitsPerPage(hitsPerPage int32) ApiSearchSy } // The body of the the `searchSynonyms` method. -func (r ApiSearchSynonymsRequest) WithSearchSynonymsParams(searchSynonymsParams SearchSynonymsParams) ApiSearchSynonymsRequest { - r.searchSynonymsParams = &searchSynonymsParams +func (r ApiSearchSynonymsRequest) WithSearchSynonymsParams(searchSynonymsParams *SearchSynonymsParams) ApiSearchSynonymsRequest { + r.searchSynonymsParams = searchSynonymsParams return r } @@ -6484,27 +8150,31 @@ func (c *APIClient) SearchSynonyms(r ApiSearchSynonymsRequest, opts ...Option) ( queryParams := url.Values{} if !isNilorEmpty(r.type_) { - queryParams.Add("type", parameterToString(*r.type_)) + queryParams.Set("type", parameterToString(*r.type_)) } if !isNilorEmpty(r.page) { - queryParams.Add("page", parameterToString(r.page)) + queryParams.Set("page", parameterToString(r.page)) } if !isNilorEmpty(r.hitsPerPage) { - queryParams.Add("hitsPerPage", parameterToString(r.hitsPerPage)) + queryParams.Set("hitsPerPage", parameterToString(r.hitsPerPage)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } } // body params - postBody = r.searchSynonymsParams + if isNilorEmpty(r.searchSynonymsParams) { + postBody = "{}" + } else { + postBody = r.searchSynonymsParams + } req, err := c.prepareRequest(context.Background(), requestPath, http.MethodPost, postBody, headers, queryParams) if err != nil { return returnValue, err @@ -6580,8 +8250,32 @@ type ApiSearchUserIdsRequest struct { searchUserIdsParams *SearchUserIdsParams } -func (r ApiSearchUserIdsRequest) WithSearchUserIdsParams(searchUserIdsParams SearchUserIdsParams) ApiSearchUserIdsRequest { - r.searchUserIdsParams = &searchUserIdsParams +func (r *ApiSearchUserIdsRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["searchUserIdsParams"]; ok { //searchUserIdsParams + err = json.Unmarshal(v, &r.searchUserIdsParams) + if err != nil { + err = json.Unmarshal(b, &r.searchUserIdsParams) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.searchUserIdsParams) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiSearchUserIdsRequest) WithSearchUserIdsParams(searchUserIdsParams *SearchUserIdsParams) ApiSearchUserIdsRequest { + r.searchUserIdsParams = searchUserIdsParams return r } @@ -6609,7 +8303,7 @@ func (c *APIClient) SearchUserIds(r ApiSearchUserIdsRequest, opts ...Option) (*S for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -6692,8 +8386,32 @@ type ApiSetDictionarySettingsRequest struct { dictionarySettingsParams *DictionarySettingsParams } -func (r ApiSetDictionarySettingsRequest) WithDictionarySettingsParams(dictionarySettingsParams DictionarySettingsParams) ApiSetDictionarySettingsRequest { - r.dictionarySettingsParams = &dictionarySettingsParams +func (r *ApiSetDictionarySettingsRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["dictionarySettingsParams"]; ok { //dictionarySettingsParams + err = json.Unmarshal(v, &r.dictionarySettingsParams) + if err != nil { + err = json.Unmarshal(b, &r.dictionarySettingsParams) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.dictionarySettingsParams) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiSetDictionarySettingsRequest) WithDictionarySettingsParams(dictionarySettingsParams *DictionarySettingsParams) ApiSetDictionarySettingsRequest { + r.dictionarySettingsParams = dictionarySettingsParams return r } @@ -6721,7 +8439,7 @@ func (c *APIClient) SetDictionarySettings(r ApiSetDictionarySettingsRequest, opt for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -6806,8 +8524,50 @@ type ApiSetSettingsRequest struct { forwardToReplicas bool } -func (r ApiSetSettingsRequest) WithIndexSettings(indexSettings IndexSettings) ApiSetSettingsRequest { - r.indexSettings = &indexSettings +func (r *ApiSetSettingsRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["indexName"]; ok { //indexName + err = json.Unmarshal(v, &r.indexName) + if err != nil { + err = json.Unmarshal(b, &r.indexName) + if err != nil { + return err + } + } + } + if v, ok := req["indexSettings"]; ok { //indexSettings + err = json.Unmarshal(v, &r.indexSettings) + if err != nil { + err = json.Unmarshal(b, &r.indexSettings) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.indexSettings) + if err != nil { + return err + } + } + if v, ok := req["forwardToReplicas"]; ok { //forwardToReplicas + err = json.Unmarshal(v, &r.forwardToReplicas) + if err != nil { + err = json.Unmarshal(b, &r.forwardToReplicas) + if err != nil { + return err + } + } + } + + return nil +} + +func (r ApiSetSettingsRequest) WithIndexSettings(indexSettings *IndexSettings) ApiSetSettingsRequest { + r.indexSettings = indexSettings return r } @@ -6841,14 +8601,14 @@ func (c *APIClient) SetSettings(r ApiSetSettingsRequest, opts ...Option) (*Updat } if !isNilorEmpty(r.forwardToReplicas) { - queryParams.Add("forwardToReplicas", parameterToString(r.forwardToReplicas)) + queryParams.Set("forwardToReplicas", parameterToString(r.forwardToReplicas)) } // optional params if any for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } @@ -6932,8 +8692,41 @@ type ApiUpdateApiKeyRequest struct { apiKey *ApiKey } -func (r ApiUpdateApiKeyRequest) WithApiKey(apiKey ApiKey) ApiUpdateApiKeyRequest { - r.apiKey = &apiKey +func (r *ApiUpdateApiKeyRequest) UnmarshalJSON(b []byte) error { + req := map[string]json.RawMessage{} + err := json.Unmarshal(b, &req) + if err != nil { + return err + } + if v, ok := req["key"]; ok { //key + err = json.Unmarshal(v, &r.key) + if err != nil { + err = json.Unmarshal(b, &r.key) + if err != nil { + return err + } + } + } + if v, ok := req["apiKey"]; ok { //apiKey + err = json.Unmarshal(v, &r.apiKey) + if err != nil { + err = json.Unmarshal(b, &r.apiKey) + if err != nil { + return err + } + } + } else { + err = json.Unmarshal(b, &r.apiKey) + if err != nil { + return err + } + } + + return nil +} + +func (r ApiUpdateApiKeyRequest) WithApiKey(apiKey *ApiKey) ApiUpdateApiKeyRequest { + r.apiKey = apiKey return r } @@ -6964,7 +8757,7 @@ func (c *APIClient) UpdateApiKey(r ApiUpdateApiKeyRequest, opts ...Option) (*Upd for _, opt := range opts { switch opt.optionType { case "query": - queryParams.Add(opt.name, opt.value) + queryParams.Set(opt.name, opt.value) case "header": headers[opt.name] = opt.value } diff --git a/clients/algoliasearch-client-go/algolia/search/client.go b/clients/algoliasearch-client-go/algolia/search/client.go index 2b14e802dc..19fd871e4b 100644 --- a/clients/algoliasearch-client-go/algolia/search/client.go +++ b/clients/algoliasearch-client-go/algolia/search/client.go @@ -20,6 +20,8 @@ import ( "strings" "time" + "github.com/go-playground/validator/v10" + "github.com/algolia/algoliasearch-client-go/v4/algolia/call" "github.com/algolia/algoliasearch-client-go/v4/algolia/compression" "github.com/algolia/algoliasearch-client-go/v4/algolia/internal/transport" @@ -132,7 +134,7 @@ func typeCheckParameter(obj any, expected string, name string) error { // parameterToString convert any parameters to string. func parameterToString(obj any) string { if reflect.TypeOf(obj).Kind() == reflect.Slice { - return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", "", -1), "[]") + return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", ",", -1), "[]") } else if t, ok := obj.(time.Time); ok { return t.Format(time.RFC3339) } @@ -231,11 +233,9 @@ func (c *APIClient) prepareRequest( // add header parameters, if any if len(headerParams) > 0 { - headers := http.Header{} for h, v := range headerParams { - headers[h] = []string{v} + req.Header.Add(h, v) } - req.Header = headers } // Add the user agent to the request. @@ -294,6 +294,17 @@ func newStrictDecoder(data []byte) *json.Decoder { return dec } +// A wrapper for validating a struct, returns nil if value is not a struct +func validateStruct(v any) error { + err := validator.New().Struct(v) + validationErrors, ok := err.(validator.ValidationErrors) + if ok && len(validationErrors) > 0 { + return validationErrors + } + + return nil +} + // Set request body from an any func setBody(body any, contentType string, c compression.Compression) (bodyBuf *bytes.Buffer, err error) { if body == nil { diff --git a/clients/algoliasearch-client-go/algolia/search/model_add_api_key_response.go b/clients/algoliasearch-client-go/algolia/search/model_add_api_key_response.go index 08c3e76a77..c445db28e2 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_add_api_key_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_add_api_key_response.go @@ -9,9 +9,9 @@ import ( // AddApiKeyResponse struct for AddApiKeyResponse type AddApiKeyResponse struct { // The API key. - Key string `json:"key"` + Key string `json:"key" validate:"required"` // Date of creation (ISO-8601 format). - CreatedAt string `json:"createdAt"` + CreatedAt string `json:"createdAt" validate:"required"` } // NewAddApiKeyResponse instantiates a new AddApiKeyResponse object diff --git a/clients/algoliasearch-client-go/algolia/search/model_api_key.go b/clients/algoliasearch-client-go/algolia/search/model_api_key.go index b7b59334cb..8f7bf7557a 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_api_key.go +++ b/clients/algoliasearch-client-go/algolia/search/model_api_key.go @@ -9,7 +9,7 @@ import ( // ApiKey Api Key object. type ApiKey struct { // Set of permissions associated with the key. - Acl []Acl `json:"acl"` + Acl []Acl `json:"acl" validate:"required"` // A comment used to identify a key more easily in the dashboard. It is not interpreted by the API. Description *string `json:"description,omitempty"` // Restrict this new API key to a list of indices or index patterns. If the list is empty, all indices are allowed. diff --git a/clients/algoliasearch-client-go/algolia/search/model_around_radius.go b/clients/algoliasearch-client-go/algolia/search/model_around_radius.go index 206ada9488..3dc1b75332 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_around_radius.go +++ b/clients/algoliasearch-client-go/algolia/search/model_around_radius.go @@ -29,15 +29,14 @@ func Int32AsAroundRadius(v *int32) AroundRadius { // Unmarshal JSON data into one of the pointers in the struct func (dst *AroundRadius) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into AroundRadiusAll err = newStrictDecoder(data).Decode(&dst.AroundRadiusAll) - if err == nil { + if err == nil && validateStruct(dst.AroundRadiusAll) == nil { jsonAroundRadiusAll, _ := json.Marshal(dst.AroundRadiusAll) if string(jsonAroundRadiusAll) == "{}" { // empty struct dst.AroundRadiusAll = nil } else { - match++ + return nil } } else { dst.AroundRadiusAll = nil @@ -45,28 +44,18 @@ func (dst *AroundRadius) UnmarshalJSON(data []byte) error { // try to unmarshal data into Int32 err = newStrictDecoder(data).Decode(&dst.Int32) - if err == nil { + if err == nil && validateStruct(dst.Int32) == nil { jsonInt32, _ := json.Marshal(dst.Int32) if string(jsonInt32) == "{}" { // empty struct dst.Int32 = nil } else { - match++ + return nil } } else { dst.Int32 = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.AroundRadiusAll = nil - dst.Int32 = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(AroundRadius)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(AroundRadius)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(AroundRadius)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/search/model_assign_user_id_params.go b/clients/algoliasearch-client-go/algolia/search/model_assign_user_id_params.go index 9b9c6245db..7f08f36783 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_assign_user_id_params.go +++ b/clients/algoliasearch-client-go/algolia/search/model_assign_user_id_params.go @@ -9,7 +9,7 @@ import ( // AssignUserIdParams Assign userID parameters. type AssignUserIdParams struct { // Name of the cluster. - Cluster string `json:"cluster"` + Cluster string `json:"cluster" validate:"required"` } // NewAssignUserIdParams instantiates a new AssignUserIdParams object diff --git a/clients/algoliasearch-client-go/algolia/search/model_attribute_to_update.go b/clients/algoliasearch-client-go/algolia/search/model_attribute_to_update.go index 5c98c5eb95..79104d2bd9 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_attribute_to_update.go +++ b/clients/algoliasearch-client-go/algolia/search/model_attribute_to_update.go @@ -29,15 +29,14 @@ func StringAsAttributeToUpdate(v *string) AttributeToUpdate { // Unmarshal JSON data into one of the pointers in the struct func (dst *AttributeToUpdate) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into BuiltInOperation err = newStrictDecoder(data).Decode(&dst.BuiltInOperation) - if err == nil { + if err == nil && validateStruct(dst.BuiltInOperation) == nil { jsonBuiltInOperation, _ := json.Marshal(dst.BuiltInOperation) if string(jsonBuiltInOperation) == "{}" { // empty struct dst.BuiltInOperation = nil } else { - match++ + return nil } } else { dst.BuiltInOperation = nil @@ -45,28 +44,18 @@ func (dst *AttributeToUpdate) UnmarshalJSON(data []byte) error { // try to unmarshal data into String err = newStrictDecoder(data).Decode(&dst.String) - if err == nil { + if err == nil && validateStruct(dst.String) == nil { jsonString, _ := json.Marshal(dst.String) if string(jsonString) == "{}" { // empty struct dst.String = nil } else { - match++ + return nil } } else { dst.String = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.BuiltInOperation = nil - dst.String = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(AttributeToUpdate)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(AttributeToUpdate)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(AttributeToUpdate)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/search/model_automatic_facet_filter.go b/clients/algoliasearch-client-go/algolia/search/model_automatic_facet_filter.go index e59af0d1a4..14a264a11d 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_automatic_facet_filter.go +++ b/clients/algoliasearch-client-go/algolia/search/model_automatic_facet_filter.go @@ -9,7 +9,7 @@ import ( // AutomaticFacetFilter Automatic facet Filter. type AutomaticFacetFilter struct { // Attribute to filter on. This must match a facet placeholder in the Rule's pattern. - Facet string `json:"facet"` + Facet string `json:"facet" validate:"required"` // Score for the filter. Typically used for optional or disjunctive filters. Score *int32 `json:"score,omitempty"` // Whether the filter is disjunctive (true) or conjunctive (false). diff --git a/clients/algoliasearch-client-go/algolia/search/model_automatic_facet_filters.go b/clients/algoliasearch-client-go/algolia/search/model_automatic_facet_filters.go index 228d530567..33258bafa5 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_automatic_facet_filters.go +++ b/clients/algoliasearch-client-go/algolia/search/model_automatic_facet_filters.go @@ -29,15 +29,14 @@ func ArrayOfStringAsAutomaticFacetFilters(v *[]string) AutomaticFacetFilters { // Unmarshal JSON data into one of the pointers in the struct func (dst *AutomaticFacetFilters) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into ArrayOfAutomaticFacetFilter err = newStrictDecoder(data).Decode(&dst.ArrayOfAutomaticFacetFilter) - if err == nil { + if err == nil && validateStruct(dst.ArrayOfAutomaticFacetFilter) == nil { jsonArrayOfAutomaticFacetFilter, _ := json.Marshal(dst.ArrayOfAutomaticFacetFilter) if string(jsonArrayOfAutomaticFacetFilter) == "{}" { // empty struct dst.ArrayOfAutomaticFacetFilter = nil } else { - match++ + return nil } } else { dst.ArrayOfAutomaticFacetFilter = nil @@ -45,28 +44,18 @@ func (dst *AutomaticFacetFilters) UnmarshalJSON(data []byte) error { // try to unmarshal data into ArrayOfString err = newStrictDecoder(data).Decode(&dst.ArrayOfString) - if err == nil { + if err == nil && validateStruct(dst.ArrayOfString) == nil { jsonArrayOfString, _ := json.Marshal(dst.ArrayOfString) if string(jsonArrayOfString) == "{}" { // empty struct dst.ArrayOfString = nil } else { - match++ + return nil } } else { dst.ArrayOfString = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.ArrayOfAutomaticFacetFilter = nil - dst.ArrayOfString = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(AutomaticFacetFilters)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(AutomaticFacetFilters)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(AutomaticFacetFilters)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/search/model_base_get_api_key_response.go b/clients/algoliasearch-client-go/algolia/search/model_base_get_api_key_response.go index a51944d576..bfe5f39fdc 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_base_get_api_key_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_base_get_api_key_response.go @@ -11,7 +11,7 @@ type BaseGetApiKeyResponse struct { // The API key. Value *string `json:"value,omitempty"` // Time of the event expressed in milliseconds since the Unix epoch. - CreatedAt int64 `json:"createdAt"` + CreatedAt int64 `json:"createdAt" validate:"required"` } type BaseGetApiKeyResponseOption func(f *BaseGetApiKeyResponse) diff --git a/clients/algoliasearch-client-go/algolia/search/model_base_search_response.go b/clients/algoliasearch-client-go/algolia/search/model_base_search_response.go index eeca83787d..230628c4a4 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_base_search_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_base_search_response.go @@ -19,7 +19,7 @@ type BaseSearchResponse struct { // Whether the facet count is exhaustive or approximate. ExhaustiveFacetsCount *bool `json:"exhaustiveFacetsCount,omitempty"` // Indicate if the nbHits count was exhaustive or approximate. - ExhaustiveNbHits bool `json:"exhaustiveNbHits"` + ExhaustiveNbHits bool `json:"exhaustiveNbHits" validate:"required"` // Indicate if the typo-tolerance search was exhaustive or approximate (only included when typo-tolerance is enabled). ExhaustiveTypo *bool `json:"exhaustiveTypo,omitempty"` // A mapping of each facet name to the corresponding facet counts. @@ -27,7 +27,7 @@ type BaseSearchResponse struct { // Statistics for numerical facets. FacetsStats *map[string]FacetsStats `json:"facets_stats,omitempty"` // Set the number of hits per page. - HitsPerPage int32 `json:"hitsPerPage"` + HitsPerPage int32 `json:"hitsPerPage" validate:"required"` // Index name used for the query. Index *string `json:"index,omitempty"` // Index name used for the query. In the case of an A/B test, the targeted index isn't always the index used by the query. @@ -35,22 +35,22 @@ type BaseSearchResponse struct { // Used to return warnings about the query. Message *string `json:"message,omitempty"` // Number of hits that the search query matched. - NbHits int32 `json:"nbHits"` + NbHits int32 `json:"nbHits" validate:"required"` // Number of pages available for the current query. - NbPages int32 `json:"nbPages"` + NbPages int32 `json:"nbPages" validate:"required"` // The number of hits selected and sorted by the relevant sort algorithm. NbSortedHits *int32 `json:"nbSortedHits,omitempty"` // Specify the page to retrieve. - Page int32 `json:"page"` + Page int32 `json:"page" validate:"required"` // A url-encoded string of all search parameters. - Params string `json:"params"` + Params string `json:"params" validate:"required"` Redirect *BaseSearchResponseRedirect `json:"redirect,omitempty"` // The query string that will be searched, after normalization. ParsedQuery *string `json:"parsedQuery,omitempty"` // Time the server took to process the request, in milliseconds. - ProcessingTimeMS int32 `json:"processingTimeMS"` + ProcessingTimeMS int32 `json:"processingTimeMS" validate:"required"` // The text to search in the index. - Query string `json:"query"` + Query string `json:"query" validate:"required"` // A markup text indicating which parts of the original query have been removed in order to retrieve a non-empty result set. QueryAfterRemoval *string `json:"queryAfterRemoval,omitempty"` // Actual host name of the server that processed the request. diff --git a/clients/algoliasearch-client-go/algolia/search/model_batch_assign_user_ids_params.go b/clients/algoliasearch-client-go/algolia/search/model_batch_assign_user_ids_params.go index bc89e8245f..6ed3834943 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_batch_assign_user_ids_params.go +++ b/clients/algoliasearch-client-go/algolia/search/model_batch_assign_user_ids_params.go @@ -9,9 +9,9 @@ import ( // BatchAssignUserIdsParams Assign userID parameters. type BatchAssignUserIdsParams struct { // Name of the cluster. - Cluster string `json:"cluster"` + Cluster string `json:"cluster" validate:"required"` // userIDs to assign. Note you cannot move users with this method. - Users []string `json:"users"` + Users []string `json:"users" validate:"required"` } // NewBatchAssignUserIdsParams instantiates a new BatchAssignUserIdsParams object diff --git a/clients/algoliasearch-client-go/algolia/search/model_batch_dictionary_entries_params.go b/clients/algoliasearch-client-go/algolia/search/model_batch_dictionary_entries_params.go index c42429230b..3a59c83670 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_batch_dictionary_entries_params.go +++ b/clients/algoliasearch-client-go/algolia/search/model_batch_dictionary_entries_params.go @@ -11,7 +11,7 @@ type BatchDictionaryEntriesParams struct { // When `true`, start the batch by removing all the custom entries from the dictionary. ClearExistingDictionaryEntries *bool `json:"clearExistingDictionaryEntries,omitempty"` // List of operations to batch. Each operation is described by an `action` and a `body`. - Requests []BatchDictionaryEntriesRequest `json:"requests"` + Requests []BatchDictionaryEntriesRequest `json:"requests" validate:"required"` } type BatchDictionaryEntriesParamsOption func(f *BatchDictionaryEntriesParams) diff --git a/clients/algoliasearch-client-go/algolia/search/model_batch_dictionary_entries_request.go b/clients/algoliasearch-client-go/algolia/search/model_batch_dictionary_entries_request.go index 8749f6fafe..6da97d06a9 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_batch_dictionary_entries_request.go +++ b/clients/algoliasearch-client-go/algolia/search/model_batch_dictionary_entries_request.go @@ -8,8 +8,8 @@ import ( // BatchDictionaryEntriesRequest struct for BatchDictionaryEntriesRequest type BatchDictionaryEntriesRequest struct { - Action DictionaryAction `json:"action"` - Body DictionaryEntry `json:"body"` + Action DictionaryAction `json:"action" validate:"required"` + Body DictionaryEntry `json:"body" validate:"required"` } // NewBatchDictionaryEntriesRequest instantiates a new BatchDictionaryEntriesRequest object diff --git a/clients/algoliasearch-client-go/algolia/search/model_batch_params.go b/clients/algoliasearch-client-go/algolia/search/model_batch_params.go index 034ef1a3a3..93772bbad2 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_batch_params.go +++ b/clients/algoliasearch-client-go/algolia/search/model_batch_params.go @@ -8,7 +8,7 @@ import ( // BatchParams The `multipleBatch` parameters. type BatchParams struct { - Requests []MultipleBatchRequest `json:"requests"` + Requests []MultipleBatchRequest `json:"requests" validate:"required"` } // NewBatchParams instantiates a new BatchParams object diff --git a/clients/algoliasearch-client-go/algolia/search/model_batch_request.go b/clients/algoliasearch-client-go/algolia/search/model_batch_request.go index 12193d7751..729075147e 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_batch_request.go +++ b/clients/algoliasearch-client-go/algolia/search/model_batch_request.go @@ -8,9 +8,9 @@ import ( // BatchRequest struct for BatchRequest type BatchRequest struct { - Action Action `json:"action"` + Action Action `json:"action" validate:"required"` // arguments to the operation (depends on the type of the operation). - Body map[string]interface{} `json:"body"` + Body map[string]interface{} `json:"body" validate:"required"` } // NewBatchRequest instantiates a new BatchRequest object diff --git a/clients/algoliasearch-client-go/algolia/search/model_batch_response.go b/clients/algoliasearch-client-go/algolia/search/model_batch_response.go index 7c855ca917..d3010c4faa 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_batch_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_batch_response.go @@ -9,9 +9,9 @@ import ( // BatchResponse struct for BatchResponse type BatchResponse struct { // taskID of the task to wait for. - TaskID int64 `json:"taskID"` + TaskID int64 `json:"taskID" validate:"required"` // List of objectID. - ObjectIDs []string `json:"objectIDs"` + ObjectIDs []string `json:"objectIDs" validate:"required"` } // NewBatchResponse instantiates a new BatchResponse object diff --git a/clients/algoliasearch-client-go/algolia/search/model_batch_write_params.go b/clients/algoliasearch-client-go/algolia/search/model_batch_write_params.go index 15686e43bd..f1e8623a3b 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_batch_write_params.go +++ b/clients/algoliasearch-client-go/algolia/search/model_batch_write_params.go @@ -8,7 +8,7 @@ import ( // BatchWriteParams The `batch` parameters. type BatchWriteParams struct { - Requests []BatchRequest `json:"requests"` + Requests []BatchRequest `json:"requests" validate:"required"` } // NewBatchWriteParams instantiates a new BatchWriteParams object diff --git a/clients/algoliasearch-client-go/algolia/search/model_browse_params.go b/clients/algoliasearch-client-go/algolia/search/model_browse_params.go index dab5d91248..2fb35d8aae 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_browse_params.go +++ b/clients/algoliasearch-client-go/algolia/search/model_browse_params.go @@ -29,15 +29,14 @@ func SearchParamsStringAsBrowseParams(v *SearchParamsString) BrowseParams { // Unmarshal JSON data into one of the pointers in the struct func (dst *BrowseParams) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into BrowseParamsObject err = newStrictDecoder(data).Decode(&dst.BrowseParamsObject) - if err == nil { + if err == nil && validateStruct(dst.BrowseParamsObject) == nil { jsonBrowseParamsObject, _ := json.Marshal(dst.BrowseParamsObject) if string(jsonBrowseParamsObject) == "{}" { // empty struct dst.BrowseParamsObject = nil } else { - match++ + return nil } } else { dst.BrowseParamsObject = nil @@ -45,28 +44,18 @@ func (dst *BrowseParams) UnmarshalJSON(data []byte) error { // try to unmarshal data into SearchParamsString err = newStrictDecoder(data).Decode(&dst.SearchParamsString) - if err == nil { + if err == nil && validateStruct(dst.SearchParamsString) == nil { jsonSearchParamsString, _ := json.Marshal(dst.SearchParamsString) if string(jsonSearchParamsString) == "{}" { // empty struct dst.SearchParamsString = nil } else { - match++ + return nil } } else { dst.SearchParamsString = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.BrowseParamsObject = nil - dst.SearchParamsString = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(BrowseParams)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(BrowseParams)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(BrowseParams)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/search/model_browse_response.go b/clients/algoliasearch-client-go/algolia/search/model_browse_response.go index f8ee1c9c97..c2c597060f 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_browse_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_browse_response.go @@ -19,7 +19,7 @@ type BrowseResponse struct { // Whether the facet count is exhaustive or approximate. ExhaustiveFacetsCount *bool `json:"exhaustiveFacetsCount,omitempty"` // Indicate if the nbHits count was exhaustive or approximate. - ExhaustiveNbHits bool `json:"exhaustiveNbHits"` + ExhaustiveNbHits bool `json:"exhaustiveNbHits" validate:"required"` // Indicate if the typo-tolerance search was exhaustive or approximate (only included when typo-tolerance is enabled). ExhaustiveTypo *bool `json:"exhaustiveTypo,omitempty"` // A mapping of each facet name to the corresponding facet counts. @@ -27,7 +27,7 @@ type BrowseResponse struct { // Statistics for numerical facets. FacetsStats *map[string]FacetsStats `json:"facets_stats,omitempty"` // Set the number of hits per page. - HitsPerPage int32 `json:"hitsPerPage"` + HitsPerPage int32 `json:"hitsPerPage" validate:"required"` // Index name used for the query. Index *string `json:"index,omitempty"` // Index name used for the query. In the case of an A/B test, the targeted index isn't always the index used by the query. @@ -35,22 +35,22 @@ type BrowseResponse struct { // Used to return warnings about the query. Message *string `json:"message,omitempty"` // Number of hits that the search query matched. - NbHits int32 `json:"nbHits"` + NbHits int32 `json:"nbHits" validate:"required"` // Number of pages available for the current query. - NbPages int32 `json:"nbPages"` + NbPages int32 `json:"nbPages" validate:"required"` // The number of hits selected and sorted by the relevant sort algorithm. NbSortedHits *int32 `json:"nbSortedHits,omitempty"` // Specify the page to retrieve. - Page int32 `json:"page"` + Page int32 `json:"page" validate:"required"` // A url-encoded string of all search parameters. - Params string `json:"params"` + Params string `json:"params" validate:"required"` Redirect *BaseSearchResponseRedirect `json:"redirect,omitempty"` // The query string that will be searched, after normalization. ParsedQuery *string `json:"parsedQuery,omitempty"` // Time the server took to process the request, in milliseconds. - ProcessingTimeMS int32 `json:"processingTimeMS"` + ProcessingTimeMS int32 `json:"processingTimeMS" validate:"required"` // The text to search in the index. - Query string `json:"query"` + Query string `json:"query" validate:"required"` // A markup text indicating which parts of the original query have been removed in order to retrieve a non-empty result set. QueryAfterRemoval *string `json:"queryAfterRemoval,omitempty"` // Actual host name of the server that processed the request. @@ -58,7 +58,7 @@ type BrowseResponse struct { // Lets you store custom data in your indices. UserData map[string]interface{} `json:"userData,omitempty"` RenderingContent *RenderingContent `json:"renderingContent,omitempty"` - Hits []Hit `json:"hits"` + Hits []Hit `json:"hits" validate:"required"` // Cursor indicating the location to resume browsing from. Must match the value returned by the previous call. Cursor *string `json:"cursor,omitempty"` } diff --git a/clients/algoliasearch-client-go/algolia/search/model_built_in_operation.go b/clients/algoliasearch-client-go/algolia/search/model_built_in_operation.go index aae090161c..45c5ff84b0 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_built_in_operation.go +++ b/clients/algoliasearch-client-go/algolia/search/model_built_in_operation.go @@ -8,9 +8,9 @@ import ( // BuiltInOperation To update an attribute without pushing the entire record, you can use these built-in operations. type BuiltInOperation struct { - Operation BuiltInOperationType `json:"_operation"` + Operation BuiltInOperationType `json:"_operation" validate:"required"` // the right-hand side argument to the operation, for example, increment or decrement step, value to add or remove. - Value string `json:"value"` + Value string `json:"value" validate:"required"` } // NewBuiltInOperation instantiates a new BuiltInOperation object diff --git a/clients/algoliasearch-client-go/algolia/search/model_consequence_hide.go b/clients/algoliasearch-client-go/algolia/search/model_consequence_hide.go index 3ba422a8a7..acceb3ef5b 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_consequence_hide.go +++ b/clients/algoliasearch-client-go/algolia/search/model_consequence_hide.go @@ -9,7 +9,7 @@ import ( // ConsequenceHide Unique identifier of the object to hide. type ConsequenceHide struct { // Unique identifier of the object. - ObjectID string `json:"objectID"` + ObjectID string `json:"objectID" validate:"required"` } // NewConsequenceHide instantiates a new ConsequenceHide object diff --git a/clients/algoliasearch-client-go/algolia/search/model_consequence_query.go b/clients/algoliasearch-client-go/algolia/search/model_consequence_query.go index c3f51c258e..389f37fca6 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_consequence_query.go +++ b/clients/algoliasearch-client-go/algolia/search/model_consequence_query.go @@ -29,15 +29,14 @@ func StringAsConsequenceQuery(v *string) ConsequenceQuery { // Unmarshal JSON data into one of the pointers in the struct func (dst *ConsequenceQuery) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into ConsequenceQueryObject err = newStrictDecoder(data).Decode(&dst.ConsequenceQueryObject) - if err == nil { + if err == nil && validateStruct(dst.ConsequenceQueryObject) == nil { jsonConsequenceQueryObject, _ := json.Marshal(dst.ConsequenceQueryObject) if string(jsonConsequenceQueryObject) == "{}" { // empty struct dst.ConsequenceQueryObject = nil } else { - match++ + return nil } } else { dst.ConsequenceQueryObject = nil @@ -45,28 +44,18 @@ func (dst *ConsequenceQuery) UnmarshalJSON(data []byte) error { // try to unmarshal data into String err = newStrictDecoder(data).Decode(&dst.String) - if err == nil { + if err == nil && validateStruct(dst.String) == nil { jsonString, _ := json.Marshal(dst.String) if string(jsonString) == "{}" { // empty struct dst.String = nil } else { - match++ + return nil } } else { dst.String = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.ConsequenceQueryObject = nil - dst.String = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(ConsequenceQuery)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(ConsequenceQuery)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(ConsequenceQuery)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/search/model_created_at_response.go b/clients/algoliasearch-client-go/algolia/search/model_created_at_response.go index 1ad3614fde..7a50615728 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_created_at_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_created_at_response.go @@ -9,7 +9,7 @@ import ( // CreatedAtResponse The response with a createdAt timestamp. type CreatedAtResponse struct { // Date of creation (ISO-8601 format). - CreatedAt string `json:"createdAt"` + CreatedAt string `json:"createdAt" validate:"required"` } // NewCreatedAtResponse instantiates a new CreatedAtResponse object diff --git a/clients/algoliasearch-client-go/algolia/search/model_delete_api_key_response.go b/clients/algoliasearch-client-go/algolia/search/model_delete_api_key_response.go index 80634302d8..fff0041711 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_delete_api_key_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_delete_api_key_response.go @@ -9,7 +9,7 @@ import ( // DeleteApiKeyResponse struct for DeleteApiKeyResponse type DeleteApiKeyResponse struct { // Date of deletion (ISO-8601 format). - DeletedAt string `json:"deletedAt"` + DeletedAt string `json:"deletedAt" validate:"required"` } // NewDeleteApiKeyResponse instantiates a new DeleteApiKeyResponse object diff --git a/clients/algoliasearch-client-go/algolia/search/model_delete_source_response.go b/clients/algoliasearch-client-go/algolia/search/model_delete_source_response.go index 0b4059f5e0..3febfdecd1 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_delete_source_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_delete_source_response.go @@ -9,7 +9,7 @@ import ( // DeleteSourceResponse struct for DeleteSourceResponse type DeleteSourceResponse struct { // Date of deletion (ISO-8601 format). - DeletedAt string `json:"deletedAt"` + DeletedAt string `json:"deletedAt" validate:"required"` } // NewDeleteSourceResponse instantiates a new DeleteSourceResponse object diff --git a/clients/algoliasearch-client-go/algolia/search/model_deleted_at_response.go b/clients/algoliasearch-client-go/algolia/search/model_deleted_at_response.go index 2c327f097c..94ac6cce57 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_deleted_at_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_deleted_at_response.go @@ -9,9 +9,9 @@ import ( // DeletedAtResponse The response with a taskID and a deletedAt timestamp. type DeletedAtResponse struct { // taskID of the task to wait for. - TaskID int64 `json:"taskID"` + TaskID int64 `json:"taskID" validate:"required"` // Date of deletion (ISO-8601 format). - DeletedAt string `json:"deletedAt"` + DeletedAt string `json:"deletedAt" validate:"required"` } // NewDeletedAtResponse instantiates a new DeletedAtResponse object diff --git a/clients/algoliasearch-client-go/algolia/search/model_dictionary_entry.go b/clients/algoliasearch-client-go/algolia/search/model_dictionary_entry.go index ba9faab7d2..8556970b18 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_dictionary_entry.go +++ b/clients/algoliasearch-client-go/algolia/search/model_dictionary_entry.go @@ -9,9 +9,9 @@ import ( // DictionaryEntry A dictionary entry. type DictionaryEntry struct { // Unique identifier of the object. - ObjectID string `json:"objectID"` + ObjectID string `json:"objectID" validate:"required"` // Language ISO code supported by the dictionary (e.g., \"en\" for English). - Language string `json:"language"` + Language string `json:"language" validate:"required"` // The word of the dictionary entry. Word *string `json:"word,omitempty"` // The words of the dictionary entry. diff --git a/clients/algoliasearch-client-go/algolia/search/model_dictionary_settings_params.go b/clients/algoliasearch-client-go/algolia/search/model_dictionary_settings_params.go index 38a057ab30..6e47000543 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_dictionary_settings_params.go +++ b/clients/algoliasearch-client-go/algolia/search/model_dictionary_settings_params.go @@ -8,7 +8,7 @@ import ( // DictionarySettingsParams Disable the builtin Algolia entries for a type of dictionary per language. type DictionarySettingsParams struct { - DisableStandardEntries StandardEntries `json:"disableStandardEntries"` + DisableStandardEntries StandardEntries `json:"disableStandardEntries" validate:"required"` } // NewDictionarySettingsParams instantiates a new DictionarySettingsParams object diff --git a/clients/algoliasearch-client-go/algolia/search/model_distinct.go b/clients/algoliasearch-client-go/algolia/search/model_distinct.go index bb3acc56af..1b31757250 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_distinct.go +++ b/clients/algoliasearch-client-go/algolia/search/model_distinct.go @@ -29,15 +29,14 @@ func Int32AsDistinct(v *int32) Distinct { // Unmarshal JSON data into one of the pointers in the struct func (dst *Distinct) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into Bool err = newStrictDecoder(data).Decode(&dst.Bool) - if err == nil { + if err == nil && validateStruct(dst.Bool) == nil { jsonBool, _ := json.Marshal(dst.Bool) if string(jsonBool) == "{}" { // empty struct dst.Bool = nil } else { - match++ + return nil } } else { dst.Bool = nil @@ -45,28 +44,18 @@ func (dst *Distinct) UnmarshalJSON(data []byte) error { // try to unmarshal data into Int32 err = newStrictDecoder(data).Decode(&dst.Int32) - if err == nil { + if err == nil && validateStruct(dst.Int32) == nil { jsonInt32, _ := json.Marshal(dst.Int32) if string(jsonInt32) == "{}" { // empty struct dst.Int32 = nil } else { - match++ + return nil } } else { dst.Int32 = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.Bool = nil - dst.Int32 = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(Distinct)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(Distinct)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(Distinct)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/search/model_facet_filters.go b/clients/algoliasearch-client-go/algolia/search/model_facet_filters.go index bf9728f1ac..81b69cdfc7 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_facet_filters.go +++ b/clients/algoliasearch-client-go/algolia/search/model_facet_filters.go @@ -29,15 +29,14 @@ func StringAsFacetFilters(v *string) FacetFilters { // Unmarshal JSON data into one of the pointers in the struct func (dst *FacetFilters) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into ArrayOfMixedSearchFilters err = newStrictDecoder(data).Decode(&dst.ArrayOfMixedSearchFilters) - if err == nil { + if err == nil && validateStruct(dst.ArrayOfMixedSearchFilters) == nil { jsonArrayOfMixedSearchFilters, _ := json.Marshal(dst.ArrayOfMixedSearchFilters) if string(jsonArrayOfMixedSearchFilters) == "{}" { // empty struct dst.ArrayOfMixedSearchFilters = nil } else { - match++ + return nil } } else { dst.ArrayOfMixedSearchFilters = nil @@ -45,28 +44,18 @@ func (dst *FacetFilters) UnmarshalJSON(data []byte) error { // try to unmarshal data into String err = newStrictDecoder(data).Decode(&dst.String) - if err == nil { + if err == nil && validateStruct(dst.String) == nil { jsonString, _ := json.Marshal(dst.String) if string(jsonString) == "{}" { // empty struct dst.String = nil } else { - match++ + return nil } } else { dst.String = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.ArrayOfMixedSearchFilters = nil - dst.String = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(FacetFilters)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(FacetFilters)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(FacetFilters)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/search/model_facet_hits.go b/clients/algoliasearch-client-go/algolia/search/model_facet_hits.go index 91ec5c2acd..f195a3adf1 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_facet_hits.go +++ b/clients/algoliasearch-client-go/algolia/search/model_facet_hits.go @@ -9,11 +9,11 @@ import ( // FacetHits struct for FacetHits type FacetHits struct { // Raw value of the facet. - Value string `json:"value"` + Value string `json:"value" validate:"required"` // Markup text with occurrences highlighted. - Highlighted string `json:"highlighted"` + Highlighted string `json:"highlighted" validate:"required"` // How many objects contain this facet value. This takes into account the extra search parameters specified in the query. Like for a regular search query, the counts may not be exhaustive. - Count int32 `json:"count"` + Count int32 `json:"count" validate:"required"` } // NewFacetHits instantiates a new FacetHits object diff --git a/clients/algoliasearch-client-go/algolia/search/model_fetched_index.go b/clients/algoliasearch-client-go/algolia/search/model_fetched_index.go index 1629642fdb..f51f14c65c 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_fetched_index.go +++ b/clients/algoliasearch-client-go/algolia/search/model_fetched_index.go @@ -9,23 +9,23 @@ import ( // FetchedIndex struct for FetchedIndex type FetchedIndex struct { // Index name. - Name string `json:"name"` + Name string `json:"name" validate:"required"` // Index creation date. An empty string means that the index has no records. - CreatedAt string `json:"createdAt"` + CreatedAt string `json:"createdAt" validate:"required"` // Date of last update (ISO-8601 format). - UpdatedAt string `json:"updatedAt"` + UpdatedAt string `json:"updatedAt" validate:"required"` // Number of records contained in the index. - Entries int32 `json:"entries"` + Entries int32 `json:"entries" validate:"required"` // Number of bytes of the index in minified format. - DataSize int32 `json:"dataSize"` + DataSize int32 `json:"dataSize" validate:"required"` // Number of bytes of the index binary file. - FileSize int32 `json:"fileSize"` + FileSize int32 `json:"fileSize" validate:"required"` // Last build time. - LastBuildTimeS int32 `json:"lastBuildTimeS"` + LastBuildTimeS int32 `json:"lastBuildTimeS" validate:"required"` // Number of pending indexing operations. This value is deprecated and should not be used. - NumberOfPendingTasks int32 `json:"numberOfPendingTasks"` + NumberOfPendingTasks int32 `json:"numberOfPendingTasks" validate:"required"` // A boolean which says whether the index has pending tasks. This value is deprecated and should not be used. - PendingTask bool `json:"pendingTask"` + PendingTask bool `json:"pendingTask" validate:"required"` // Only present if the index is a replica. Contains the name of the related primary index. Primary *string `json:"primary,omitempty"` // Only present if the index is a primary index with replicas. Contains the names of all linked replicas. diff --git a/clients/algoliasearch-client-go/algolia/search/model_get_api_key_response.go b/clients/algoliasearch-client-go/algolia/search/model_get_api_key_response.go index 7523b0f214..44b877c93b 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_get_api_key_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_get_api_key_response.go @@ -11,9 +11,9 @@ type GetApiKeyResponse struct { // The API key. Value *string `json:"value,omitempty"` // Time of the event expressed in milliseconds since the Unix epoch. - CreatedAt int64 `json:"createdAt"` + CreatedAt int64 `json:"createdAt" validate:"required"` // Set of permissions associated with the key. - Acl []Acl `json:"acl"` + Acl []Acl `json:"acl" validate:"required"` // A comment used to identify a key more easily in the dashboard. It is not interpreted by the API. Description *string `json:"description,omitempty"` // Restrict this new API key to a list of indices or index patterns. If the list is empty, all indices are allowed. diff --git a/clients/algoliasearch-client-go/algolia/search/model_get_dictionary_settings_response.go b/clients/algoliasearch-client-go/algolia/search/model_get_dictionary_settings_response.go index c39e81f6e6..8c48f3f36c 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_get_dictionary_settings_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_get_dictionary_settings_response.go @@ -8,7 +8,7 @@ import ( // GetDictionarySettingsResponse struct for GetDictionarySettingsResponse type GetDictionarySettingsResponse struct { - DisableStandardEntries StandardEntries `json:"disableStandardEntries"` + DisableStandardEntries StandardEntries `json:"disableStandardEntries" validate:"required"` } // NewGetDictionarySettingsResponse instantiates a new GetDictionarySettingsResponse object diff --git a/clients/algoliasearch-client-go/algolia/search/model_get_logs_response.go b/clients/algoliasearch-client-go/algolia/search/model_get_logs_response.go index 164dd8b1a6..734aca8303 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_get_logs_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_get_logs_response.go @@ -8,7 +8,7 @@ import ( // GetLogsResponse struct for GetLogsResponse type GetLogsResponse struct { - Logs []Log `json:"logs"` + Logs []Log `json:"logs" validate:"required"` } // NewGetLogsResponse instantiates a new GetLogsResponse object diff --git a/clients/algoliasearch-client-go/algolia/search/model_get_objects_params.go b/clients/algoliasearch-client-go/algolia/search/model_get_objects_params.go index 1c76f9424b..e06833a01f 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_get_objects_params.go +++ b/clients/algoliasearch-client-go/algolia/search/model_get_objects_params.go @@ -8,7 +8,7 @@ import ( // GetObjectsParams The `getObjects` parameters. type GetObjectsParams struct { - Requests []GetObjectsRequest `json:"requests"` + Requests []GetObjectsRequest `json:"requests" validate:"required"` } // NewGetObjectsParams instantiates a new GetObjectsParams object diff --git a/clients/algoliasearch-client-go/algolia/search/model_get_objects_request.go b/clients/algoliasearch-client-go/algolia/search/model_get_objects_request.go index 3b603e673f..149f53e6e1 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_get_objects_request.go +++ b/clients/algoliasearch-client-go/algolia/search/model_get_objects_request.go @@ -11,9 +11,9 @@ type GetObjectsRequest struct { // List of attributes to retrieve. By default, all retrievable attributes are returned. AttributesToRetrieve []string `json:"attributesToRetrieve,omitempty"` // ID of the object within that index. - ObjectID string `json:"objectID"` + ObjectID string `json:"objectID" validate:"required"` // name of the index containing the object. - IndexName string `json:"indexName"` + IndexName string `json:"indexName" validate:"required"` } type GetObjectsRequestOption func(f *GetObjectsRequest) diff --git a/clients/algoliasearch-client-go/algolia/search/model_get_objects_response.go b/clients/algoliasearch-client-go/algolia/search/model_get_objects_response.go index 85cd6206b5..3e72f41ee7 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_get_objects_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_get_objects_response.go @@ -9,7 +9,7 @@ import ( // GetObjectsResponse struct for GetObjectsResponse type GetObjectsResponse struct { // List of results fetched. - Results []map[string]interface{} `json:"results"` + Results []map[string]interface{} `json:"results" validate:"required"` } // NewGetObjectsResponse instantiates a new GetObjectsResponse object diff --git a/clients/algoliasearch-client-go/algolia/search/model_get_task_response.go b/clients/algoliasearch-client-go/algolia/search/model_get_task_response.go index 357982844b..f086a67958 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_get_task_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_get_task_response.go @@ -8,7 +8,7 @@ import ( // GetTaskResponse struct for GetTaskResponse type GetTaskResponse struct { - Status TaskStatus `json:"status"` + Status TaskStatus `json:"status" validate:"required"` } // NewGetTaskResponse instantiates a new GetTaskResponse object diff --git a/clients/algoliasearch-client-go/algolia/search/model_get_top_user_ids_response.go b/clients/algoliasearch-client-go/algolia/search/model_get_top_user_ids_response.go index 6e47229318..df32b4b7aa 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_get_top_user_ids_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_get_top_user_ids_response.go @@ -9,7 +9,7 @@ import ( // GetTopUserIdsResponse Array of userIDs and clusters. type GetTopUserIdsResponse struct { // Mapping of cluster names to top users. - TopUsers []map[string][]UserId `json:"topUsers"` + TopUsers []map[string][]UserId `json:"topUsers" validate:"required"` } // NewGetTopUserIdsResponse instantiates a new GetTopUserIdsResponse object diff --git a/clients/algoliasearch-client-go/algolia/search/model_has_pending_mappings_response.go b/clients/algoliasearch-client-go/algolia/search/model_has_pending_mappings_response.go index 2818430fd4..949d4b6ca7 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_has_pending_mappings_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_has_pending_mappings_response.go @@ -9,7 +9,7 @@ import ( // HasPendingMappingsResponse struct for HasPendingMappingsResponse type HasPendingMappingsResponse struct { // If there is any clusters with pending mapping state. - Pending bool `json:"pending"` + Pending bool `json:"pending" validate:"required"` // Describe cluster pending (migrating, creating, deleting) mapping state. Clusters *map[string][]string `json:"clusters,omitempty"` } diff --git a/clients/algoliasearch-client-go/algolia/search/model_highlight_result.go b/clients/algoliasearch-client-go/algolia/search/model_highlight_result.go index 5acae5b9c3..9ba494261a 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_highlight_result.go +++ b/clients/algoliasearch-client-go/algolia/search/model_highlight_result.go @@ -29,15 +29,14 @@ func ArrayOfHighlightResultOptionAsHighlightResult(v *[]HighlightResultOption) H // Unmarshal JSON data into one of the pointers in the struct func (dst *HighlightResult) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into HighlightResultOption err = newStrictDecoder(data).Decode(&dst.HighlightResultOption) - if err == nil { + if err == nil && validateStruct(dst.HighlightResultOption) == nil { jsonHighlightResultOption, _ := json.Marshal(dst.HighlightResultOption) if string(jsonHighlightResultOption) == "{}" { // empty struct dst.HighlightResultOption = nil } else { - match++ + return nil } } else { dst.HighlightResultOption = nil @@ -45,28 +44,18 @@ func (dst *HighlightResult) UnmarshalJSON(data []byte) error { // try to unmarshal data into ArrayOfHighlightResultOption err = newStrictDecoder(data).Decode(&dst.ArrayOfHighlightResultOption) - if err == nil { + if err == nil && validateStruct(dst.ArrayOfHighlightResultOption) == nil { jsonArrayOfHighlightResultOption, _ := json.Marshal(dst.ArrayOfHighlightResultOption) if string(jsonArrayOfHighlightResultOption) == "{}" { // empty struct dst.ArrayOfHighlightResultOption = nil } else { - match++ + return nil } } else { dst.ArrayOfHighlightResultOption = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.HighlightResultOption = nil - dst.ArrayOfHighlightResultOption = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(HighlightResult)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(HighlightResult)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(HighlightResult)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/search/model_highlight_result_option.go b/clients/algoliasearch-client-go/algolia/search/model_highlight_result_option.go index 2635170cdd..afca0776fd 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_highlight_result_option.go +++ b/clients/algoliasearch-client-go/algolia/search/model_highlight_result_option.go @@ -9,10 +9,10 @@ import ( // HighlightResultOption Show highlighted section and words matched on a query. type HighlightResultOption struct { // Markup text with occurrences highlighted. - Value string `json:"value"` - MatchLevel MatchLevel `json:"matchLevel"` + Value string `json:"value" validate:"required"` + MatchLevel MatchLevel `json:"matchLevel" validate:"required"` // List of words from the query that matched the object. - MatchedWords []string `json:"matchedWords"` + MatchedWords []string `json:"matchedWords" validate:"required"` // Whether the entire attribute value is highlighted. FullyHighlighted *bool `json:"fullyHighlighted,omitempty"` } diff --git a/clients/algoliasearch-client-go/algolia/search/model_hit.go b/clients/algoliasearch-client-go/algolia/search/model_hit.go index 28456d4608..6934e9ce4d 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_hit.go +++ b/clients/algoliasearch-client-go/algolia/search/model_hit.go @@ -9,7 +9,7 @@ import ( // Hit A single hit. type Hit struct { // Unique identifier of the object. - ObjectID string `json:"objectID"` + ObjectID string `json:"objectID" validate:"required"` // Show highlighted section and words matched on a query. HighlightResult *map[string]HighlightResult `json:"_highlightResult,omitempty"` // Snippeted attributes show parts of the matched attributes. Only returned when attributesToSnippet is non-empty. diff --git a/clients/algoliasearch-client-go/algolia/search/model_ignore_plurals.go b/clients/algoliasearch-client-go/algolia/search/model_ignore_plurals.go index 1d0b3077d3..2c89ab23a2 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_ignore_plurals.go +++ b/clients/algoliasearch-client-go/algolia/search/model_ignore_plurals.go @@ -29,15 +29,14 @@ func BoolAsIgnorePlurals(v *bool) IgnorePlurals { // Unmarshal JSON data into one of the pointers in the struct func (dst *IgnorePlurals) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into ArrayOfString err = newStrictDecoder(data).Decode(&dst.ArrayOfString) - if err == nil { + if err == nil && validateStruct(dst.ArrayOfString) == nil { jsonArrayOfString, _ := json.Marshal(dst.ArrayOfString) if string(jsonArrayOfString) == "{}" { // empty struct dst.ArrayOfString = nil } else { - match++ + return nil } } else { dst.ArrayOfString = nil @@ -45,28 +44,18 @@ func (dst *IgnorePlurals) UnmarshalJSON(data []byte) error { // try to unmarshal data into Bool err = newStrictDecoder(data).Decode(&dst.Bool) - if err == nil { + if err == nil && validateStruct(dst.Bool) == nil { jsonBool, _ := json.Marshal(dst.Bool) if string(jsonBool) == "{}" { // empty struct dst.Bool = nil } else { - match++ + return nil } } else { dst.Bool = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.ArrayOfString = nil - dst.Bool = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(IgnorePlurals)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(IgnorePlurals)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(IgnorePlurals)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/search/model_languages.go b/clients/algoliasearch-client-go/algolia/search/model_languages.go index 24765cc629..e7e9360611 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_languages.go +++ b/clients/algoliasearch-client-go/algolia/search/model_languages.go @@ -8,9 +8,9 @@ import ( // Languages A dictionary language. type Languages struct { - Plurals NullableDictionaryLanguage `json:"plurals"` - Stopwords NullableDictionaryLanguage `json:"stopwords"` - Compounds NullableDictionaryLanguage `json:"compounds"` + Plurals NullableDictionaryLanguage `json:"plurals" validate:"required"` + Stopwords NullableDictionaryLanguage `json:"stopwords" validate:"required"` + Compounds NullableDictionaryLanguage `json:"compounds" validate:"required"` } // NewLanguages instantiates a new Languages object diff --git a/clients/algoliasearch-client-go/algolia/search/model_list_api_keys_response.go b/clients/algoliasearch-client-go/algolia/search/model_list_api_keys_response.go index 792d4f67f4..e96cfa8dea 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_list_api_keys_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_list_api_keys_response.go @@ -9,7 +9,7 @@ import ( // ListApiKeysResponse struct for ListApiKeysResponse type ListApiKeysResponse struct { // List of api keys. - Keys []GetApiKeyResponse `json:"keys"` + Keys []GetApiKeyResponse `json:"keys" validate:"required"` } // NewListApiKeysResponse instantiates a new ListApiKeysResponse object diff --git a/clients/algoliasearch-client-go/algolia/search/model_list_clusters_response.go b/clients/algoliasearch-client-go/algolia/search/model_list_clusters_response.go index 9e79849f13..7df74ae91f 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_list_clusters_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_list_clusters_response.go @@ -9,7 +9,7 @@ import ( // ListClustersResponse Array of clusters. type ListClustersResponse struct { // Mapping of cluster names to top users. - TopUsers []string `json:"topUsers"` + TopUsers []string `json:"topUsers" validate:"required"` } // NewListClustersResponse instantiates a new ListClustersResponse object diff --git a/clients/algoliasearch-client-go/algolia/search/model_list_indices_response.go b/clients/algoliasearch-client-go/algolia/search/model_list_indices_response.go index ff6c3093e5..708012e681 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_list_indices_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_list_indices_response.go @@ -9,7 +9,7 @@ import ( // ListIndicesResponse struct for ListIndicesResponse type ListIndicesResponse struct { // List of the fetched indices. - Items []FetchedIndex `json:"items"` + Items []FetchedIndex `json:"items" validate:"required"` // Number of pages. NbPages *int32 `json:"nbPages,omitempty"` } diff --git a/clients/algoliasearch-client-go/algolia/search/model_list_user_ids_response.go b/clients/algoliasearch-client-go/algolia/search/model_list_user_ids_response.go index af900d5720..0f4a02ce25 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_list_user_ids_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_list_user_ids_response.go @@ -9,7 +9,7 @@ import ( // ListUserIdsResponse UserIDs data. type ListUserIdsResponse struct { // List of userIDs. - UserIDs []UserId `json:"userIDs"` + UserIDs []UserId `json:"userIDs" validate:"required"` } // NewListUserIdsResponse instantiates a new ListUserIdsResponse object diff --git a/clients/algoliasearch-client-go/algolia/search/model_log.go b/clients/algoliasearch-client-go/algolia/search/model_log.go index bb001ca62d..c4bdfbbbf3 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_log.go +++ b/clients/algoliasearch-client-go/algolia/search/model_log.go @@ -9,27 +9,27 @@ import ( // Log struct for Log type Log struct { // Timestamp in ISO-8601 format. - Timestamp string `json:"timestamp"` + Timestamp string `json:"timestamp" validate:"required"` // HTTP method of the performed request. - Method string `json:"method"` + Method string `json:"method" validate:"required"` // HTTP response code. - AnswerCode string `json:"answer_code"` + AnswerCode string `json:"answer_code" validate:"required"` // Request body. Truncated after 1000 characters. - QueryBody string `json:"query_body"` + QueryBody string `json:"query_body" validate:"required"` // Answer body. Truncated after 1000 characters. - Answer string `json:"answer"` + Answer string `json:"answer" validate:"required"` // Request URL. - Url string `json:"url"` + Url string `json:"url" validate:"required"` // IP of the client which performed the request. - Ip string `json:"ip"` + Ip string `json:"ip" validate:"required"` // Request Headers (API Key is obfuscated). - QueryHeaders string `json:"query_headers"` + QueryHeaders string `json:"query_headers" validate:"required"` // SHA1 signature of the log entry. - Sha1 string `json:"sha1"` + Sha1 string `json:"sha1" validate:"required"` // Number of API calls. - NbApiCalls string `json:"nb_api_calls"` + NbApiCalls string `json:"nb_api_calls" validate:"required"` // Processing time for the query. It doesn't include network time. - ProcessingTimeMs string `json:"processing_time_ms"` + ProcessingTimeMs string `json:"processing_time_ms" validate:"required"` // Index targeted by the query. Index *string `json:"index,omitempty"` // Query parameters sent with the request. diff --git a/clients/algoliasearch-client-go/algolia/search/model_mixed_search_filters.go b/clients/algoliasearch-client-go/algolia/search/model_mixed_search_filters.go index eca5ab73d8..c02e695f83 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_mixed_search_filters.go +++ b/clients/algoliasearch-client-go/algolia/search/model_mixed_search_filters.go @@ -29,15 +29,14 @@ func StringAsMixedSearchFilters(v *string) MixedSearchFilters { // Unmarshal JSON data into one of the pointers in the struct func (dst *MixedSearchFilters) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into ArrayOfString err = newStrictDecoder(data).Decode(&dst.ArrayOfString) - if err == nil { + if err == nil && validateStruct(dst.ArrayOfString) == nil { jsonArrayOfString, _ := json.Marshal(dst.ArrayOfString) if string(jsonArrayOfString) == "{}" { // empty struct dst.ArrayOfString = nil } else { - match++ + return nil } } else { dst.ArrayOfString = nil @@ -45,28 +44,18 @@ func (dst *MixedSearchFilters) UnmarshalJSON(data []byte) error { // try to unmarshal data into String err = newStrictDecoder(data).Decode(&dst.String) - if err == nil { + if err == nil && validateStruct(dst.String) == nil { jsonString, _ := json.Marshal(dst.String) if string(jsonString) == "{}" { // empty struct dst.String = nil } else { - match++ + return nil } } else { dst.String = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.ArrayOfString = nil - dst.String = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(MixedSearchFilters)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(MixedSearchFilters)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(MixedSearchFilters)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/search/model_multiple_batch_request.go b/clients/algoliasearch-client-go/algolia/search/model_multiple_batch_request.go index cfff9ff6f6..d75e27bf0d 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_multiple_batch_request.go +++ b/clients/algoliasearch-client-go/algolia/search/model_multiple_batch_request.go @@ -8,11 +8,11 @@ import ( // MultipleBatchRequest struct for MultipleBatchRequest type MultipleBatchRequest struct { - Action Action `json:"action"` + Action Action `json:"action" validate:"required"` // arguments to the operation (depends on the type of the operation). - Body map[string]interface{} `json:"body"` + Body map[string]interface{} `json:"body" validate:"required"` // Index to target for this operation. - IndexName string `json:"indexName"` + IndexName string `json:"indexName" validate:"required"` } // NewMultipleBatchRequest instantiates a new MultipleBatchRequest object diff --git a/clients/algoliasearch-client-go/algolia/search/model_multiple_batch_response.go b/clients/algoliasearch-client-go/algolia/search/model_multiple_batch_response.go index 0fbbcd53d1..6ae3c48abe 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_multiple_batch_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_multiple_batch_response.go @@ -9,9 +9,9 @@ import ( // MultipleBatchResponse struct for MultipleBatchResponse type MultipleBatchResponse struct { // List of tasksIDs per index. - TaskID map[string]int64 `json:"taskID"` + TaskID map[string]int64 `json:"taskID" validate:"required"` // List of objectID. - ObjectIDs []string `json:"objectIDs"` + ObjectIDs []string `json:"objectIDs" validate:"required"` } // NewMultipleBatchResponse instantiates a new MultipleBatchResponse object diff --git a/clients/algoliasearch-client-go/algolia/search/model_numeric_filters.go b/clients/algoliasearch-client-go/algolia/search/model_numeric_filters.go index 4fd04e9245..35859b9b6c 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_numeric_filters.go +++ b/clients/algoliasearch-client-go/algolia/search/model_numeric_filters.go @@ -29,15 +29,14 @@ func StringAsNumericFilters(v *string) NumericFilters { // Unmarshal JSON data into one of the pointers in the struct func (dst *NumericFilters) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into ArrayOfMixedSearchFilters err = newStrictDecoder(data).Decode(&dst.ArrayOfMixedSearchFilters) - if err == nil { + if err == nil && validateStruct(dst.ArrayOfMixedSearchFilters) == nil { jsonArrayOfMixedSearchFilters, _ := json.Marshal(dst.ArrayOfMixedSearchFilters) if string(jsonArrayOfMixedSearchFilters) == "{}" { // empty struct dst.ArrayOfMixedSearchFilters = nil } else { - match++ + return nil } } else { dst.ArrayOfMixedSearchFilters = nil @@ -45,28 +44,18 @@ func (dst *NumericFilters) UnmarshalJSON(data []byte) error { // try to unmarshal data into String err = newStrictDecoder(data).Decode(&dst.String) - if err == nil { + if err == nil && validateStruct(dst.String) == nil { jsonString, _ := json.Marshal(dst.String) if string(jsonString) == "{}" { // empty struct dst.String = nil } else { - match++ + return nil } } else { dst.String = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.ArrayOfMixedSearchFilters = nil - dst.String = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(NumericFilters)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(NumericFilters)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(NumericFilters)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/search/model_operation_index_params.go b/clients/algoliasearch-client-go/algolia/search/model_operation_index_params.go index 7bfc539bee..d29837cf63 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_operation_index_params.go +++ b/clients/algoliasearch-client-go/algolia/search/model_operation_index_params.go @@ -8,9 +8,9 @@ import ( // OperationIndexParams struct for OperationIndexParams type OperationIndexParams struct { - Operation OperationType `json:"operation"` + Operation OperationType `json:"operation" validate:"required"` // The Algolia index name. - Destination string `json:"destination"` + Destination string `json:"destination" validate:"required"` // Scope of the data to copy. When absent, a full copy is performed. When present, only the selected scopes are copied. Scope []ScopeType `json:"scope,omitempty"` } diff --git a/clients/algoliasearch-client-go/algolia/search/model_optional_filters.go b/clients/algoliasearch-client-go/algolia/search/model_optional_filters.go index efe4e1bebe..dd40848ba1 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_optional_filters.go +++ b/clients/algoliasearch-client-go/algolia/search/model_optional_filters.go @@ -29,15 +29,14 @@ func StringAsOptionalFilters(v *string) OptionalFilters { // Unmarshal JSON data into one of the pointers in the struct func (dst *OptionalFilters) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into ArrayOfMixedSearchFilters err = newStrictDecoder(data).Decode(&dst.ArrayOfMixedSearchFilters) - if err == nil { + if err == nil && validateStruct(dst.ArrayOfMixedSearchFilters) == nil { jsonArrayOfMixedSearchFilters, _ := json.Marshal(dst.ArrayOfMixedSearchFilters) if string(jsonArrayOfMixedSearchFilters) == "{}" { // empty struct dst.ArrayOfMixedSearchFilters = nil } else { - match++ + return nil } } else { dst.ArrayOfMixedSearchFilters = nil @@ -45,28 +44,18 @@ func (dst *OptionalFilters) UnmarshalJSON(data []byte) error { // try to unmarshal data into String err = newStrictDecoder(data).Decode(&dst.String) - if err == nil { + if err == nil && validateStruct(dst.String) == nil { jsonString, _ := json.Marshal(dst.String) if string(jsonString) == "{}" { // empty struct dst.String = nil } else { - match++ + return nil } } else { dst.String = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.ArrayOfMixedSearchFilters = nil - dst.String = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(OptionalFilters)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(OptionalFilters)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(OptionalFilters)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/search/model_promote.go b/clients/algoliasearch-client-go/algolia/search/model_promote.go index 50f2da9756..c378a6782a 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_promote.go +++ b/clients/algoliasearch-client-go/algolia/search/model_promote.go @@ -29,15 +29,14 @@ func PromoteObjectIDsAsPromote(v *PromoteObjectIDs) Promote { // Unmarshal JSON data into one of the pointers in the struct func (dst *Promote) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into PromoteObjectID err = newStrictDecoder(data).Decode(&dst.PromoteObjectID) - if err == nil { + if err == nil && validateStruct(dst.PromoteObjectID) == nil { jsonPromoteObjectID, _ := json.Marshal(dst.PromoteObjectID) if string(jsonPromoteObjectID) == "{}" { // empty struct dst.PromoteObjectID = nil } else { - match++ + return nil } } else { dst.PromoteObjectID = nil @@ -45,28 +44,18 @@ func (dst *Promote) UnmarshalJSON(data []byte) error { // try to unmarshal data into PromoteObjectIDs err = newStrictDecoder(data).Decode(&dst.PromoteObjectIDs) - if err == nil { + if err == nil && validateStruct(dst.PromoteObjectIDs) == nil { jsonPromoteObjectIDs, _ := json.Marshal(dst.PromoteObjectIDs) if string(jsonPromoteObjectIDs) == "{}" { // empty struct dst.PromoteObjectIDs = nil } else { - match++ + return nil } } else { dst.PromoteObjectIDs = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.PromoteObjectID = nil - dst.PromoteObjectIDs = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(Promote)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(Promote)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(Promote)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/search/model_promote_object_id.go b/clients/algoliasearch-client-go/algolia/search/model_promote_object_id.go index df6fdc1104..2e8c04d471 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_promote_object_id.go +++ b/clients/algoliasearch-client-go/algolia/search/model_promote_object_id.go @@ -9,9 +9,9 @@ import ( // PromoteObjectID Single objectID to promote as hits. type PromoteObjectID struct { // Unique identifier of the object to promote. - ObjectID string `json:"objectID"` + ObjectID string `json:"objectID" validate:"required"` // The position to promote the objects to (zero-based). If you pass objectIDs, the objects are placed at this position as a group. For example, if you pass four objectIDs to position 0, the objects take the first four positions. - Position int32 `json:"position"` + Position int32 `json:"position" validate:"required"` } // NewPromoteObjectID instantiates a new PromoteObjectID object diff --git a/clients/algoliasearch-client-go/algolia/search/model_promote_object_ids.go b/clients/algoliasearch-client-go/algolia/search/model_promote_object_ids.go index 550ff24eab..11103ba6c1 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_promote_object_ids.go +++ b/clients/algoliasearch-client-go/algolia/search/model_promote_object_ids.go @@ -9,9 +9,9 @@ import ( // PromoteObjectIDs Multiple objectIDs to promote as hits. type PromoteObjectIDs struct { // Array of unique identifiers of the objects to promote. - ObjectIDs []string `json:"objectIDs"` + ObjectIDs []string `json:"objectIDs" validate:"required"` // The position to promote the objects to (zero-based). If you pass objectIDs, the objects are placed at this position as a group. For example, if you pass four objectIDs to position 0, the objects take the first four positions. - Position int32 `json:"position"` + Position int32 `json:"position" validate:"required"` } // NewPromoteObjectIDs instantiates a new PromoteObjectIDs object diff --git a/clients/algoliasearch-client-go/algolia/search/model_ranking_info.go b/clients/algoliasearch-client-go/algolia/search/model_ranking_info.go index 088078731a..a510acf6f2 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_ranking_info.go +++ b/clients/algoliasearch-client-go/algolia/search/model_ranking_info.go @@ -9,27 +9,27 @@ import ( // RankingInfo struct for RankingInfo type RankingInfo struct { // This field is reserved for advanced usage. - Filters int32 `json:"filters"` + Filters int32 `json:"filters" validate:"required"` // Position of the most important matched attribute in the attributes to index list. - FirstMatchedWord int32 `json:"firstMatchedWord"` + FirstMatchedWord int32 `json:"firstMatchedWord" validate:"required"` // Distance between the geo location in the search query and the best matching geo location in the record, divided by the geo precision (in meters). - GeoDistance int32 `json:"geoDistance"` + GeoDistance int32 `json:"geoDistance" validate:"required"` // Precision used when computing the geo distance, in meters. GeoPrecision *int32 `json:"geoPrecision,omitempty"` MatchedGeoLocation *MatchedGeoLocation `json:"matchedGeoLocation,omitempty"` Personalization *Personalization `json:"personalization,omitempty"` // Number of exactly matched words. - NbExactWords int32 `json:"nbExactWords"` + NbExactWords int32 `json:"nbExactWords" validate:"required"` // Number of typos encountered when matching the record. - NbTypos int32 `json:"nbTypos"` + NbTypos int32 `json:"nbTypos" validate:"required"` // Present and set to true if a Rule promoted the hit. - Promoted bool `json:"promoted"` + Promoted bool `json:"promoted" validate:"required"` // When the query contains more than one word, the sum of the distances between matched words (in meters). ProximityDistance *int32 `json:"proximityDistance,omitempty"` // Custom ranking for the object, expressed as a single integer value. - UserScore int32 `json:"userScore"` + UserScore int32 `json:"userScore" validate:"required"` // Number of matched words, including prefixes and typos. - Words int32 `json:"words"` + Words int32 `json:"words" validate:"required"` // Wether the record are promoted by the re-ranking strategy. PromotedByReRanking *bool `json:"promotedByReRanking,omitempty"` } diff --git a/clients/algoliasearch-client-go/algolia/search/model_re_ranking_apply_filter.go b/clients/algoliasearch-client-go/algolia/search/model_re_ranking_apply_filter.go index c50d14d54b..1771c24edb 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_re_ranking_apply_filter.go +++ b/clients/algoliasearch-client-go/algolia/search/model_re_ranking_apply_filter.go @@ -34,15 +34,14 @@ func (dst *ReRankingApplyFilter) UnmarshalJSON(data []byte) error { return nil } - match := 0 // try to unmarshal data into ArrayOfMixedSearchFilters err = newStrictDecoder(data).Decode(&dst.ArrayOfMixedSearchFilters) - if err == nil { + if err == nil && validateStruct(dst.ArrayOfMixedSearchFilters) == nil { jsonArrayOfMixedSearchFilters, _ := json.Marshal(dst.ArrayOfMixedSearchFilters) if string(jsonArrayOfMixedSearchFilters) == "{}" { // empty struct dst.ArrayOfMixedSearchFilters = nil } else { - match++ + return nil } } else { dst.ArrayOfMixedSearchFilters = nil @@ -50,28 +49,18 @@ func (dst *ReRankingApplyFilter) UnmarshalJSON(data []byte) error { // try to unmarshal data into String err = newStrictDecoder(data).Decode(&dst.String) - if err == nil { + if err == nil && validateStruct(dst.String) == nil { jsonString, _ := json.Marshal(dst.String) if string(jsonString) == "{}" { // empty struct dst.String = nil } else { - match++ + return nil } } else { dst.String = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.ArrayOfMixedSearchFilters = nil - dst.String = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(ReRankingApplyFilter)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(ReRankingApplyFilter)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(ReRankingApplyFilter)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/search/model_redirect_rule_index_metadata.go b/clients/algoliasearch-client-go/algolia/search/model_redirect_rule_index_metadata.go index f3f71fb968..c55014f3f6 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_redirect_rule_index_metadata.go +++ b/clients/algoliasearch-client-go/algolia/search/model_redirect_rule_index_metadata.go @@ -9,14 +9,14 @@ import ( // RedirectRuleIndexMetadata struct for RedirectRuleIndexMetadata type RedirectRuleIndexMetadata struct { // Source index for the redirect rule. - Source string `json:"source"` + Source string `json:"source" validate:"required"` // Destination index for the redirect rule. - Dest string `json:"dest"` + Dest string `json:"dest" validate:"required"` // Reason for the redirect rule. - Reason string `json:"reason"` + Reason string `json:"reason" validate:"required"` // Status for the redirect rule. - Succeed bool `json:"succeed"` - Data RedirectRuleIndexMetadataData `json:"data"` + Succeed bool `json:"succeed" validate:"required"` + Data RedirectRuleIndexMetadataData `json:"data" validate:"required"` } // NewRedirectRuleIndexMetadata instantiates a new RedirectRuleIndexMetadata object diff --git a/clients/algoliasearch-client-go/algolia/search/model_redirect_rule_index_metadata_data.go b/clients/algoliasearch-client-go/algolia/search/model_redirect_rule_index_metadata_data.go index 68f08cd286..4ae3bbd248 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_redirect_rule_index_metadata_data.go +++ b/clients/algoliasearch-client-go/algolia/search/model_redirect_rule_index_metadata_data.go @@ -8,7 +8,7 @@ import ( // RedirectRuleIndexMetadataData Data for the redirect rule. type RedirectRuleIndexMetadataData struct { - RuleObjectID string `json:"ruleObjectID"` + RuleObjectID string `json:"ruleObjectID" validate:"required"` } // NewRedirectRuleIndexMetadataData instantiates a new RedirectRuleIndexMetadataData object diff --git a/clients/algoliasearch-client-go/algolia/search/model_remove_stop_words.go b/clients/algoliasearch-client-go/algolia/search/model_remove_stop_words.go index d97d161e70..9b2b9e9859 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_remove_stop_words.go +++ b/clients/algoliasearch-client-go/algolia/search/model_remove_stop_words.go @@ -29,15 +29,14 @@ func BoolAsRemoveStopWords(v *bool) RemoveStopWords { // Unmarshal JSON data into one of the pointers in the struct func (dst *RemoveStopWords) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into ArrayOfString err = newStrictDecoder(data).Decode(&dst.ArrayOfString) - if err == nil { + if err == nil && validateStruct(dst.ArrayOfString) == nil { jsonArrayOfString, _ := json.Marshal(dst.ArrayOfString) if string(jsonArrayOfString) == "{}" { // empty struct dst.ArrayOfString = nil } else { - match++ + return nil } } else { dst.ArrayOfString = nil @@ -45,28 +44,18 @@ func (dst *RemoveStopWords) UnmarshalJSON(data []byte) error { // try to unmarshal data into Bool err = newStrictDecoder(data).Decode(&dst.Bool) - if err == nil { + if err == nil && validateStruct(dst.Bool) == nil { jsonBool, _ := json.Marshal(dst.Bool) if string(jsonBool) == "{}" { // empty struct dst.Bool = nil } else { - match++ + return nil } } else { dst.Bool = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.ArrayOfString = nil - dst.Bool = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(RemoveStopWords)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(RemoveStopWords)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(RemoveStopWords)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/search/model_remove_user_id_response.go b/clients/algoliasearch-client-go/algolia/search/model_remove_user_id_response.go index 9b4185e3aa..df749d234f 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_remove_user_id_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_remove_user_id_response.go @@ -9,7 +9,7 @@ import ( // RemoveUserIdResponse struct for RemoveUserIdResponse type RemoveUserIdResponse struct { // Date of deletion (ISO-8601 format). - DeletedAt string `json:"deletedAt"` + DeletedAt string `json:"deletedAt" validate:"required"` } // NewRemoveUserIdResponse instantiates a new RemoveUserIdResponse object diff --git a/clients/algoliasearch-client-go/algolia/search/model_replace_source_response.go b/clients/algoliasearch-client-go/algolia/search/model_replace_source_response.go index a8bad58cb9..d07f0e2569 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_replace_source_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_replace_source_response.go @@ -9,7 +9,7 @@ import ( // ReplaceSourceResponse struct for ReplaceSourceResponse type ReplaceSourceResponse struct { // Date of last update (ISO-8601 format). - UpdatedAt string `json:"updatedAt"` + UpdatedAt string `json:"updatedAt" validate:"required"` } // NewReplaceSourceResponse instantiates a new ReplaceSourceResponse object diff --git a/clients/algoliasearch-client-go/algolia/search/model_rule.go b/clients/algoliasearch-client-go/algolia/search/model_rule.go index d66ab1b13a..89411c7525 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_rule.go +++ b/clients/algoliasearch-client-go/algolia/search/model_rule.go @@ -9,7 +9,7 @@ import ( // Rule Rule object. type Rule struct { // Unique identifier of the object. - ObjectID string `json:"objectID"` + ObjectID string `json:"objectID" validate:"required"` // A list of conditions that should apply to activate a Rule. You can use up to 25 conditions per Rule. Conditions []Condition `json:"conditions,omitempty"` Consequence *Consequence `json:"consequence,omitempty"` diff --git a/clients/algoliasearch-client-go/algolia/search/model_save_object_response.go b/clients/algoliasearch-client-go/algolia/search/model_save_object_response.go index 7127318fde..e793710873 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_save_object_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_save_object_response.go @@ -8,9 +8,9 @@ import ( // SaveObjectResponse struct for SaveObjectResponse type SaveObjectResponse struct { - CreatedAt string `json:"createdAt"` + CreatedAt string `json:"createdAt" validate:"required"` // taskID of the task to wait for. - TaskID int64 `json:"taskID"` + TaskID int64 `json:"taskID" validate:"required"` // Unique identifier of the object. ObjectID *string `json:"objectID,omitempty"` } diff --git a/clients/algoliasearch-client-go/algolia/search/model_save_synonym_response.go b/clients/algoliasearch-client-go/algolia/search/model_save_synonym_response.go index 4a703d497e..e4e56ea315 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_save_synonym_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_save_synonym_response.go @@ -9,11 +9,11 @@ import ( // SaveSynonymResponse struct for SaveSynonymResponse type SaveSynonymResponse struct { // taskID of the task to wait for. - TaskID int64 `json:"taskID"` + TaskID int64 `json:"taskID" validate:"required"` // Date of last update (ISO-8601 format). - UpdatedAt string `json:"updatedAt"` + UpdatedAt string `json:"updatedAt" validate:"required"` // objectID of the inserted object. - Id string `json:"id"` + Id string `json:"id" validate:"required"` } // NewSaveSynonymResponse instantiates a new SaveSynonymResponse object diff --git a/clients/algoliasearch-client-go/algolia/search/model_search_dictionary_entries_params.go b/clients/algoliasearch-client-go/algolia/search/model_search_dictionary_entries_params.go index d0c2a91835..f269dbba7b 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_search_dictionary_entries_params.go +++ b/clients/algoliasearch-client-go/algolia/search/model_search_dictionary_entries_params.go @@ -9,7 +9,7 @@ import ( // SearchDictionaryEntriesParams The `searchDictionaryEntries` parameters. type SearchDictionaryEntriesParams struct { // The text to search in the index. - Query string `json:"query"` + Query string `json:"query" validate:"required"` // Specify the page to retrieve. Page *int32 `json:"page,omitempty"` // Set the number of hits per page. diff --git a/clients/algoliasearch-client-go/algolia/search/model_search_for_facet_values_response.go b/clients/algoliasearch-client-go/algolia/search/model_search_for_facet_values_response.go index df8c2847a5..08902b2b1c 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_search_for_facet_values_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_search_for_facet_values_response.go @@ -8,7 +8,7 @@ import ( // SearchForFacetValuesResponse struct for SearchForFacetValuesResponse type SearchForFacetValuesResponse struct { - FacetHits []FacetHits `json:"facetHits"` + FacetHits []FacetHits `json:"facetHits" validate:"required"` } // NewSearchForFacetValuesResponse instantiates a new SearchForFacetValuesResponse object diff --git a/clients/algoliasearch-client-go/algolia/search/model_search_for_facets.go b/clients/algoliasearch-client-go/algolia/search/model_search_for_facets.go index 20d1082601..fd6156aced 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_search_for_facets.go +++ b/clients/algoliasearch-client-go/algolia/search/model_search_for_facets.go @@ -153,12 +153,12 @@ type SearchForFacets struct { AttributeCriteriaComputedByMinProximity *bool `json:"attributeCriteriaComputedByMinProximity,omitempty"` RenderingContent *RenderingContent `json:"renderingContent,omitempty"` // The `facet` name. - Facet string `json:"facet"` + Facet string `json:"facet" validate:"required"` // The Algolia index name. - IndexName string `json:"indexName"` + IndexName string `json:"indexName" validate:"required"` // Text to search inside the facet's values. FacetQuery *string `json:"facetQuery,omitempty"` - Type SearchTypeFacet `json:"type"` + Type SearchTypeFacet `json:"type" validate:"required"` } type SearchForFacetsOption func(f *SearchForFacets) diff --git a/clients/algoliasearch-client-go/algolia/search/model_search_for_facets_options.go b/clients/algoliasearch-client-go/algolia/search/model_search_for_facets_options.go index 53625f29bb..37203b9ea3 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_search_for_facets_options.go +++ b/clients/algoliasearch-client-go/algolia/search/model_search_for_facets_options.go @@ -9,14 +9,14 @@ import ( // SearchForFacetsOptions struct for SearchForFacetsOptions type SearchForFacetsOptions struct { // The `facet` name. - Facet string `json:"facet"` + Facet string `json:"facet" validate:"required"` // The Algolia index name. - IndexName string `json:"indexName"` + IndexName string `json:"indexName" validate:"required"` // Text to search inside the facet's values. FacetQuery *string `json:"facetQuery,omitempty"` // Maximum number of facet hits to return during a search for facet values. For performance reasons, the maximum allowed number of returned values is 100. MaxFacetHits *int32 `json:"maxFacetHits,omitempty"` - Type SearchTypeFacet `json:"type"` + Type SearchTypeFacet `json:"type" validate:"required"` } type SearchForFacetsOptionsOption func(f *SearchForFacetsOptions) diff --git a/clients/algoliasearch-client-go/algolia/search/model_search_for_hits.go b/clients/algoliasearch-client-go/algolia/search/model_search_for_hits.go index 4a85c52095..ca5740f1c4 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_search_for_hits.go +++ b/clients/algoliasearch-client-go/algolia/search/model_search_for_hits.go @@ -153,7 +153,7 @@ type SearchForHits struct { AttributeCriteriaComputedByMinProximity *bool `json:"attributeCriteriaComputedByMinProximity,omitempty"` RenderingContent *RenderingContent `json:"renderingContent,omitempty"` // The Algolia index name. - IndexName string `json:"indexName"` + IndexName string `json:"indexName" validate:"required"` Type *SearchTypeDefault `json:"type,omitempty"` } diff --git a/clients/algoliasearch-client-go/algolia/search/model_search_for_hits_options.go b/clients/algoliasearch-client-go/algolia/search/model_search_for_hits_options.go index 3fb1efe987..27c3e1a89d 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_search_for_hits_options.go +++ b/clients/algoliasearch-client-go/algolia/search/model_search_for_hits_options.go @@ -9,7 +9,7 @@ import ( // SearchForHitsOptions struct for SearchForHitsOptions type SearchForHitsOptions struct { // The Algolia index name. - IndexName string `json:"indexName"` + IndexName string `json:"indexName" validate:"required"` Type *SearchTypeDefault `json:"type,omitempty"` } diff --git a/clients/algoliasearch-client-go/algolia/search/model_search_hits.go b/clients/algoliasearch-client-go/algolia/search/model_search_hits.go index 005317a6b5..73fea28128 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_search_hits.go +++ b/clients/algoliasearch-client-go/algolia/search/model_search_hits.go @@ -8,7 +8,7 @@ import ( // SearchHits struct for SearchHits type SearchHits struct { - Hits []Hit `json:"hits"` + Hits []Hit `json:"hits" validate:"required"` } // NewSearchHits instantiates a new SearchHits object diff --git a/clients/algoliasearch-client-go/algolia/search/model_search_method_params.go b/clients/algoliasearch-client-go/algolia/search/model_search_method_params.go index 9ab6311955..88ae7f5443 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_search_method_params.go +++ b/clients/algoliasearch-client-go/algolia/search/model_search_method_params.go @@ -8,7 +8,7 @@ import ( // SearchMethodParams struct for SearchMethodParams type SearchMethodParams struct { - Requests []SearchQuery `json:"requests"` + Requests []SearchQuery `json:"requests" validate:"required"` Strategy *SearchStrategy `json:"strategy,omitempty"` } diff --git a/clients/algoliasearch-client-go/algolia/search/model_search_params.go b/clients/algoliasearch-client-go/algolia/search/model_search_params.go index a602f81ef4..6377bd83a0 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_search_params.go +++ b/clients/algoliasearch-client-go/algolia/search/model_search_params.go @@ -29,15 +29,14 @@ func SearchParamsStringAsSearchParams(v *SearchParamsString) SearchParams { // Unmarshal JSON data into one of the pointers in the struct func (dst *SearchParams) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into SearchParamsObject err = newStrictDecoder(data).Decode(&dst.SearchParamsObject) - if err == nil { + if err == nil && validateStruct(dst.SearchParamsObject) == nil { jsonSearchParamsObject, _ := json.Marshal(dst.SearchParamsObject) if string(jsonSearchParamsObject) == "{}" { // empty struct dst.SearchParamsObject = nil } else { - match++ + return nil } } else { dst.SearchParamsObject = nil @@ -45,28 +44,18 @@ func (dst *SearchParams) UnmarshalJSON(data []byte) error { // try to unmarshal data into SearchParamsString err = newStrictDecoder(data).Decode(&dst.SearchParamsString) - if err == nil { + if err == nil && validateStruct(dst.SearchParamsString) == nil { jsonSearchParamsString, _ := json.Marshal(dst.SearchParamsString) if string(jsonSearchParamsString) == "{}" { // empty struct dst.SearchParamsString = nil } else { - match++ + return nil } } else { dst.SearchParamsString = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.SearchParamsObject = nil - dst.SearchParamsString = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(SearchParams)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(SearchParams)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(SearchParams)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/search/model_search_query.go b/clients/algoliasearch-client-go/algolia/search/model_search_query.go index a4596f0f52..947f75ea2a 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_search_query.go +++ b/clients/algoliasearch-client-go/algolia/search/model_search_query.go @@ -29,15 +29,14 @@ func SearchForHitsAsSearchQuery(v *SearchForHits) SearchQuery { // Unmarshal JSON data into one of the pointers in the struct func (dst *SearchQuery) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into SearchForFacets err = newStrictDecoder(data).Decode(&dst.SearchForFacets) - if err == nil { + if err == nil && validateStruct(dst.SearchForFacets) == nil { jsonSearchForFacets, _ := json.Marshal(dst.SearchForFacets) if string(jsonSearchForFacets) == "{}" { // empty struct dst.SearchForFacets = nil } else { - match++ + return nil } } else { dst.SearchForFacets = nil @@ -45,28 +44,18 @@ func (dst *SearchQuery) UnmarshalJSON(data []byte) error { // try to unmarshal data into SearchForHits err = newStrictDecoder(data).Decode(&dst.SearchForHits) - if err == nil { + if err == nil && validateStruct(dst.SearchForHits) == nil { jsonSearchForHits, _ := json.Marshal(dst.SearchForHits) if string(jsonSearchForHits) == "{}" { // empty struct dst.SearchForHits = nil } else { - match++ + return nil } } else { dst.SearchForHits = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.SearchForFacets = nil - dst.SearchForHits = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(SearchQuery)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(SearchQuery)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(SearchQuery)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/search/model_search_response.go b/clients/algoliasearch-client-go/algolia/search/model_search_response.go index 5888f772ab..d779e4e626 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_search_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_search_response.go @@ -19,7 +19,7 @@ type SearchResponse struct { // Whether the facet count is exhaustive or approximate. ExhaustiveFacetsCount *bool `json:"exhaustiveFacetsCount,omitempty"` // Indicate if the nbHits count was exhaustive or approximate. - ExhaustiveNbHits bool `json:"exhaustiveNbHits"` + ExhaustiveNbHits bool `json:"exhaustiveNbHits" validate:"required"` // Indicate if the typo-tolerance search was exhaustive or approximate (only included when typo-tolerance is enabled). ExhaustiveTypo *bool `json:"exhaustiveTypo,omitempty"` // A mapping of each facet name to the corresponding facet counts. @@ -27,7 +27,7 @@ type SearchResponse struct { // Statistics for numerical facets. FacetsStats *map[string]FacetsStats `json:"facets_stats,omitempty"` // Set the number of hits per page. - HitsPerPage int32 `json:"hitsPerPage"` + HitsPerPage int32 `json:"hitsPerPage" validate:"required"` // Index name used for the query. Index *string `json:"index,omitempty"` // Index name used for the query. In the case of an A/B test, the targeted index isn't always the index used by the query. @@ -35,22 +35,22 @@ type SearchResponse struct { // Used to return warnings about the query. Message *string `json:"message,omitempty"` // Number of hits that the search query matched. - NbHits int32 `json:"nbHits"` + NbHits int32 `json:"nbHits" validate:"required"` // Number of pages available for the current query. - NbPages int32 `json:"nbPages"` + NbPages int32 `json:"nbPages" validate:"required"` // The number of hits selected and sorted by the relevant sort algorithm. NbSortedHits *int32 `json:"nbSortedHits,omitempty"` // Specify the page to retrieve. - Page int32 `json:"page"` + Page int32 `json:"page" validate:"required"` // A url-encoded string of all search parameters. - Params string `json:"params"` + Params string `json:"params" validate:"required"` Redirect *BaseSearchResponseRedirect `json:"redirect,omitempty"` // The query string that will be searched, after normalization. ParsedQuery *string `json:"parsedQuery,omitempty"` // Time the server took to process the request, in milliseconds. - ProcessingTimeMS int32 `json:"processingTimeMS"` + ProcessingTimeMS int32 `json:"processingTimeMS" validate:"required"` // The text to search in the index. - Query string `json:"query"` + Query string `json:"query" validate:"required"` // A markup text indicating which parts of the original query have been removed in order to retrieve a non-empty result set. QueryAfterRemoval *string `json:"queryAfterRemoval,omitempty"` // Actual host name of the server that processed the request. @@ -58,7 +58,7 @@ type SearchResponse struct { // Lets you store custom data in your indices. UserData map[string]interface{} `json:"userData,omitempty"` RenderingContent *RenderingContent `json:"renderingContent,omitempty"` - Hits []Hit `json:"hits"` + Hits []Hit `json:"hits" validate:"required"` } type SearchResponseOption func(f *SearchResponse) diff --git a/clients/algoliasearch-client-go/algolia/search/model_search_responses.go b/clients/algoliasearch-client-go/algolia/search/model_search_responses.go index f7f163e150..e93df1c655 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_search_responses.go +++ b/clients/algoliasearch-client-go/algolia/search/model_search_responses.go @@ -8,7 +8,7 @@ import ( // SearchResponses struct for SearchResponses type SearchResponses struct { - Results []SearchResponse `json:"results"` + Results []SearchResponse `json:"results" validate:"required"` } // NewSearchResponses instantiates a new SearchResponses object diff --git a/clients/algoliasearch-client-go/algolia/search/model_search_rules_response.go b/clients/algoliasearch-client-go/algolia/search/model_search_rules_response.go index 90c48a976b..99f2a2ea6f 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_search_rules_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_search_rules_response.go @@ -9,13 +9,13 @@ import ( // SearchRulesResponse struct for SearchRulesResponse type SearchRulesResponse struct { // Fetched rules. - Hits []Rule `json:"hits"` + Hits []Rule `json:"hits" validate:"required"` // Number of fetched rules. - NbHits int32 `json:"nbHits"` + NbHits int32 `json:"nbHits" validate:"required"` // Current page. - Page int32 `json:"page"` + Page int32 `json:"page" validate:"required"` // Number of pages. - NbPages int32 `json:"nbPages"` + NbPages int32 `json:"nbPages" validate:"required"` } // NewSearchRulesResponse instantiates a new SearchRulesResponse object diff --git a/clients/algoliasearch-client-go/algolia/search/model_search_synonyms_response.go b/clients/algoliasearch-client-go/algolia/search/model_search_synonyms_response.go index 1abdeec497..23d9fa20ec 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_search_synonyms_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_search_synonyms_response.go @@ -9,9 +9,9 @@ import ( // SearchSynonymsResponse struct for SearchSynonymsResponse type SearchSynonymsResponse struct { // Array of synonym objects. - Hits []SynonymHit `json:"hits"` + Hits []SynonymHit `json:"hits" validate:"required"` // Number of hits that the search query matched. - NbHits int32 `json:"nbHits"` + NbHits int32 `json:"nbHits" validate:"required"` AdditionalProperties map[string]any } diff --git a/clients/algoliasearch-client-go/algolia/search/model_search_user_ids_params.go b/clients/algoliasearch-client-go/algolia/search/model_search_user_ids_params.go index 4ec6e3da6d..d631d3458a 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_search_user_ids_params.go +++ b/clients/algoliasearch-client-go/algolia/search/model_search_user_ids_params.go @@ -9,7 +9,7 @@ import ( // SearchUserIdsParams OK type SearchUserIdsParams struct { // Query to search. The search is a prefix search with typoTolerance. Use empty query to retrieve all users. - Query string `json:"query"` + Query string `json:"query" validate:"required"` // Name of the cluster. ClusterName *string `json:"clusterName,omitempty"` // Specify the page to retrieve. diff --git a/clients/algoliasearch-client-go/algolia/search/model_search_user_ids_response.go b/clients/algoliasearch-client-go/algolia/search/model_search_user_ids_response.go index aa094e56d6..7da6b71c68 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_search_user_ids_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_search_user_ids_response.go @@ -9,15 +9,15 @@ import ( // SearchUserIdsResponse userIDs data. type SearchUserIdsResponse struct { // List of user object matching the query. - Hits []UserHit `json:"hits"` + Hits []UserHit `json:"hits" validate:"required"` // Number of hits that the search query matched. - NbHits int32 `json:"nbHits"` + NbHits int32 `json:"nbHits" validate:"required"` // Specify the page to retrieve. - Page int32 `json:"page"` + Page int32 `json:"page" validate:"required"` // Maximum number of hits in a page. Minimum is 1, maximum is 1000. - HitsPerPage int32 `json:"hitsPerPage"` + HitsPerPage int32 `json:"hitsPerPage" validate:"required"` // Date of last update (ISO-8601 format). - UpdatedAt string `json:"updatedAt"` + UpdatedAt string `json:"updatedAt" validate:"required"` } // NewSearchUserIdsResponse instantiates a new SearchUserIdsResponse object diff --git a/clients/algoliasearch-client-go/algolia/search/model_snippet_result.go b/clients/algoliasearch-client-go/algolia/search/model_snippet_result.go index a4f4ea39ac..e6a59df29a 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_snippet_result.go +++ b/clients/algoliasearch-client-go/algolia/search/model_snippet_result.go @@ -29,15 +29,14 @@ func ArrayOfSnippetResultOptionAsSnippetResult(v *[]SnippetResultOption) Snippet // Unmarshal JSON data into one of the pointers in the struct func (dst *SnippetResult) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into SnippetResultOption err = newStrictDecoder(data).Decode(&dst.SnippetResultOption) - if err == nil { + if err == nil && validateStruct(dst.SnippetResultOption) == nil { jsonSnippetResultOption, _ := json.Marshal(dst.SnippetResultOption) if string(jsonSnippetResultOption) == "{}" { // empty struct dst.SnippetResultOption = nil } else { - match++ + return nil } } else { dst.SnippetResultOption = nil @@ -45,28 +44,18 @@ func (dst *SnippetResult) UnmarshalJSON(data []byte) error { // try to unmarshal data into ArrayOfSnippetResultOption err = newStrictDecoder(data).Decode(&dst.ArrayOfSnippetResultOption) - if err == nil { + if err == nil && validateStruct(dst.ArrayOfSnippetResultOption) == nil { jsonArrayOfSnippetResultOption, _ := json.Marshal(dst.ArrayOfSnippetResultOption) if string(jsonArrayOfSnippetResultOption) == "{}" { // empty struct dst.ArrayOfSnippetResultOption = nil } else { - match++ + return nil } } else { dst.ArrayOfSnippetResultOption = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.SnippetResultOption = nil - dst.ArrayOfSnippetResultOption = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(SnippetResult)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(SnippetResult)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(SnippetResult)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/search/model_snippet_result_option.go b/clients/algoliasearch-client-go/algolia/search/model_snippet_result_option.go index 535982d6d7..5e18ffed09 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_snippet_result_option.go +++ b/clients/algoliasearch-client-go/algolia/search/model_snippet_result_option.go @@ -9,8 +9,8 @@ import ( // SnippetResultOption Snippeted attributes show parts of the matched attributes. Only returned when attributesToSnippet is non-empty. type SnippetResultOption struct { // Markup text with occurrences highlighted. - Value string `json:"value"` - MatchLevel MatchLevel `json:"matchLevel"` + Value string `json:"value" validate:"required"` + MatchLevel MatchLevel `json:"matchLevel" validate:"required"` } // NewSnippetResultOption instantiates a new SnippetResultOption object diff --git a/clients/algoliasearch-client-go/algolia/search/model_source.go b/clients/algoliasearch-client-go/algolia/search/model_source.go index e7a0d2cd8d..628dee1eb1 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_source.go +++ b/clients/algoliasearch-client-go/algolia/search/model_source.go @@ -9,7 +9,7 @@ import ( // Source The source. type Source struct { // The IP range of the source. - Source string `json:"source"` + Source string `json:"source" validate:"required"` // The description of the source. Description *string `json:"description,omitempty"` } diff --git a/clients/algoliasearch-client-go/algolia/search/model_synonym_hit.go b/clients/algoliasearch-client-go/algolia/search/model_synonym_hit.go index 353a7e258d..a9f73bb5a1 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_synonym_hit.go +++ b/clients/algoliasearch-client-go/algolia/search/model_synonym_hit.go @@ -9,8 +9,8 @@ import ( // SynonymHit Synonym object. type SynonymHit struct { // Unique identifier of the synonym object to be created or updated. - ObjectID string `json:"objectID"` - Type SynonymType `json:"type"` + ObjectID string `json:"objectID" validate:"required"` + Type SynonymType `json:"type" validate:"required"` // Words or phrases to be considered equivalent. Synonyms []string `json:"synonyms,omitempty"` // Word or phrase to appear in query strings (for onewaysynonym). diff --git a/clients/algoliasearch-client-go/algolia/search/model_tag_filters.go b/clients/algoliasearch-client-go/algolia/search/model_tag_filters.go index 4106b9c477..e204f3b975 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_tag_filters.go +++ b/clients/algoliasearch-client-go/algolia/search/model_tag_filters.go @@ -29,15 +29,14 @@ func StringAsTagFilters(v *string) TagFilters { // Unmarshal JSON data into one of the pointers in the struct func (dst *TagFilters) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into ArrayOfMixedSearchFilters err = newStrictDecoder(data).Decode(&dst.ArrayOfMixedSearchFilters) - if err == nil { + if err == nil && validateStruct(dst.ArrayOfMixedSearchFilters) == nil { jsonArrayOfMixedSearchFilters, _ := json.Marshal(dst.ArrayOfMixedSearchFilters) if string(jsonArrayOfMixedSearchFilters) == "{}" { // empty struct dst.ArrayOfMixedSearchFilters = nil } else { - match++ + return nil } } else { dst.ArrayOfMixedSearchFilters = nil @@ -45,28 +44,18 @@ func (dst *TagFilters) UnmarshalJSON(data []byte) error { // try to unmarshal data into String err = newStrictDecoder(data).Decode(&dst.String) - if err == nil { + if err == nil && validateStruct(dst.String) == nil { jsonString, _ := json.Marshal(dst.String) if string(jsonString) == "{}" { // empty struct dst.String = nil } else { - match++ + return nil } } else { dst.String = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.ArrayOfMixedSearchFilters = nil - dst.String = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(TagFilters)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(TagFilters)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(TagFilters)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/search/model_time_range.go b/clients/algoliasearch-client-go/algolia/search/model_time_range.go index 60d4061d09..1eea512603 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_time_range.go +++ b/clients/algoliasearch-client-go/algolia/search/model_time_range.go @@ -9,9 +9,9 @@ import ( // TimeRange struct for TimeRange type TimeRange struct { // Lower bound of the time range (Unix timestamp). - From int32 `json:"from"` + From int32 `json:"from" validate:"required"` // Upper bound of the time range (Unix timestamp). - Until int32 `json:"until"` + Until int32 `json:"until" validate:"required"` } // NewTimeRange instantiates a new TimeRange object diff --git a/clients/algoliasearch-client-go/algolia/search/model_typo_tolerance.go b/clients/algoliasearch-client-go/algolia/search/model_typo_tolerance.go index 3cbdb4bfeb..ead96610c5 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_typo_tolerance.go +++ b/clients/algoliasearch-client-go/algolia/search/model_typo_tolerance.go @@ -29,15 +29,14 @@ func BoolAsTypoTolerance(v *bool) TypoTolerance { // Unmarshal JSON data into one of the pointers in the struct func (dst *TypoTolerance) UnmarshalJSON(data []byte) error { var err error - match := 0 // try to unmarshal data into TypoToleranceEnum err = newStrictDecoder(data).Decode(&dst.TypoToleranceEnum) - if err == nil { + if err == nil && validateStruct(dst.TypoToleranceEnum) == nil { jsonTypoToleranceEnum, _ := json.Marshal(dst.TypoToleranceEnum) if string(jsonTypoToleranceEnum) == "{}" { // empty struct dst.TypoToleranceEnum = nil } else { - match++ + return nil } } else { dst.TypoToleranceEnum = nil @@ -45,28 +44,18 @@ func (dst *TypoTolerance) UnmarshalJSON(data []byte) error { // try to unmarshal data into Bool err = newStrictDecoder(data).Decode(&dst.Bool) - if err == nil { + if err == nil && validateStruct(dst.Bool) == nil { jsonBool, _ := json.Marshal(dst.Bool) if string(jsonBool) == "{}" { // empty struct dst.Bool = nil } else { - match++ + return nil } } else { dst.Bool = nil } - if match > 1 { // more than 1 match - // reset to nil - dst.TypoToleranceEnum = nil - dst.Bool = nil - - return fmt.Errorf("Data matches more than one schema in oneOf(TypoTolerance)") - } else if match == 1 { - return nil // exactly one match - } else { // no match - return fmt.Errorf("Data failed to match schemas in oneOf(TypoTolerance)") - } + return fmt.Errorf("Data failed to match schemas in oneOf(TypoTolerance)") } // Marshal data from the first non-nil pointers in the struct to JSON diff --git a/clients/algoliasearch-client-go/algolia/search/model_update_api_key_response.go b/clients/algoliasearch-client-go/algolia/search/model_update_api_key_response.go index af29eeb861..cbefda32e6 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_update_api_key_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_update_api_key_response.go @@ -9,9 +9,9 @@ import ( // UpdateApiKeyResponse struct for UpdateApiKeyResponse type UpdateApiKeyResponse struct { // The API key. - Key string `json:"key"` + Key string `json:"key" validate:"required"` // Date of last update (ISO-8601 format). - UpdatedAt string `json:"updatedAt"` + UpdatedAt string `json:"updatedAt" validate:"required"` } // NewUpdateApiKeyResponse instantiates a new UpdateApiKeyResponse object diff --git a/clients/algoliasearch-client-go/algolia/search/model_updated_at_response.go b/clients/algoliasearch-client-go/algolia/search/model_updated_at_response.go index c8b90e9986..d6e487c818 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_updated_at_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_updated_at_response.go @@ -9,9 +9,9 @@ import ( // UpdatedAtResponse The response with a taskID and an updatedAt timestamp. type UpdatedAtResponse struct { // taskID of the task to wait for. - TaskID int64 `json:"taskID"` + TaskID int64 `json:"taskID" validate:"required"` // Date of last update (ISO-8601 format). - UpdatedAt string `json:"updatedAt"` + UpdatedAt string `json:"updatedAt" validate:"required"` } // NewUpdatedAtResponse instantiates a new UpdatedAtResponse object diff --git a/clients/algoliasearch-client-go/algolia/search/model_updated_rule_response.go b/clients/algoliasearch-client-go/algolia/search/model_updated_rule_response.go index 005a373d8a..6e812ef136 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_updated_rule_response.go +++ b/clients/algoliasearch-client-go/algolia/search/model_updated_rule_response.go @@ -9,11 +9,11 @@ import ( // UpdatedRuleResponse struct for UpdatedRuleResponse type UpdatedRuleResponse struct { // Unique identifier of the object. - ObjectID string `json:"objectID"` + ObjectID string `json:"objectID" validate:"required"` // Date of last update (ISO-8601 format). - UpdatedAt string `json:"updatedAt"` + UpdatedAt string `json:"updatedAt" validate:"required"` // taskID of the task to wait for. - TaskID int64 `json:"taskID"` + TaskID int64 `json:"taskID" validate:"required"` } // NewUpdatedRuleResponse instantiates a new UpdatedRuleResponse object diff --git a/clients/algoliasearch-client-go/algolia/search/model_user_highlight_result.go b/clients/algoliasearch-client-go/algolia/search/model_user_highlight_result.go index 0eddcd0f41..52086556c5 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_user_highlight_result.go +++ b/clients/algoliasearch-client-go/algolia/search/model_user_highlight_result.go @@ -9,9 +9,9 @@ import ( // UserHighlightResult struct for UserHighlightResult type UserHighlightResult struct { // Show highlighted section and words matched on a query. - UserID map[string]HighlightResult `json:"userID"` + UserID map[string]HighlightResult `json:"userID" validate:"required"` // Show highlighted section and words matched on a query. - ClusterName map[string]HighlightResult `json:"clusterName"` + ClusterName map[string]HighlightResult `json:"clusterName" validate:"required"` } // NewUserHighlightResult instantiates a new UserHighlightResult object diff --git a/clients/algoliasearch-client-go/algolia/search/model_user_hit.go b/clients/algoliasearch-client-go/algolia/search/model_user_hit.go index f2adf796ab..dc4f04babd 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_user_hit.go +++ b/clients/algoliasearch-client-go/algolia/search/model_user_hit.go @@ -9,16 +9,16 @@ import ( // UserHit struct for UserHit type UserHit struct { // userID of the user. - UserID string `json:"userID"` + UserID string `json:"userID" validate:"required"` // Name of the cluster. - ClusterName string `json:"clusterName"` + ClusterName string `json:"clusterName" validate:"required"` // Number of records in the cluster. - NbRecords int32 `json:"nbRecords"` + NbRecords int32 `json:"nbRecords" validate:"required"` // Data size taken by all the users assigned to the cluster. - DataSize int32 `json:"dataSize"` + DataSize int32 `json:"dataSize" validate:"required"` // userID of the requested user. Same as userID. - ObjectID string `json:"objectID"` - HighlightResult UserHighlightResult `json:"_highlightResult"` + ObjectID string `json:"objectID" validate:"required"` + HighlightResult UserHighlightResult `json:"_highlightResult" validate:"required"` } // NewUserHit instantiates a new UserHit object diff --git a/clients/algoliasearch-client-go/algolia/search/model_user_id.go b/clients/algoliasearch-client-go/algolia/search/model_user_id.go index 6701e067d9..41f2c6bd56 100644 --- a/clients/algoliasearch-client-go/algolia/search/model_user_id.go +++ b/clients/algoliasearch-client-go/algolia/search/model_user_id.go @@ -9,13 +9,13 @@ import ( // UserId A userID. type UserId struct { // userID of the user. - UserID string `json:"userID"` + UserID string `json:"userID" validate:"required"` // Cluster on which the user is assigned. - ClusterName string `json:"clusterName"` + ClusterName string `json:"clusterName" validate:"required"` // Number of records belonging to the user. - NbRecords int32 `json:"nbRecords"` + NbRecords int32 `json:"nbRecords" validate:"required"` // Data size used by the user. - DataSize int32 `json:"dataSize"` + DataSize int32 `json:"dataSize" validate:"required"` } // NewUserId instantiates a new UserId object diff --git a/clients/algoliasearch-client-go/algolia/search/utils.go b/clients/algoliasearch-client-go/algolia/search/utils.go index c5b8424175..12f26a1da2 100644 --- a/clients/algoliasearch-client-go/algolia/search/utils.go +++ b/clients/algoliasearch-client-go/algolia/search/utils.go @@ -336,6 +336,8 @@ func isNilorEmpty(i any) bool { switch reflect.TypeOf(i).Kind() { case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.UnsafePointer, reflect.Interface, reflect.Slice: return reflect.ValueOf(i).IsNil() + case reflect.Bool: + return false default: return reflect.ValueOf(i).IsZero() } diff --git a/clients/algoliasearch-client-kotlin/client-bom/README.md b/clients/algoliasearch-client-kotlin/client-bom/README.md new file mode 100644 index 0000000000..e83785e004 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client-bom/README.md @@ -0,0 +1,16 @@ +# Algolia Kotlin API client BOM + +Client [BOM][1] module, can be used to control the dependency versions of direct and transitive dependencies: + +```groovy +dependencies { + // import Kotlin API client BOM + implementation platform('com.algolia:algoliasearch-client-kotlin-bom:{{{{packageVersion}}}}') + + // define dependencies without versions + implementation 'com.algolia:algoliasearch-client-kotlin' + runtimeOnly 'io.ktor:ktor-client-okhttp' +} +``` + +[1]: https://docs.gradle.org/current/userguide/platforms.html#sub:bom_import diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/BuildConfig.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/BuildConfig.kt new file mode 100644 index 0000000000..ac98bc4f3e --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/BuildConfig.kt @@ -0,0 +1,5 @@ +package com.algolia.client + +internal object BuildConfig { + internal const val version: String = "3.0.0-SNAPSHOT" +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/AbtestingClient.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/AbtestingClient.kt new file mode 100644 index 0000000000..1d538e8697 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/AbtestingClient.kt @@ -0,0 +1,217 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.api + +import com.algolia.client.configuration.* +import com.algolia.client.exception.* +import com.algolia.client.extensions.internal.* +import com.algolia.client.model.abtesting.* +import com.algolia.client.transport.* +import com.algolia.client.transport.internal.* +import kotlinx.serialization.json.* + +public class AbtestingClient( + override val appId: String, + override val apiKey: String, + public val region: String? = null, + override val options: ClientOptions = ClientOptions(), +) : ApiClient { + + init { + require(appId.isNotBlank()) { "`appId` is missing." } + require(apiKey.isNotBlank()) { "`apiKey` is missing." } + } + + override val requester: Requester = requesterOf(clientName = "Abtesting", appId = appId, apiKey = apiKey, options = options) { + val allowedRegions = listOf("de", "us") + require(region == null || region in allowedRegions) { "`region` must be one of the following: ${allowedRegions.joinToString()}" } + val url = if (region == null) "analytics.algolia.com" else "analytics.$region.algolia.com" + listOf(Host(url)) + } + + /** + * Create a test. + * Creates a new A/B test with provided configuration. You can set an A/B test on two different indices with different settings, or on the same index with different search parameters by providing a customSearchParameters setting on one of the variants. + * @param addABTestsRequest + * @param requestOptions additional request configuration. + */ + public suspend fun addABTests(addABTestsRequest: AddABTestsRequest, requestOptions: RequestOptions? = null): ABTestResponse { + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("2", "abtests"), + body = addABTestsRequest, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param requestOptions additional request configuration. + */ + public suspend fun del(path: String, parameters: Map? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `del`." } + val requestConfig = RequestConfig( + method = RequestMethod.DELETE, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Delete a test. + * Delete a test. + * @param id The A/B test ID. + * @param requestOptions additional request configuration. + */ + public suspend fun deleteABTest(id: Int, requestOptions: RequestOptions? = null): ABTestResponse { + val requestConfig = RequestConfig( + method = RequestMethod.DELETE, + path = listOf("2", "abtests", "$id"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param requestOptions additional request configuration. + */ + public suspend fun get(path: String, parameters: Map? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `get`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get a test. + * Returns metadata and metrics for an A/B test. + * @param id The A/B test ID. + * @param requestOptions additional request configuration. + */ + public suspend fun getABTest(id: Int, requestOptions: RequestOptions? = null): ABTest { + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("2", "abtests", "$id"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * List all tests. + * Fetch all existing A/B tests for App that are available for the current API Key. When no data has been processed, the metrics will be returned as null. + * @param offset Position of the starting record. Used for paging. 0 is the first record. (default to 0) + * @param limit Number of records to return. Limit is the size of the page. (default to 10) + * @param indexPrefix Filters the returned ab tests by any indices starting with the provided prefix that are assigned to either variant of an ab test. + * @param indexSuffix Filters the returned ab tests by any indices ending with the provided suffix that are assigned to either variant of an ab test. + * @param requestOptions additional request configuration. + */ + public suspend fun listABTests(offset: Int? = null, limit: Int? = null, indexPrefix: String? = null, indexSuffix: String? = null, requestOptions: RequestOptions? = null): ListABTestsResponse { + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("2", "abtests"), + query = buildMap { + offset?.let { put("offset", it) } + limit?.let { put("limit", it) } + indexPrefix?.let { put("indexPrefix", it) } + indexSuffix?.let { put("indexSuffix", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param body The parameters to send with the custom request. + * @param requestOptions additional request configuration. + */ + public suspend fun post(path: String, parameters: Map? = null, body: JsonObject? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `post`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + body = body, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param body The parameters to send with the custom request. + * @param requestOptions additional request configuration. + */ + public suspend fun put(path: String, parameters: Map? = null, body: JsonObject? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `put`." } + val requestConfig = RequestConfig( + method = RequestMethod.PUT, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + body = body, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Stop a test. + * Marks the A/B test as stopped. At this point, the test is over and cannot be restarted. As a result, your application is back to normal: index A will perform as usual, receiving 100% of all search requests. Associated metadata and metrics are still stored. + * @param id The A/B test ID. + * @param requestOptions additional request configuration. + */ + public suspend fun stopABTest(id: Int, requestOptions: RequestOptions? = null): ABTestResponse { + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("2", "abtests", "$id", "stop"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/AnalyticsClient.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/AnalyticsClient.kt new file mode 100644 index 0000000000..41bc537311 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/AnalyticsClient.kt @@ -0,0 +1,625 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.api + +import com.algolia.client.configuration.* +import com.algolia.client.exception.* +import com.algolia.client.extensions.internal.* +import com.algolia.client.model.analytics.* +import com.algolia.client.transport.* +import com.algolia.client.transport.internal.* +import kotlinx.serialization.json.* + +public class AnalyticsClient( + override val appId: String, + override val apiKey: String, + public val region: String? = null, + override val options: ClientOptions = ClientOptions(), +) : ApiClient { + + init { + require(appId.isNotBlank()) { "`appId` is missing." } + require(apiKey.isNotBlank()) { "`apiKey` is missing." } + } + + override val requester: Requester = requesterOf(clientName = "Analytics", appId = appId, apiKey = apiKey, options = options) { + val allowedRegions = listOf("de", "us") + require(region == null || region in allowedRegions) { "`region` must be one of the following: ${allowedRegions.joinToString()}" } + val url = if (region == null) "analytics.algolia.com" else "analytics.$region.algolia.com" + listOf(Host(url)) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param requestOptions additional request configuration. + */ + public suspend fun del(path: String, parameters: Map? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `del`." } + val requestConfig = RequestConfig( + method = RequestMethod.DELETE, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param requestOptions additional request configuration. + */ + public suspend fun get(path: String, parameters: Map? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `get`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get average click position. + * Returns the average click position. The endpoint returns a value for the complete given time range, as well as a value per day. + * @param index The index name to target. + * @param startDate The lower bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param endDate The upper bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param tags Filter metrics on the provided tags. Each tag must correspond to an analyticsTags set at search time. Multiple tags can be combined with the operators OR and AND. If a tag contains characters like spaces or parentheses, it should be URL encoded. + * @param requestOptions additional request configuration. + */ + public suspend fun getAverageClickPosition(index: String, startDate: String? = null, endDate: String? = null, tags: String? = null, requestOptions: RequestOptions? = null): GetAverageClickPositionResponse { + require(index.isNotBlank()) { "Parameter `index` is required when calling `getAverageClickPosition`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("2", "clicks", "averageClickPosition"), + query = buildMap { + put("index", index) + startDate?.let { put("startDate", it) } + endDate?.let { put("endDate", it) } + tags?.let { put("tags", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get clicks per positions. + * Returns the distribution of clicks per range of positions. If the groups all have a count of 0, it means Algolia didn’t receive any click events for the queries with the clickAnalytics search parameter set to true. The count is 0 until Algolia receives at least one click event. + * @param index The index name to target. + * @param startDate The lower bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param endDate The upper bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param tags Filter metrics on the provided tags. Each tag must correspond to an analyticsTags set at search time. Multiple tags can be combined with the operators OR and AND. If a tag contains characters like spaces or parentheses, it should be URL encoded. + * @param requestOptions additional request configuration. + */ + public suspend fun getClickPositions(index: String, startDate: String? = null, endDate: String? = null, tags: String? = null, requestOptions: RequestOptions? = null): GetClickPositionsResponse { + require(index.isNotBlank()) { "Parameter `index` is required when calling `getClickPositions`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("2", "clicks", "positions"), + query = buildMap { + put("index", index) + startDate?.let { put("startDate", it) } + endDate?.let { put("endDate", it) } + tags?.let { put("tags", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get click-through rate (CTR). + * Returns a click-through rate (CTR). The endpoint returns a value for the complete given time range, as well as a value per day. It also returns the count of clicks and searches used to compute the rates. + * @param index The index name to target. + * @param startDate The lower bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param endDate The upper bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param tags Filter metrics on the provided tags. Each tag must correspond to an analyticsTags set at search time. Multiple tags can be combined with the operators OR and AND. If a tag contains characters like spaces or parentheses, it should be URL encoded. + * @param requestOptions additional request configuration. + */ + public suspend fun getClickThroughRate(index: String, startDate: String? = null, endDate: String? = null, tags: String? = null, requestOptions: RequestOptions? = null): GetClickThroughRateResponse { + require(index.isNotBlank()) { "Parameter `index` is required when calling `getClickThroughRate`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("2", "clicks", "clickThroughRate"), + query = buildMap { + put("index", index) + startDate?.let { put("startDate", it) } + endDate?.let { put("endDate", it) } + tags?.let { put("tags", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get conversion rate (CR). + * Returns a conversion rate (CR). The endpoint returns a value for the complete given time range, as well as a value per day. It also returns the count of conversion and searches used to compute the rates. + * @param index The index name to target. + * @param startDate The lower bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param endDate The upper bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param tags Filter metrics on the provided tags. Each tag must correspond to an analyticsTags set at search time. Multiple tags can be combined with the operators OR and AND. If a tag contains characters like spaces or parentheses, it should be URL encoded. + * @param requestOptions additional request configuration. + */ + public suspend fun getConversationRate(index: String, startDate: String? = null, endDate: String? = null, tags: String? = null, requestOptions: RequestOptions? = null): GetConversationRateResponse { + require(index.isNotBlank()) { "Parameter `index` is required when calling `getConversationRate`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("2", "conversions", "conversionRate"), + query = buildMap { + put("index", index) + startDate?.let { put("startDate", it) } + endDate?.let { put("endDate", it) } + tags?.let { put("tags", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get no click rate. + * Returns the rate at which searches didn't lead to any clicks. The endpoint returns a value for the complete given time range, as well as a value per day. It also returns the count of searches and searches without clicks. + * @param index The index name to target. + * @param startDate The lower bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param endDate The upper bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param tags Filter metrics on the provided tags. Each tag must correspond to an analyticsTags set at search time. Multiple tags can be combined with the operators OR and AND. If a tag contains characters like spaces or parentheses, it should be URL encoded. + * @param requestOptions additional request configuration. + */ + public suspend fun getNoClickRate(index: String, startDate: String? = null, endDate: String? = null, tags: String? = null, requestOptions: RequestOptions? = null): GetNoClickRateResponse { + require(index.isNotBlank()) { "Parameter `index` is required when calling `getNoClickRate`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("2", "searches", "noClickRate"), + query = buildMap { + put("index", index) + startDate?.let { put("startDate", it) } + endDate?.let { put("endDate", it) } + tags?.let { put("tags", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get no results rate. + * Returns the rate at which searches didn't return any results. The endpoint returns a value for the complete given time range, as well as a value per day. It also returns the count of searches and searches without results used to compute the rates. + * @param index The index name to target. + * @param startDate The lower bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param endDate The upper bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param tags Filter metrics on the provided tags. Each tag must correspond to an analyticsTags set at search time. Multiple tags can be combined with the operators OR and AND. If a tag contains characters like spaces or parentheses, it should be URL encoded. + * @param requestOptions additional request configuration. + */ + public suspend fun getNoResultsRate(index: String, startDate: String? = null, endDate: String? = null, tags: String? = null, requestOptions: RequestOptions? = null): GetNoResultsRateResponse { + require(index.isNotBlank()) { "Parameter `index` is required when calling `getNoResultsRate`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("2", "searches", "noResultRate"), + query = buildMap { + put("index", index) + startDate?.let { put("startDate", it) } + endDate?.let { put("endDate", it) } + tags?.let { put("tags", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get searches count. + * Returns the number of searches across the given time range. The endpoint returns a value for the complete given time range, as well as a value per day. + * @param index The index name to target. + * @param startDate The lower bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param endDate The upper bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param tags Filter metrics on the provided tags. Each tag must correspond to an analyticsTags set at search time. Multiple tags can be combined with the operators OR and AND. If a tag contains characters like spaces or parentheses, it should be URL encoded. + * @param requestOptions additional request configuration. + */ + public suspend fun getSearchesCount(index: String, startDate: String? = null, endDate: String? = null, tags: String? = null, requestOptions: RequestOptions? = null): GetSearchesCountResponse { + require(index.isNotBlank()) { "Parameter `index` is required when calling `getSearchesCount`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("2", "searches", "count"), + query = buildMap { + put("index", index) + startDate?.let { put("startDate", it) } + endDate?.let { put("endDate", it) } + tags?.let { put("tags", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get top searches with no clicks. + * Returns top searches that didn't lead to any clicks. Limited to the 1000 most frequent ones. For each search, also returns the average number of found hits. + * @param index The index name to target. + * @param startDate The lower bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param endDate The upper bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param limit Number of records to return. Limit is the size of the page. (default to 10) + * @param offset Position of the starting record. Used for paging. 0 is the first record. (default to 0) + * @param tags Filter metrics on the provided tags. Each tag must correspond to an analyticsTags set at search time. Multiple tags can be combined with the operators OR and AND. If a tag contains characters like spaces or parentheses, it should be URL encoded. + * @param requestOptions additional request configuration. + */ + public suspend fun getSearchesNoClicks(index: String, startDate: String? = null, endDate: String? = null, limit: Int? = null, offset: Int? = null, tags: String? = null, requestOptions: RequestOptions? = null): GetSearchesNoClicksResponse { + require(index.isNotBlank()) { "Parameter `index` is required when calling `getSearchesNoClicks`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("2", "searches", "noClicks"), + query = buildMap { + put("index", index) + startDate?.let { put("startDate", it) } + endDate?.let { put("endDate", it) } + limit?.let { put("limit", it) } + offset?.let { put("offset", it) } + tags?.let { put("tags", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get top searches with no results. + * Returns top searches that didn't return any results. Limited to the 1000 most frequent ones. + * @param index The index name to target. + * @param startDate The lower bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param endDate The upper bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param limit Number of records to return. Limit is the size of the page. (default to 10) + * @param offset Position of the starting record. Used for paging. 0 is the first record. (default to 0) + * @param tags Filter metrics on the provided tags. Each tag must correspond to an analyticsTags set at search time. Multiple tags can be combined with the operators OR and AND. If a tag contains characters like spaces or parentheses, it should be URL encoded. + * @param requestOptions additional request configuration. + */ + public suspend fun getSearchesNoResults(index: String, startDate: String? = null, endDate: String? = null, limit: Int? = null, offset: Int? = null, tags: String? = null, requestOptions: RequestOptions? = null): GetSearchesNoResultsResponse { + require(index.isNotBlank()) { "Parameter `index` is required when calling `getSearchesNoResults`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("2", "searches", "noResults"), + query = buildMap { + put("index", index) + startDate?.let { put("startDate", it) } + endDate?.let { put("endDate", it) } + limit?.let { put("limit", it) } + offset?.let { put("offset", it) } + tags?.let { put("tags", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get Analytics API status. + * Returns the latest update time of the analytics API for a given index. If the index has been recently created and/or no search has been performed yet the updated time will be null. + * @param index The index name to target. + * @param requestOptions additional request configuration. + */ + public suspend fun getStatus(index: String, requestOptions: RequestOptions? = null): GetStatusResponse { + require(index.isNotBlank()) { "Parameter `index` is required when calling `getStatus`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("2", "status"), + query = buildMap { + put("index", index) + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get top countries. + * Returns top countries. Limited to the 1000 most frequent ones. + * @param index The index name to target. + * @param startDate The lower bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param endDate The upper bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param limit Number of records to return. Limit is the size of the page. (default to 10) + * @param offset Position of the starting record. Used for paging. 0 is the first record. (default to 0) + * @param tags Filter metrics on the provided tags. Each tag must correspond to an analyticsTags set at search time. Multiple tags can be combined with the operators OR and AND. If a tag contains characters like spaces or parentheses, it should be URL encoded. + * @param requestOptions additional request configuration. + */ + public suspend fun getTopCountries(index: String, startDate: String? = null, endDate: String? = null, limit: Int? = null, offset: Int? = null, tags: String? = null, requestOptions: RequestOptions? = null): GetTopCountriesResponse { + require(index.isNotBlank()) { "Parameter `index` is required when calling `getTopCountries`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("2", "countries"), + query = buildMap { + put("index", index) + startDate?.let { put("startDate", it) } + endDate?.let { put("endDate", it) } + limit?.let { put("limit", it) } + offset?.let { put("offset", it) } + tags?.let { put("tags", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get top filter attributes. + * Returns top filter attributes. Limited to the 1000 most used filters. + * @param index The index name to target. + * @param search The query term to search for. Must match the exact user input. + * @param startDate The lower bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param endDate The upper bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param limit Number of records to return. Limit is the size of the page. (default to 10) + * @param offset Position of the starting record. Used for paging. 0 is the first record. (default to 0) + * @param tags Filter metrics on the provided tags. Each tag must correspond to an analyticsTags set at search time. Multiple tags can be combined with the operators OR and AND. If a tag contains characters like spaces or parentheses, it should be URL encoded. + * @param requestOptions additional request configuration. + */ + public suspend fun getTopFilterAttributes(index: String, search: String? = null, startDate: String? = null, endDate: String? = null, limit: Int? = null, offset: Int? = null, tags: String? = null, requestOptions: RequestOptions? = null): GetTopFilterAttributesResponse { + require(index.isNotBlank()) { "Parameter `index` is required when calling `getTopFilterAttributes`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("2", "filters"), + query = buildMap { + put("index", index) + search?.let { put("search", it) } + startDate?.let { put("startDate", it) } + endDate?.let { put("endDate", it) } + limit?.let { put("limit", it) } + offset?.let { put("offset", it) } + tags?.let { put("tags", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get top filters for the an attribute. + * Returns top filters for the given attribute. Limited to the 1000 most used filters. + * @param attribute The exact name of the attribute. + * @param index The index name to target. + * @param search The query term to search for. Must match the exact user input. + * @param startDate The lower bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param endDate The upper bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param limit Number of records to return. Limit is the size of the page. (default to 10) + * @param offset Position of the starting record. Used for paging. 0 is the first record. (default to 0) + * @param tags Filter metrics on the provided tags. Each tag must correspond to an analyticsTags set at search time. Multiple tags can be combined with the operators OR and AND. If a tag contains characters like spaces or parentheses, it should be URL encoded. + * @param requestOptions additional request configuration. + */ + public suspend fun getTopFilterForAttribute(attribute: String, index: String, search: String? = null, startDate: String? = null, endDate: String? = null, limit: Int? = null, offset: Int? = null, tags: String? = null, requestOptions: RequestOptions? = null): GetTopFilterForAttributeResponse { + require(attribute.isNotBlank()) { "Parameter `attribute` is required when calling `getTopFilterForAttribute`." } + require(index.isNotBlank()) { "Parameter `index` is required when calling `getTopFilterForAttribute`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("2", "filters", "$attribute"), + query = buildMap { + put("index", index) + search?.let { put("search", it) } + startDate?.let { put("startDate", it) } + endDate?.let { put("endDate", it) } + limit?.let { put("limit", it) } + offset?.let { put("offset", it) } + tags?.let { put("tags", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get top filters for a no result search. + * Returns top filters with no results. Limited to the 1000 most used filters. + * @param index The index name to target. + * @param search The query term to search for. Must match the exact user input. + * @param startDate The lower bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param endDate The upper bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param limit Number of records to return. Limit is the size of the page. (default to 10) + * @param offset Position of the starting record. Used for paging. 0 is the first record. (default to 0) + * @param tags Filter metrics on the provided tags. Each tag must correspond to an analyticsTags set at search time. Multiple tags can be combined with the operators OR and AND. If a tag contains characters like spaces or parentheses, it should be URL encoded. + * @param requestOptions additional request configuration. + */ + public suspend fun getTopFiltersNoResults(index: String, search: String? = null, startDate: String? = null, endDate: String? = null, limit: Int? = null, offset: Int? = null, tags: String? = null, requestOptions: RequestOptions? = null): GetTopFiltersNoResultsResponse { + require(index.isNotBlank()) { "Parameter `index` is required when calling `getTopFiltersNoResults`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("2", "filters", "noResults"), + query = buildMap { + put("index", index) + search?.let { put("search", it) } + startDate?.let { put("startDate", it) } + endDate?.let { put("endDate", it) } + limit?.let { put("limit", it) } + offset?.let { put("offset", it) } + tags?.let { put("tags", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get top hits. + * Returns top hits. Limited to the 1000 most frequent ones. + * @param index The index name to target. + * @param search The query term to search for. Must match the exact user input. + * @param clickAnalytics Whether to include the click-through and conversion rates for a search. (default to false) + * @param startDate The lower bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param endDate The upper bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param limit Number of records to return. Limit is the size of the page. (default to 10) + * @param offset Position of the starting record. Used for paging. 0 is the first record. (default to 0) + * @param tags Filter metrics on the provided tags. Each tag must correspond to an analyticsTags set at search time. Multiple tags can be combined with the operators OR and AND. If a tag contains characters like spaces or parentheses, it should be URL encoded. + * @param requestOptions additional request configuration. + */ + public suspend fun getTopHits(index: String, search: String? = null, clickAnalytics: Boolean? = null, startDate: String? = null, endDate: String? = null, limit: Int? = null, offset: Int? = null, tags: String? = null, requestOptions: RequestOptions? = null): GetTopHitsResponse { + require(index.isNotBlank()) { "Parameter `index` is required when calling `getTopHits`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("2", "hits"), + query = buildMap { + put("index", index) + search?.let { put("search", it) } + clickAnalytics?.let { put("clickAnalytics", it) } + startDate?.let { put("startDate", it) } + endDate?.let { put("endDate", it) } + limit?.let { put("limit", it) } + offset?.let { put("offset", it) } + tags?.let { put("tags", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get top searches. + * Returns top searches. Limited to the 1000 most frequent ones. For each search, also returns the average number of hits returned. + * @param index The index name to target. + * @param clickAnalytics Whether to include the click-through and conversion rates for a search. (default to false) + * @param startDate The lower bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param endDate The upper bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param orderBy Reorder the results. (default to searchCount) + * @param direction The sorting of the result. (default to asc) + * @param limit Number of records to return. Limit is the size of the page. (default to 10) + * @param offset Position of the starting record. Used for paging. 0 is the first record. (default to 0) + * @param tags Filter metrics on the provided tags. Each tag must correspond to an analyticsTags set at search time. Multiple tags can be combined with the operators OR and AND. If a tag contains characters like spaces or parentheses, it should be URL encoded. + * @param requestOptions additional request configuration. + */ + public suspend fun getTopSearches(index: String, clickAnalytics: Boolean? = null, startDate: String? = null, endDate: String? = null, orderBy: OrderBy? = null, direction: Direction? = null, limit: Int? = null, offset: Int? = null, tags: String? = null, requestOptions: RequestOptions? = null): GetTopSearchesResponse { + require(index.isNotBlank()) { "Parameter `index` is required when calling `getTopSearches`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("2", "searches"), + query = buildMap { + put("index", index) + clickAnalytics?.let { put("clickAnalytics", it) } + startDate?.let { put("startDate", it) } + endDate?.let { put("endDate", it) } + orderBy?.let { put("orderBy", it) } + direction?.let { put("direction", it) } + limit?.let { put("limit", it) } + offset?.let { put("offset", it) } + tags?.let { put("tags", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get users count. + * Returns the distinct count of users across the given time range. The endpoint returns a value for the complete given time range, as well as a value per day. + * @param index The index name to target. + * @param startDate The lower bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param endDate The upper bound timestamp (a date, a string like \"2006-01-02\") of the period to analyze. + * @param tags Filter metrics on the provided tags. Each tag must correspond to an analyticsTags set at search time. Multiple tags can be combined with the operators OR and AND. If a tag contains characters like spaces or parentheses, it should be URL encoded. + * @param requestOptions additional request configuration. + */ + public suspend fun getUsersCount(index: String, startDate: String? = null, endDate: String? = null, tags: String? = null, requestOptions: RequestOptions? = null): GetUsersCountResponse { + require(index.isNotBlank()) { "Parameter `index` is required when calling `getUsersCount`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("2", "users", "count"), + query = buildMap { + put("index", index) + startDate?.let { put("startDate", it) } + endDate?.let { put("endDate", it) } + tags?.let { put("tags", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param body The parameters to send with the custom request. + * @param requestOptions additional request configuration. + */ + public suspend fun post(path: String, parameters: Map? = null, body: JsonObject? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `post`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + body = body, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param body The parameters to send with the custom request. + * @param requestOptions additional request configuration. + */ + public suspend fun put(path: String, parameters: Map? = null, body: JsonObject? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `put`." } + val requestConfig = RequestConfig( + method = RequestMethod.PUT, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + body = body, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/ApiClient.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/ApiClient.kt new file mode 100644 index 0000000000..55f5c3a006 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/ApiClient.kt @@ -0,0 +1,18 @@ +package com.algolia.client.api + +import com.algolia.client.configuration.ClientOptions +import com.algolia.client.transport.Requester + +/** + * An interface representing an API client with specific properties and options. + * + * @property appId The unique identifier for the application using the API client. + * @property apiKey The API key used for authentication. + * @property options A set of custom client options to configure the behavior of the API client. + */ +public sealed interface ApiClient { + public val appId: String + public val apiKey: String + public val options: ClientOptions + public val requester: Requester +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/IngestionClient.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/IngestionClient.kt new file mode 100644 index 0000000000..67da400e1b --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/IngestionClient.kt @@ -0,0 +1,770 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.api + +import com.algolia.client.configuration.* +import com.algolia.client.exception.* +import com.algolia.client.extensions.internal.* +import com.algolia.client.model.ingestion.* +import com.algolia.client.transport.* +import com.algolia.client.transport.internal.* +import kotlinx.serialization.json.* + +public class IngestionClient( + override val appId: String, + override val apiKey: String, + public val region: String, + override val options: ClientOptions = ClientOptions(), +) : ApiClient { + + init { + require(appId.isNotBlank()) { "`appId` is missing." } + require(apiKey.isNotBlank()) { "`apiKey` is missing." } + } + + override val requester: Requester = requesterOf(clientName = "Ingestion", appId = appId, apiKey = apiKey, options = options) { + val allowedRegions = listOf("eu", "us") + require(region in allowedRegions) { "`region` is required and must be one of the following: ${allowedRegions.joinToString()}" } + val url = "data.$region.algolia.com" + listOf(Host(url)) + } + + /** + * Create a authentication. + * Create a authentication. + * @param authenticationCreate + * @param requestOptions additional request configuration. + */ + public suspend fun createAuthentication(authenticationCreate: AuthenticationCreate, requestOptions: RequestOptions? = null): AuthenticationCreateResponse { + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "authentications"), + body = authenticationCreate, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Create a destination. + * Create a destination. + * @param destinationCreate + * @param requestOptions additional request configuration. + */ + public suspend fun createDestination(destinationCreate: DestinationCreate, requestOptions: RequestOptions? = null): DestinationCreateResponse { + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "destinations"), + body = destinationCreate, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Create a source. + * Create a source. + * @param sourceCreate + * @param requestOptions additional request configuration. + */ + public suspend fun createSource(sourceCreate: SourceCreate, requestOptions: RequestOptions? = null): SourceCreateResponse { + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "sources"), + body = sourceCreate, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Create a task. + * Create a task. + * @param taskCreate + * @param requestOptions additional request configuration. + */ + public suspend fun createTask(taskCreate: TaskCreate, requestOptions: RequestOptions? = null): TaskCreateResponse { + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "tasks"), + body = taskCreate, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param requestOptions additional request configuration. + */ + public suspend fun del(path: String, parameters: Map? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `del`." } + val requestConfig = RequestConfig( + method = RequestMethod.DELETE, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Delete a authentication. + * Soft delete the authentication of the given authenticationID. + * @param authenticationID The authentication UUID. + * @param requestOptions additional request configuration. + */ + public suspend fun deleteAuthentication(authenticationID: String, requestOptions: RequestOptions? = null): DeleteResponse { + require(authenticationID.isNotBlank()) { "Parameter `authenticationID` is required when calling `deleteAuthentication`." } + val requestConfig = RequestConfig( + method = RequestMethod.DELETE, + path = listOf("1", "authentications", "$authenticationID"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Delete a destination. + * Soft delete the destination of the given destinationID. + * @param destinationID The destination UUID. + * @param requestOptions additional request configuration. + */ + public suspend fun deleteDestination(destinationID: String, requestOptions: RequestOptions? = null): DeleteResponse { + require(destinationID.isNotBlank()) { "Parameter `destinationID` is required when calling `deleteDestination`." } + val requestConfig = RequestConfig( + method = RequestMethod.DELETE, + path = listOf("1", "destinations", "$destinationID"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Delete a source. + * Soft delete the source of the given sourceID. + * @param sourceID The source UUID. + * @param requestOptions additional request configuration. + */ + public suspend fun deleteSource(sourceID: String, requestOptions: RequestOptions? = null): DeleteResponse { + require(sourceID.isNotBlank()) { "Parameter `sourceID` is required when calling `deleteSource`." } + val requestConfig = RequestConfig( + method = RequestMethod.DELETE, + path = listOf("1", "sources", "$sourceID"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Delete a task. + * Soft delete the task of the given taskID. + * @param taskID The task UUID. + * @param requestOptions additional request configuration. + */ + public suspend fun deleteTask(taskID: String, requestOptions: RequestOptions? = null): DeleteResponse { + require(taskID.isNotBlank()) { "Parameter `taskID` is required when calling `deleteTask`." } + val requestConfig = RequestConfig( + method = RequestMethod.DELETE, + path = listOf("1", "tasks", "$taskID"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Disable a task. + * Disable the task of the given taskID. + * @param taskID The task UUID. + * @param requestOptions additional request configuration. + */ + public suspend fun disableTask(taskID: String, requestOptions: RequestOptions? = null): TaskUpdateResponse { + require(taskID.isNotBlank()) { "Parameter `taskID` is required when calling `disableTask`." } + val requestConfig = RequestConfig( + method = RequestMethod.PUT, + path = listOf("1", "tasks", "$taskID", "disable"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Enable a task. + * Enable the task of the given taskID. + * @param taskID The task UUID. + * @param requestOptions additional request configuration. + */ + public suspend fun enableTask(taskID: String, requestOptions: RequestOptions? = null): TaskUpdateResponse { + require(taskID.isNotBlank()) { "Parameter `taskID` is required when calling `enableTask`." } + val requestConfig = RequestConfig( + method = RequestMethod.PUT, + path = listOf("1", "tasks", "$taskID", "enable"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param requestOptions additional request configuration. + */ + public suspend fun get(path: String, parameters: Map? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `get`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get a authentication. + * Get the authentication of the given authenticationID. + * @param authenticationID The authentication UUID. + * @param requestOptions additional request configuration. + */ + public suspend fun getAuthentication(authenticationID: String, requestOptions: RequestOptions? = null): AuthenticationWithInput { + require(authenticationID.isNotBlank()) { "Parameter `authenticationID` is required when calling `getAuthentication`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "authentications", "$authenticationID"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get a list of authentications. + * Get a list of authentications for the given query parameters, with pagination details. + * @param itemsPerPage The number of items per page to return. + * @param page The page number to fetch, starting at 1. + * @param type The type of the authentications to retrieve. + * @param platform The platform of the authentications to retrieve. + * @param sort The key by which the list should be sorted. + * @param order The order of the returned list. + * @param requestOptions additional request configuration. + */ + public suspend fun getAuthentications(itemsPerPage: Int? = null, page: Int? = null, type: List? = null, platform: List? = null, sort: AuthenticationSortKeys? = null, order: OrderKeys? = null, requestOptions: RequestOptions? = null): ListAuthenticationsResponse { + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "authentications"), + query = buildMap { + itemsPerPage?.let { put("itemsPerPage", it) } + page?.let { put("page", it) } + type?.let { put("type", it.joinToString(",")) } + platform?.let { put("platform", it.joinToString(",")) } + sort?.let { put("sort", it) } + order?.let { put("order", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get a destination. + * Get the destination of the given destinationID. + * @param destinationID The destination UUID. + * @param requestOptions additional request configuration. + */ + public suspend fun getDestination(destinationID: String, requestOptions: RequestOptions? = null): Destination { + require(destinationID.isNotBlank()) { "Parameter `destinationID` is required when calling `getDestination`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "destinations", "$destinationID"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get a list of destinations. + * Get a list of destinations for the given query parameters, with pagination details. + * @param itemsPerPage The number of items per page to return. + * @param page The page number to fetch, starting at 1. + * @param type The type of the destinations to retrive. + * @param authenticationID The authenticationIDs of the destinations to retrive. + * @param sort The key by which the list should be sorted. + * @param order The order of the returned list. + * @param requestOptions additional request configuration. + */ + public suspend fun getDestinations(itemsPerPage: Int? = null, page: Int? = null, type: List? = null, authenticationID: List? = null, sort: DestinationSortKeys? = null, order: OrderKeys? = null, requestOptions: RequestOptions? = null): ListDestinationsResponse { + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "destinations"), + query = buildMap { + itemsPerPage?.let { put("itemsPerPage", it) } + page?.let { put("page", it) } + type?.let { put("type", it.joinToString(",")) } + authenticationID?.let { put("authenticationID", it.joinToString(",")) } + sort?.let { put("sort", it) } + order?.let { put("order", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get an event. + * Get a single event for a specific runID. + * @param runID The run UUID. + * @param eventID The event UUID. + * @param requestOptions additional request configuration. + */ + public suspend fun getEvent(runID: String, eventID: String, requestOptions: RequestOptions? = null): Event { + require(runID.isNotBlank()) { "Parameter `runID` is required when calling `getEvent`." } + require(eventID.isNotBlank()) { "Parameter `eventID` is required when calling `getEvent`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "runs", "$runID", "events", "$eventID"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get a list of events. + * Get a list of events associated to the given runID, for the given query parameters. + * @param runID The run UUID. + * @param itemsPerPage The number of items per page to return. + * @param page The page number to fetch, starting at 1. + * @param status Filter the status of the events. + * @param type Filter the type of the events. + * @param sort The key by which the list should be sorted. + * @param order The order of the returned list. + * @param requestOptions additional request configuration. + */ + public suspend fun getEvents(runID: String, itemsPerPage: Int? = null, page: Int? = null, status: List? = null, type: List? = null, sort: EventSortKeys? = null, order: OrderKeys? = null, requestOptions: RequestOptions? = null): ListEventsResponse { + require(runID.isNotBlank()) { "Parameter `runID` is required when calling `getEvents`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "runs", "$runID", "events"), + query = buildMap { + itemsPerPage?.let { put("itemsPerPage", it) } + page?.let { put("page", it) } + status?.let { put("status", it.joinToString(",")) } + type?.let { put("type", it.joinToString(",")) } + sort?.let { put("sort", it) } + order?.let { put("order", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get a run. + * Get a single run for the given ID. + * @param runID The run UUID. + * @param requestOptions additional request configuration. + */ + public suspend fun getRun(runID: String, requestOptions: RequestOptions? = null): Run { + require(runID.isNotBlank()) { "Parameter `runID` is required when calling `getRun`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "runs", "$runID"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get a list of runs. + * Get a list of runs for the given query parameters, with pagination details. + * @param itemsPerPage The number of items per page to return. + * @param page The page number to fetch, starting at 1. + * @param status Filter the status of the runs. + * @param taskID Filter by taskID. + * @param sort The key by which the list should be sorted. + * @param order The order of the returned list. + * @param requestOptions additional request configuration. + */ + public suspend fun getRuns(itemsPerPage: Int? = null, page: Int? = null, status: List? = null, taskID: String? = null, sort: RunSortKeys? = null, order: OrderKeys? = null, requestOptions: RequestOptions? = null): RunListResponse { + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "runs"), + query = buildMap { + itemsPerPage?.let { put("itemsPerPage", it) } + page?.let { put("page", it) } + status?.let { put("status", it.joinToString(",")) } + taskID?.let { put("taskID", it) } + sort?.let { put("sort", it) } + order?.let { put("order", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get a source. + * Get the source of the given sourceID. + * @param sourceID The source UUID. + * @param requestOptions additional request configuration. + */ + public suspend fun getSource(sourceID: String, requestOptions: RequestOptions? = null): Source { + require(sourceID.isNotBlank()) { "Parameter `sourceID` is required when calling `getSource`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "sources", "$sourceID"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get a list of sources. + * Get a list of sources for the given query parameters, with pagination details. + * @param itemsPerPage The number of items per page to return. + * @param page The page number to fetch, starting at 1. + * @param type The type of the sources to retrieve. + * @param authenticationID The authenticationIDs of the sources to retrieve. 'none' returns sources that doesn't have an authentication. + * @param sort The key by which the list should be sorted. + * @param order The order of the returned list. + * @param requestOptions additional request configuration. + */ + public suspend fun getSources(itemsPerPage: Int? = null, page: Int? = null, type: List? = null, authenticationID: List? = null, sort: SourceSortKeys? = null, order: OrderKeys? = null, requestOptions: RequestOptions? = null): ListSourcesResponse { + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "sources"), + query = buildMap { + itemsPerPage?.let { put("itemsPerPage", it) } + page?.let { put("page", it) } + type?.let { put("type", it.joinToString(",")) } + authenticationID?.let { put("authenticationID", it.joinToString(",")) } + sort?.let { put("sort", it) } + order?.let { put("order", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get a task. + * Get the task of the given taskID. + * @param taskID The task UUID. + * @param requestOptions additional request configuration. + */ + public suspend fun getTask(taskID: String, requestOptions: RequestOptions? = null): Task { + require(taskID.isNotBlank()) { "Parameter `taskID` is required when calling `getTask`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "tasks", "$taskID"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get a list of tasks. + * Get a list of tasks for the given query parameters, with pagination details. + * @param itemsPerPage The number of items per page to return. + * @param page The page number to fetch, starting at 1. + * @param action The action of the tasks to retrieve. + * @param enabled Whether the task is enabled or not. + * @param sourceID The sourceIDs of the tasks to retrive. + * @param destinationID The destinationIDs of the tasks to retrive. + * @param triggerType The trigger type of the task. + * @param sort The key by which the list should be sorted. + * @param order The order of the returned list. + * @param requestOptions additional request configuration. + */ + public suspend fun getTasks(itemsPerPage: Int? = null, page: Int? = null, action: List? = null, enabled: Boolean? = null, sourceID: List? = null, destinationID: List? = null, triggerType: List? = null, sort: TaskSortKeys? = null, order: OrderKeys? = null, requestOptions: RequestOptions? = null): ListTasksResponse { + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "tasks"), + query = buildMap { + itemsPerPage?.let { put("itemsPerPage", it) } + page?.let { put("page", it) } + action?.let { put("action", it.joinToString(",")) } + enabled?.let { put("enabled", it) } + sourceID?.let { put("sourceID", it.joinToString(",")) } + destinationID?.let { put("destinationID", it.joinToString(",")) } + triggerType?.let { put("triggerType", it.joinToString(",")) } + sort?.let { put("sort", it) } + order?.let { put("order", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param body The parameters to send with the custom request. + * @param requestOptions additional request configuration. + */ + public suspend fun post(path: String, parameters: Map? = null, body: JsonObject? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `post`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + body = body, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param body The parameters to send with the custom request. + * @param requestOptions additional request configuration. + */ + public suspend fun put(path: String, parameters: Map? = null, body: JsonObject? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `put`." } + val requestConfig = RequestConfig( + method = RequestMethod.PUT, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + body = body, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Run a task. + * Run the task of the given taskID. + * @param taskID The task UUID. + * @param requestOptions additional request configuration. + */ + public suspend fun runTask(taskID: String, requestOptions: RequestOptions? = null): RunResponse { + require(taskID.isNotBlank()) { "Parameter `taskID` is required when calling `runTask`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "tasks", "$taskID", "run"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Search among authentications. + * Search among authentications with a defined set of parameters. + * @param authenticationSearch + * @param requestOptions additional request configuration. + */ + public suspend fun searchAuthentications(authenticationSearch: AuthenticationSearch, requestOptions: RequestOptions? = null): List { + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "authentications", "search"), + body = authenticationSearch, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Search among destinations. + * Search among destinations with a defined set of parameters. + * @param destinationSearch + * @param requestOptions additional request configuration. + */ + public suspend fun searchDestinations(destinationSearch: DestinationSearch, requestOptions: RequestOptions? = null): List { + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "destinations", "search"), + body = destinationSearch, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Search among sources. + * Search among sources with a defined set of parameters. + * @param sourceSearch + * @param requestOptions additional request configuration. + */ + public suspend fun searchSources(sourceSearch: SourceSearch, requestOptions: RequestOptions? = null): List { + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "sources", "search"), + body = sourceSearch, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Search among tasks. + * Search among tasks with a defined set of parameters. + * @param taskSearch + * @param requestOptions additional request configuration. + */ + public suspend fun searchTasks(taskSearch: TaskSearch, requestOptions: RequestOptions? = null): List { + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "tasks", "search"), + body = taskSearch, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Update a authentication. + * Update the authentication of the given authenticationID. + * @param authenticationID The authentication UUID. + * @param authenticationUpdate + * @param requestOptions additional request configuration. + */ + public suspend fun updateAuthentication(authenticationID: String, authenticationUpdate: AuthenticationUpdate, requestOptions: RequestOptions? = null): AuthenticationUpdateResponse { + require(authenticationID.isNotBlank()) { "Parameter `authenticationID` is required when calling `updateAuthentication`." } + val requestConfig = RequestConfig( + method = RequestMethod.PUT, + path = listOf("1", "authentications", "$authenticationID"), + body = authenticationUpdate, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Update a destination. + * Update the destination of the given destinationID. + * @param destinationID The destination UUID. + * @param destinationUpdate + * @param requestOptions additional request configuration. + */ + public suspend fun updateDestination(destinationID: String, destinationUpdate: DestinationUpdate, requestOptions: RequestOptions? = null): DestinationUpdateResponse { + require(destinationID.isNotBlank()) { "Parameter `destinationID` is required when calling `updateDestination`." } + val requestConfig = RequestConfig( + method = RequestMethod.PUT, + path = listOf("1", "destinations", "$destinationID"), + body = destinationUpdate, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Update a source. + * Update the source of the given sourceID. + * @param sourceID The source UUID. + * @param sourceUpdate + * @param requestOptions additional request configuration. + */ + public suspend fun updateSource(sourceID: String, sourceUpdate: SourceUpdate, requestOptions: RequestOptions? = null): SourceUpdateResponse { + require(sourceID.isNotBlank()) { "Parameter `sourceID` is required when calling `updateSource`." } + val requestConfig = RequestConfig( + method = RequestMethod.PUT, + path = listOf("1", "sources", "$sourceID"), + body = sourceUpdate, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Update a task. + * Update the task of the given taskID. + * @param taskID The task UUID. + * @param taskUpdate + * @param requestOptions additional request configuration. + */ + public suspend fun updateTask(taskID: String, taskUpdate: TaskUpdate, requestOptions: RequestOptions? = null): TaskUpdateResponse { + require(taskID.isNotBlank()) { "Parameter `taskID` is required when calling `updateTask`." } + val requestConfig = RequestConfig( + method = RequestMethod.PUT, + path = listOf("1", "tasks", "$taskID"), + body = taskUpdate, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/InsightsClient.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/InsightsClient.kt new file mode 100644 index 0000000000..12b88ced4f --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/InsightsClient.kt @@ -0,0 +1,140 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.api + +import com.algolia.client.configuration.* +import com.algolia.client.exception.* +import com.algolia.client.extensions.internal.* +import com.algolia.client.model.insights.* +import com.algolia.client.transport.* +import com.algolia.client.transport.internal.* +import kotlinx.serialization.json.* + +public class InsightsClient( + override val appId: String, + override val apiKey: String, + public val region: String? = null, + override val options: ClientOptions = ClientOptions(), +) : ApiClient { + + init { + require(appId.isNotBlank()) { "`appId` is missing." } + require(apiKey.isNotBlank()) { "`apiKey` is missing." } + } + + override val requester: Requester = requesterOf(clientName = "Insights", appId = appId, apiKey = apiKey, options = options) { + val allowedRegions = listOf("de", "us") + require(region == null || region in allowedRegions) { "`region` must be one of the following: ${allowedRegions.joinToString()}" } + val url = if (region == null) "insights.algolia.io" else "insights.$region.algolia.io" + listOf(Host(url)) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param requestOptions additional request configuration. + */ + public suspend fun del(path: String, parameters: Map? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `del`." } + val requestConfig = RequestConfig( + method = RequestMethod.DELETE, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param requestOptions additional request configuration. + */ + public suspend fun get(path: String, parameters: Map? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `get`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param body The parameters to send with the custom request. + * @param requestOptions additional request configuration. + */ + public suspend fun post(path: String, parameters: Map? = null, body: JsonObject? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `post`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + body = body, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Push events. + * This command pushes an array of events. An event is - an action: `eventName` - performed in a context: `eventType` - at some point in time provided: `timestamp` - by an end user: `userToken` - on something: `index` Notes: - To be accepted, all events sent must be valid. - The size of the body must be *less than 2 MB*. - When an event is tied to an Algolia search, it must also provide a `queryID`. If that event is a `click`, their absolute `positions` should also be passed. - We consider that an `index` provides access to 2 resources: objects and filters. An event can only interact with a single resource type, but not necessarily on a single item. As such an event will accept an array of `objectIDs` or `filters`. + * @param insightEvents + * @param requestOptions additional request configuration. + */ + public suspend fun pushEvents(insightEvents: InsightEvents, requestOptions: RequestOptions? = null): PushEventsResponse { + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "events"), + body = insightEvents, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param body The parameters to send with the custom request. + * @param requestOptions additional request configuration. + */ + public suspend fun put(path: String, parameters: Map? = null, body: JsonObject? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `put`." } + val requestConfig = RequestConfig( + method = RequestMethod.PUT, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + body = body, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/PersonalizationClient.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/PersonalizationClient.kt new file mode 100644 index 0000000000..cde863d273 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/PersonalizationClient.kt @@ -0,0 +1,192 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.api + +import com.algolia.client.configuration.* +import com.algolia.client.exception.* +import com.algolia.client.extensions.internal.* +import com.algolia.client.model.personalization.* +import com.algolia.client.transport.* +import com.algolia.client.transport.internal.* +import kotlinx.serialization.json.* + +public class PersonalizationClient( + override val appId: String, + override val apiKey: String, + public val region: String, + override val options: ClientOptions = ClientOptions(), +) : ApiClient { + + init { + require(appId.isNotBlank()) { "`appId` is missing." } + require(apiKey.isNotBlank()) { "`apiKey` is missing." } + } + + override val requester: Requester = requesterOf(clientName = "Personalization", appId = appId, apiKey = apiKey, options = options) { + val allowedRegions = listOf("eu", "us") + require(region in allowedRegions) { "`region` is required and must be one of the following: ${allowedRegions.joinToString()}" } + val url = "personalization.$region.algolia.com" + listOf(Host(url)) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param requestOptions additional request configuration. + */ + public suspend fun del(path: String, parameters: Map? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `del`." } + val requestConfig = RequestConfig( + method = RequestMethod.DELETE, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Delete a user profile. + * Delete the user profile and all its associated data. Returns, as part of the response, a date until which the data can safely be considered as deleted for the given user. This means if you send events for the given user before this date, they will be ignored. Any data received after the deletedUntil date will start building a new user profile. It might take a couple hours for the deletion request to be fully processed. + * @param userToken userToken representing the user for which to fetch the Personalization profile. + * @param requestOptions additional request configuration. + */ + public suspend fun deleteUserProfile(userToken: String, requestOptions: RequestOptions? = null): DeleteUserProfileResponse { + require(userToken.isNotBlank()) { "Parameter `userToken` is required when calling `deleteUserProfile`." } + val requestConfig = RequestConfig( + method = RequestMethod.DELETE, + path = listOf("1", "profiles", "$userToken"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param requestOptions additional request configuration. + */ + public suspend fun get(path: String, parameters: Map? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `get`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get the current strategy. + * The strategy contains information on the events and facets that impact user profiles and personalized search results. + * @param requestOptions additional request configuration. + */ + public suspend fun getPersonalizationStrategy(requestOptions: RequestOptions? = null): PersonalizationStrategyParams { + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "strategies", "personalization"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get a user profile. + * Get the user profile built from Personalization strategy. The profile is structured by facet name used in the strategy. Each facet value is mapped to its score. Each score represents the user affinity for a specific facet value given the userToken past events and the Personalization strategy defined. Scores are bounded to 20. The last processed event timestamp is provided using the ISO 8601 format for debugging purposes. + * @param userToken userToken representing the user for which to fetch the Personalization profile. + * @param requestOptions additional request configuration. + */ + public suspend fun getUserTokenProfile(userToken: String, requestOptions: RequestOptions? = null): GetUserTokenResponse { + require(userToken.isNotBlank()) { "Parameter `userToken` is required when calling `getUserTokenProfile`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "profiles", "personalization", "$userToken"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param body The parameters to send with the custom request. + * @param requestOptions additional request configuration. + */ + public suspend fun post(path: String, parameters: Map? = null, body: JsonObject? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `post`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + body = body, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param body The parameters to send with the custom request. + * @param requestOptions additional request configuration. + */ + public suspend fun put(path: String, parameters: Map? = null, body: JsonObject? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `put`." } + val requestConfig = RequestConfig( + method = RequestMethod.PUT, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + body = body, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Set a new strategy. + * A strategy defines the events and facets that impact user profiles and personalized search results. + * @param personalizationStrategyParams + * @param requestOptions additional request configuration. + */ + public suspend fun setPersonalizationStrategy(personalizationStrategyParams: PersonalizationStrategyParams, requestOptions: RequestOptions? = null): SetPersonalizationStrategyResponse { + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "strategies", "personalization"), + body = personalizationStrategyParams, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/PredictClient.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/PredictClient.kt new file mode 100644 index 0000000000..434a11c667 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/PredictClient.kt @@ -0,0 +1,416 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.api + +import com.algolia.client.configuration.* +import com.algolia.client.exception.* +import com.algolia.client.extensions.internal.* +import com.algolia.client.model.predict.* +import com.algolia.client.transport.* +import com.algolia.client.transport.internal.* +import kotlinx.serialization.json.* + +public class PredictClient( + override val appId: String, + override val apiKey: String, + public val region: String, + override val options: ClientOptions = ClientOptions(), +) : ApiClient { + + init { + require(appId.isNotBlank()) { "`appId` is missing." } + require(apiKey.isNotBlank()) { "`apiKey` is missing." } + } + + override val requester: Requester = requesterOf(clientName = "Predict", appId = appId, apiKey = apiKey, options = options) { + val allowedRegions = listOf("eu", "us") + require(region in allowedRegions) { "`region` is required and must be one of the following: ${allowedRegions.joinToString()}" } + val url = "predict.$region.algolia.com" + listOf(Host(url)) + } + + /** + * Activate a model instance. + * Activate an existing model template. This action triggers the training and inference pipelines for the selected model. The model is added with `modelStatus=pending`. If a model with the exact same source & index already exists, the API endpoint returns an error. + * @param activateModelParams + * @param requestOptions additional request configuration. + */ + public suspend fun activateModelInstance(activateModelParams: ActivateModelParams, requestOptions: RequestOptions? = null): ActivateModelInstanceResponse { + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "predict", "models"), + body = activateModelParams, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Create a segment. + * Create a new segment. All segments added by this endpoint will have a computed type. The endpoint receives a filters parameter, with a syntax similar to filters for Rules. + * @param createSegmentParams + * @param requestOptions additional request configuration. + */ + public suspend fun createSegment(createSegmentParams: CreateSegmentParams, requestOptions: RequestOptions? = null): CreateSegmentResponse { + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "segments"), + body = createSegmentParams, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param requestOptions additional request configuration. + */ + public suspend fun del(path: String, parameters: Map? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `del`." } + val requestConfig = RequestConfig( + method = RequestMethod.DELETE, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Delete a model instance. + * Delete the model’s configuration, pipelines and generated predictions. + * @param modelID The ID of the model to retrieve. + * @param requestOptions additional request configuration. + */ + public suspend fun deleteModelInstance(modelID: String, requestOptions: RequestOptions? = null): DeleteModelInstanceResponse { + require(modelID.isNotBlank()) { "Parameter `modelID` is required when calling `deleteModelInstance`." } + val requestConfig = RequestConfig( + method = RequestMethod.DELETE, + path = listOf("1", "predict", "models", "$modelID"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Delete a segment's configuration. + * Delete the segment’s configuration. User intents (predictions) from the segment are not deleted. All segment types (computed or custom) can be deleted. When the query is successful, the HTTP response is 200 OK and returns the date until which you can safely consider the data as being deleted. + * @param segmentID The ID of the Segment to fetch. + * @param requestOptions additional request configuration. + */ + public suspend fun deleteSegment(segmentID: String, requestOptions: RequestOptions? = null): DeleteSegmentResponse { + require(segmentID.isNotBlank()) { "Parameter `segmentID` is required when calling `deleteSegment`." } + val requestConfig = RequestConfig( + method = RequestMethod.DELETE, + path = listOf("1", "segments", "$segmentID"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Delete user profile. + * Delete all data and predictions associated with an authenticated user (userID) or an anonymous user (cookieID, sessionID). + * @param userID User ID for authenticated users or cookie ID for non-authenticated repeated users (visitors). + * @param requestOptions additional request configuration. + */ + public suspend fun deleteUserProfile(userID: String, requestOptions: RequestOptions? = null): DeleteUserProfileResponse { + require(userID.isNotBlank()) { "Parameter `userID` is required when calling `deleteUserProfile`." } + val requestConfig = RequestConfig( + method = RequestMethod.DELETE, + path = listOf("1", "users", "$userID"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get all segments. + * Get the list of segments with their configuration. + * @param type The type of segments to fetch. + * @param requestOptions additional request configuration. + */ + public suspend fun fetchAllSegments(type: SegmentType? = null, requestOptions: RequestOptions? = null): List { + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "segments"), + query = buildMap { + type?.let { put("type", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get all user profiles. + * Get all users with predictions in the provided application. + * @param fetchAllUserProfilesParams + * @param requestOptions additional request configuration. + */ + public suspend fun fetchAllUserProfiles(fetchAllUserProfilesParams: FetchAllUserProfilesParams, requestOptions: RequestOptions? = null): FetchAllUserProfilesResponse { + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "users"), + body = fetchAllUserProfilesParams, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get the segment configuration. + * Get the segment configuration. + * @param segmentID The ID of the Segment to fetch. + * @param requestOptions additional request configuration. + */ + public suspend fun fetchSegment(segmentID: String, requestOptions: RequestOptions? = null): Segment { + require(segmentID.isNotBlank()) { "Parameter `segmentID` is required when calling `fetchSegment`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "segments", "$segmentID"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get user profile. + * Get predictions, properties (raw, computed or custom) and segments (computed or custom) for a user profile. + * @param userID User ID for authenticated users or cookie ID for non-authenticated repeated users (visitors). + * @param params + * @param requestOptions additional request configuration. + */ + public suspend fun fetchUserProfile(userID: String, params: Params, requestOptions: RequestOptions? = null): UserProfile { + require(userID.isNotBlank()) { "Parameter `userID` is required when calling `fetchUserProfile`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "users", "$userID", "fetch"), + body = params, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param requestOptions additional request configuration. + */ + public suspend fun get(path: String, parameters: Map? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `get`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get a list of available model types. + * Get a list of all available model types. Each model type can be activated more than once, by selecting a different data source. + * @param requestOptions additional request configuration. + */ + public suspend fun getAvailableModelTypes(requestOptions: RequestOptions? = null): List { + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "predict", "modeltypes"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get a model’s instance configuration. + * Get the configuration for a model that was activated. + * @param modelID The ID of the model to retrieve. + * @param requestOptions additional request configuration. + */ + public suspend fun getModelInstanceConfig(modelID: String, requestOptions: RequestOptions? = null): ModelInstance { + require(modelID.isNotBlank()) { "Parameter `modelID` is required when calling `getModelInstanceConfig`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "predict", "models", "$modelID"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get model instances. + * Get a list of all model instances. + * @param requestOptions additional request configuration. + */ + public suspend fun getModelInstances(requestOptions: RequestOptions? = null): List { + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "predict", "models"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get a model’s instance metrics. + * Get the model instance’ training metrics. + * @param modelID The ID of the model to retrieve. + * @param requestOptions additional request configuration. + */ + public suspend fun getModelMetrics(modelID: String, requestOptions: RequestOptions? = null): GetModelMetricsResponse { + require(modelID.isNotBlank()) { "Parameter `modelID` is required when calling `getModelMetrics`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "predict", "models", "$modelID", "metrics"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get segment users. + * Get the profiles of users that belong to a segment. + * @param segmentID The ID of the Segment to fetch. + * @param fetchAllUserProfilesParams + * @param requestOptions additional request configuration. + */ + public suspend fun getSegmentUsers(segmentID: String, fetchAllUserProfilesParams: FetchAllUserProfilesParams, requestOptions: RequestOptions? = null): GetSegmentUsersResponse { + require(segmentID.isNotBlank()) { "Parameter `segmentID` is required when calling `getSegmentUsers`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "segments", "$segmentID", "users"), + body = fetchAllUserProfilesParams, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param body The parameters to send with the custom request. + * @param requestOptions additional request configuration. + */ + public suspend fun post(path: String, parameters: Map? = null, body: JsonObject? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `post`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + body = body, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param body The parameters to send with the custom request. + * @param requestOptions additional request configuration. + */ + public suspend fun put(path: String, parameters: Map? = null, body: JsonObject? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `put`." } + val requestConfig = RequestConfig( + method = RequestMethod.PUT, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + body = body, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Update a model instance. + * Update a model’s configuration. + * @param modelID The ID of the model to retrieve. + * @param updateModelParams + * @param requestOptions additional request configuration. + */ + public suspend fun updateModelInstance(modelID: String, updateModelParams: UpdateModelParams, requestOptions: RequestOptions? = null): UpdateModelInstanceResponse { + require(modelID.isNotBlank()) { "Parameter `modelID` is required when calling `updateModelInstance`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "predict", "models", "$modelID"), + body = updateModelParams, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Update segment. + * Update a segment’s configuration. + * @param segmentID The ID of the Segment to fetch. + * @param updateSegmentParams + * @param requestOptions additional request configuration. + */ + public suspend fun updateSegment(segmentID: String, updateSegmentParams: UpdateSegmentParams, requestOptions: RequestOptions? = null): UpdateSegmentResponse { + require(segmentID.isNotBlank()) { "Parameter `segmentID` is required when calling `updateSegment`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "segments", "$segmentID"), + body = updateSegmentParams, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/QuerySuggestionsClient.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/QuerySuggestionsClient.kt new file mode 100644 index 0000000000..15ecd43672 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/QuerySuggestionsClient.kt @@ -0,0 +1,248 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.api + +import com.algolia.client.configuration.* +import com.algolia.client.exception.* +import com.algolia.client.extensions.internal.* +import com.algolia.client.model.querysuggestions.* +import com.algolia.client.transport.* +import com.algolia.client.transport.internal.* +import kotlinx.serialization.json.* + +public class QuerySuggestionsClient( + override val appId: String, + override val apiKey: String, + public val region: String, + override val options: ClientOptions = ClientOptions(), +) : ApiClient { + + init { + require(appId.isNotBlank()) { "`appId` is missing." } + require(apiKey.isNotBlank()) { "`apiKey` is missing." } + } + + override val requester: Requester = requesterOf(clientName = "QuerySuggestions", appId = appId, apiKey = apiKey, options = options) { + val allowedRegions = listOf("eu", "us") + require(region in allowedRegions) { "`region` is required and must be one of the following: ${allowedRegions.joinToString()}" } + val url = "query-suggestions.$region.algolia.com" + listOf(Host(url)) + } + + /** + * Create a configuration. + * Create a configuration of a Query Suggestions index. There's a limit of 100 configurations per application. + * @param querySuggestionsIndexWithIndexParam + * @param requestOptions additional request configuration. + */ + public suspend fun createConfig(querySuggestionsIndexWithIndexParam: QuerySuggestionsIndexWithIndexParam, requestOptions: RequestOptions? = null): SuccessResponse { + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "configs"), + body = querySuggestionsIndexWithIndexParam, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param requestOptions additional request configuration. + */ + public suspend fun del(path: String, parameters: Map? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `del`." } + val requestConfig = RequestConfig( + method = RequestMethod.DELETE, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Delete a configuration. + * Delete a configuration of a Query Suggestion's index. By deleting a configuration, you stop all updates to the underlying query suggestion index. Note that when doing this, the underlying index does not change - existing suggestions remain untouched. + * @param indexName The index in which to perform the request. + * @param requestOptions additional request configuration. + */ + public suspend fun deleteConfig(indexName: String, requestOptions: RequestOptions? = null): SuccessResponse { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `deleteConfig`." } + val requestConfig = RequestConfig( + method = RequestMethod.DELETE, + path = listOf("1", "configs", "$indexName"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param requestOptions additional request configuration. + */ + public suspend fun get(path: String, parameters: Map? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `get`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * List configurations. + * Get all the configurations of Query Suggestions. For each index, you get a block of JSON with a list of its configuration settings. + * @param requestOptions additional request configuration. + */ + public suspend fun getAllConfigs(requestOptions: RequestOptions? = null): List { + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "configs"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get a single configuration. + * Get the configuration of a single Query Suggestions index. + * @param indexName The index in which to perform the request. + * @param requestOptions additional request configuration. + */ + public suspend fun getConfig(indexName: String, requestOptions: RequestOptions? = null): QuerySuggestionsIndex { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `getConfig`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "configs", "$indexName"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get configuration status. + * Get the status of a Query Suggestion's index. The status includes whether the Query Suggestions index is currently in the process of being built, and the last build time. + * @param indexName The index in which to perform the request. + * @param requestOptions additional request configuration. + */ + public suspend fun getConfigStatus(indexName: String, requestOptions: RequestOptions? = null): Status { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `getConfigStatus`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "configs", "$indexName", "status"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get a log file. + * Get the log file of the last build of a single Query Suggestion index. + * @param indexName The index in which to perform the request. + * @param requestOptions additional request configuration. + */ + public suspend fun getLogFile(indexName: String, requestOptions: RequestOptions? = null): List { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `getLogFile`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "logs", "$indexName"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param body The parameters to send with the custom request. + * @param requestOptions additional request configuration. + */ + public suspend fun post(path: String, parameters: Map? = null, body: JsonObject? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `post`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + body = body, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param body The parameters to send with the custom request. + * @param requestOptions additional request configuration. + */ + public suspend fun put(path: String, parameters: Map? = null, body: JsonObject? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `put`." } + val requestConfig = RequestConfig( + method = RequestMethod.PUT, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + body = body, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Update a configuration. + * Update the configuration of a Query Suggestions index. + * @param indexName The index in which to perform the request. + * @param querySuggestionsIndexParam + * @param requestOptions additional request configuration. + */ + public suspend fun updateConfig(indexName: String, querySuggestionsIndexParam: QuerySuggestionsIndexParam, requestOptions: RequestOptions? = null): SuccessResponse { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `updateConfig`." } + val requestConfig = RequestConfig( + method = RequestMethod.PUT, + path = listOf("1", "configs", "$indexName"), + body = querySuggestionsIndexParam, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/RecommendClient.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/RecommendClient.kt new file mode 100644 index 0000000000..f02e9eadfd --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/RecommendClient.kt @@ -0,0 +1,144 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.api + +import com.algolia.client.configuration.* +import com.algolia.client.exception.* +import com.algolia.client.extensions.internal.* +import com.algolia.client.model.recommend.* +import com.algolia.client.transport.* +import com.algolia.client.transport.internal.* +import kotlinx.serialization.json.* + +public class RecommendClient( + override val appId: String, + override val apiKey: String, + override val options: ClientOptions = ClientOptions(), +) : ApiClient { + + init { + require(appId.isNotBlank()) { "`appId` is missing." } + require(apiKey.isNotBlank()) { "`apiKey` is missing." } + } + + override val requester: Requester = requesterOf(clientName = "Recommend", appId = appId, apiKey = apiKey, options = options) { + listOf( + Host("$appId-dsn.algolia.net", CallType.Read), + Host("$appId.algolia.net", CallType.Write), + ) + mutableListOf( + Host("$appId-1.algolianet.com"), + Host("$appId-2.algolianet.com"), + Host("$appId-3.algolianet.com"), + ).apply { shuffle() } + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param requestOptions additional request configuration. + */ + public suspend fun del(path: String, parameters: Map? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `del`." } + val requestConfig = RequestConfig( + method = RequestMethod.DELETE, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param requestOptions additional request configuration. + */ + public suspend fun get(path: String, parameters: Map? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `get`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get results. + * Returns recommendations or trending results, for a specific model and `objectID`. + * @param getRecommendationsParams + * @param requestOptions additional request configuration. + */ + public suspend fun getRecommendations(getRecommendationsParams: GetRecommendationsParams, requestOptions: RequestOptions? = null): GetRecommendationsResponse { + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "indexes", "*", "recommendations"), + isRead = true, + body = getRecommendationsParams, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param body The parameters to send with the custom request. + * @param requestOptions additional request configuration. + */ + public suspend fun post(path: String, parameters: Map? = null, body: JsonObject? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `post`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + body = body, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param body The parameters to send with the custom request. + * @param requestOptions additional request configuration. + */ + public suspend fun put(path: String, parameters: Map? = null, body: JsonObject? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `put`." } + val requestConfig = RequestConfig( + method = RequestMethod.PUT, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + body = body, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/SearchClient.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/SearchClient.kt new file mode 100644 index 0000000000..fcaf562794 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/api/SearchClient.kt @@ -0,0 +1,1290 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.api + +import com.algolia.client.configuration.* +import com.algolia.client.exception.* +import com.algolia.client.extensions.internal.* +import com.algolia.client.model.search.* +import com.algolia.client.transport.* +import com.algolia.client.transport.internal.* +import kotlinx.serialization.json.* + +public class SearchClient( + override val appId: String, + override val apiKey: String, + override val options: ClientOptions = ClientOptions(), +) : ApiClient { + + init { + require(appId.isNotBlank()) { "`appId` is missing." } + require(apiKey.isNotBlank()) { "`apiKey` is missing." } + } + + override val requester: Requester = requesterOf(clientName = "Search", appId = appId, apiKey = apiKey, options = options) { + listOf( + Host("$appId-dsn.algolia.net", CallType.Read), + Host("$appId.algolia.net", CallType.Write), + ) + mutableListOf( + Host("$appId-1.algolianet.com"), + Host("$appId-2.algolianet.com"), + Host("$appId-3.algolianet.com"), + ).apply { shuffle() } + } + + /** + * Create an API key. + * Add a new API Key with specific permissions/restrictions. + * @param apiKey + * @param requestOptions additional request configuration. + */ + public suspend fun addApiKey(apiKey: ApiKey, requestOptions: RequestOptions? = null): AddApiKeyResponse { + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "keys"), + body = apiKey, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Add or replace an object. + * Add or replace an object with a given object ID. If the object does not exist, it will be created. If it already exists, it will be replaced. + * @param indexName The index in which to perform the request. + * @param objectID Unique identifier of an object. + * @param body The Algolia object. + * @param requestOptions additional request configuration. + */ + public suspend fun addOrUpdateObject(indexName: String, objectID: String, body: JsonObject, requestOptions: RequestOptions? = null): UpdatedAtWithObjectIdResponse { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `addOrUpdateObject`." } + require(objectID.isNotBlank()) { "Parameter `objectID` is required when calling `addOrUpdateObject`." } + require(body.isNotEmpty()) { "Parameter `body` is required when calling `addOrUpdateObject`." } + val requestConfig = RequestConfig( + method = RequestMethod.PUT, + path = listOf("1", "indexes", "$indexName", "$objectID"), + body = body, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Add a single source. + * Add a single source to the list of allowed sources. + * @param source The source to add. + * @param requestOptions additional request configuration. + */ + public suspend fun appendSource(source: Source, requestOptions: RequestOptions? = null): CreatedAtResponse { + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "security", "sources", "append"), + body = source, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Assign or Move userID. + * Assign or Move a userID to a cluster. The time it takes to migrate (move) a user is proportional to the amount of data linked to the userID. Upon success, the response is 200 OK. A successful response indicates that the operation has been taken into account, and the userID is directly usable. + * @param xAlgoliaUserID userID to assign. + * @param assignUserIdParams + * @param requestOptions additional request configuration. + */ + public suspend fun assignUserId(xAlgoliaUserID: String, assignUserIdParams: AssignUserIdParams, requestOptions: RequestOptions? = null): CreatedAtResponse { + require(xAlgoliaUserID.isNotBlank()) { "Parameter `xAlgoliaUserID` is required when calling `assignUserId`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "clusters", "mapping"), + headers = buildMap { + put("X-Algolia-User-ID", xAlgoliaUserID) + }, + body = assignUserIdParams, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Batch operations to one index. + * Perform multiple write operations targeting one index, in a single API call. + * @param indexName The index in which to perform the request. + * @param batchWriteParams + * @param requestOptions additional request configuration. + */ + public suspend fun batch(indexName: String, batchWriteParams: BatchWriteParams, requestOptions: RequestOptions? = null): BatchResponse { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `batch`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "indexes", "$indexName", "batch"), + body = batchWriteParams, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Batch assign userIDs. + * Assign multiple userIDs to a cluster. Upon success, the response is 200 OK. A successful response indicates that the operation has been taken into account, and the userIDs are directly usable. + * @param xAlgoliaUserID userID to assign. + * @param batchAssignUserIdsParams + * @param requestOptions additional request configuration. + */ + public suspend fun batchAssignUserIds(xAlgoliaUserID: String, batchAssignUserIdsParams: BatchAssignUserIdsParams, requestOptions: RequestOptions? = null): CreatedAtResponse { + require(xAlgoliaUserID.isNotBlank()) { "Parameter `xAlgoliaUserID` is required when calling `batchAssignUserIds`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "clusters", "mapping", "batch"), + headers = buildMap { + put("X-Algolia-User-ID", xAlgoliaUserID) + }, + body = batchAssignUserIdsParams, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Batch dictionary entries. + * Send a batch of dictionary entries. + * @param dictionaryName The dictionary to search in. + * @param batchDictionaryEntriesParams + * @param requestOptions additional request configuration. + */ + public suspend fun batchDictionaryEntries(dictionaryName: DictionaryType, batchDictionaryEntriesParams: BatchDictionaryEntriesParams, requestOptions: RequestOptions? = null): UpdatedAtResponse { + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "dictionaries", "$dictionaryName", "batch"), + body = batchDictionaryEntriesParams, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Retrieve all index content. + * This method allows you to retrieve all index content. It can retrieve up to 1,000 records per call and supports full text search and filters. For performance reasons, some features are not supported, including `distinct`, sorting by `typos`, `words` or `geo distance`. When there is more content to be browsed, the response contains a cursor field. This cursor has to be passed to the subsequent call to browse in order to get the next page of results. When the end of the index has been reached, the cursor field is absent from the response. + * @param indexName The index in which to perform the request. + * @param browseParams + * @param requestOptions additional request configuration. + */ + public suspend fun browse(indexName: String, browseParams: BrowseParams? = null, requestOptions: RequestOptions? = null): BrowseResponse { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `browse`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "indexes", "$indexName", "browse"), + body = browseParams, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Clear all synonyms. + * Remove all synonyms from an index. + * @param indexName The index in which to perform the request. + * @param forwardToReplicas When true, changes are also propagated to replicas of the given indexName. + * @param requestOptions additional request configuration. + */ + public suspend fun clearAllSynonyms(indexName: String, forwardToReplicas: Boolean? = null, requestOptions: RequestOptions? = null): UpdatedAtResponse { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `clearAllSynonyms`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "indexes", "$indexName", "synonyms", "clear"), + query = buildMap { + forwardToReplicas?.let { put("forwardToReplicas", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Clear all objects from an index. + * Delete an index's content, but leave settings and index-specific API keys untouched. + * @param indexName The index in which to perform the request. + * @param requestOptions additional request configuration. + */ + public suspend fun clearObjects(indexName: String, requestOptions: RequestOptions? = null): UpdatedAtResponse { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `clearObjects`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "indexes", "$indexName", "clear"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Clear Rules. + * Delete all Rules in the index. + * @param indexName The index in which to perform the request. + * @param forwardToReplicas When true, changes are also propagated to replicas of the given indexName. + * @param requestOptions additional request configuration. + */ + public suspend fun clearRules(indexName: String, forwardToReplicas: Boolean? = null, requestOptions: RequestOptions? = null): UpdatedAtResponse { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `clearRules`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "indexes", "$indexName", "rules", "clear"), + query = buildMap { + forwardToReplicas?.let { put("forwardToReplicas", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param requestOptions additional request configuration. + */ + public suspend fun del(path: String, parameters: Map? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `del`." } + val requestConfig = RequestConfig( + method = RequestMethod.DELETE, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Delete an API key. + * Delete an existing API Key. + * @param key API Key string. + * @param requestOptions additional request configuration. + */ + public suspend fun deleteApiKey(key: String, requestOptions: RequestOptions? = null): DeleteApiKeyResponse { + require(key.isNotBlank()) { "Parameter `key` is required when calling `deleteApiKey`." } + val requestConfig = RequestConfig( + method = RequestMethod.DELETE, + path = listOf("1", "keys", "$key"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Delete all records matching the query. + * Remove all objects matching a filter (including geo filters). This method enables you to delete one or more objects based on filters (numeric, facet, tag or geo queries). It doesn't accept empty filters or a query. + * @param indexName The index in which to perform the request. + * @param deleteByParams + * @param requestOptions additional request configuration. + */ + public suspend fun deleteBy(indexName: String, deleteByParams: DeleteByParams, requestOptions: RequestOptions? = null): DeletedAtResponse { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `deleteBy`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "indexes", "$indexName", "deleteByQuery"), + body = deleteByParams, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Delete index. + * Delete an existing index. + * @param indexName The index in which to perform the request. + * @param requestOptions additional request configuration. + */ + public suspend fun deleteIndex(indexName: String, requestOptions: RequestOptions? = null): DeletedAtResponse { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `deleteIndex`." } + val requestConfig = RequestConfig( + method = RequestMethod.DELETE, + path = listOf("1", "indexes", "$indexName"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Delete an object. + * Delete an existing object. + * @param indexName The index in which to perform the request. + * @param objectID Unique identifier of an object. + * @param requestOptions additional request configuration. + */ + public suspend fun deleteObject(indexName: String, objectID: String, requestOptions: RequestOptions? = null): DeletedAtResponse { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `deleteObject`." } + require(objectID.isNotBlank()) { "Parameter `objectID` is required when calling `deleteObject`." } + val requestConfig = RequestConfig( + method = RequestMethod.DELETE, + path = listOf("1", "indexes", "$indexName", "$objectID"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Delete a rule. + * Delete the Rule with the specified objectID. + * @param indexName The index in which to perform the request. + * @param objectID Unique identifier of an object. + * @param forwardToReplicas When true, changes are also propagated to replicas of the given indexName. + * @param requestOptions additional request configuration. + */ + public suspend fun deleteRule(indexName: String, objectID: String, forwardToReplicas: Boolean? = null, requestOptions: RequestOptions? = null): UpdatedAtResponse { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `deleteRule`." } + require(objectID.isNotBlank()) { "Parameter `objectID` is required when calling `deleteRule`." } + val requestConfig = RequestConfig( + method = RequestMethod.DELETE, + path = listOf("1", "indexes", "$indexName", "rules", "$objectID"), + query = buildMap { + forwardToReplicas?.let { put("forwardToReplicas", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Remove a single source. + * Remove a single source from the list of allowed sources. + * @param source The IP range of the source. + * @param requestOptions additional request configuration. + */ + public suspend fun deleteSource(source: String, requestOptions: RequestOptions? = null): DeleteSourceResponse { + require(source.isNotBlank()) { "Parameter `source` is required when calling `deleteSource`." } + val requestConfig = RequestConfig( + method = RequestMethod.DELETE, + path = listOf("1", "security", "sources", "$source"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Delete synonym. + * Delete a single synonyms set, identified by the given objectID. + * @param indexName The index in which to perform the request. + * @param objectID Unique identifier of an object. + * @param forwardToReplicas When true, changes are also propagated to replicas of the given indexName. + * @param requestOptions additional request configuration. + */ + public suspend fun deleteSynonym(indexName: String, objectID: String, forwardToReplicas: Boolean? = null, requestOptions: RequestOptions? = null): DeletedAtResponse { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `deleteSynonym`." } + require(objectID.isNotBlank()) { "Parameter `objectID` is required when calling `deleteSynonym`." } + val requestConfig = RequestConfig( + method = RequestMethod.DELETE, + path = listOf("1", "indexes", "$indexName", "synonyms", "$objectID"), + query = buildMap { + forwardToReplicas?.let { put("forwardToReplicas", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param requestOptions additional request configuration. + */ + public suspend fun get(path: String, parameters: Map? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `get`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get an API key. + * Get the permissions of an API key. + * @param key API Key string. + * @param requestOptions additional request configuration. + */ + public suspend fun getApiKey(key: String, requestOptions: RequestOptions? = null): GetApiKeyResponse { + require(key.isNotBlank()) { "Parameter `key` is required when calling `getApiKey`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "keys", "$key"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * List available languages. + * List dictionaries supported per language. + * @param requestOptions additional request configuration. + */ + public suspend fun getDictionaryLanguages(requestOptions: RequestOptions? = null): Map { + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "dictionaries", "*", "languages"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Retrieve dictionaries settings. + * Retrieve dictionaries settings. The API stores languages whose standard entries are disabled. Fetch settings does not return false values. + * @param requestOptions additional request configuration. + */ + public suspend fun getDictionarySettings(requestOptions: RequestOptions? = null): GetDictionarySettingsResponse { + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "dictionaries", "*", "settings"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Return the latest log entries. + * Return the latest log entries. + * @param offset First entry to retrieve (zero-based). Log entries are sorted by decreasing date, therefore 0 designates the most recent log entry. (default to 0) + * @param length Maximum number of entries to retrieve. The maximum allowed value is 1000. (default to 10) + * @param indexName Index for which log entries should be retrieved. When omitted, log entries are retrieved across all indices. + * @param type Type of log entries to retrieve. When omitted, all log entries are retrieved. (default to all) + * @param requestOptions additional request configuration. + */ + public suspend fun getLogs(offset: Int? = null, length: Int? = null, indexName: String? = null, type: LogType? = null, requestOptions: RequestOptions? = null): GetLogsResponse { + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "logs"), + query = buildMap { + offset?.let { put("offset", it) } + length?.let { put("length", it) } + indexName?.let { put("indexName", it) } + type?.let { put("type", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Retrieve an object. + * Retrieve one object from the index. + * @param indexName The index in which to perform the request. + * @param objectID Unique identifier of an object. + * @param attributesToRetrieve List of attributes to retrieve. If not specified, all retrievable attributes are returned. + * @param requestOptions additional request configuration. + */ + public suspend fun getObject(indexName: String, objectID: String, attributesToRetrieve: List? = null, requestOptions: RequestOptions? = null): Map { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `getObject`." } + require(objectID.isNotBlank()) { "Parameter `objectID` is required when calling `getObject`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "indexes", "$indexName", "$objectID"), + query = buildMap { + attributesToRetrieve?.let { put("attributesToRetrieve", it.joinToString(",")) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Retrieve one or more objects. + * Retrieve one or more objects, potentially from different indices, in a single API call. + * @param getObjectsParams The Algolia object. + * @param requestOptions additional request configuration. + */ + public suspend fun getObjects(getObjectsParams: GetObjectsParams, requestOptions: RequestOptions? = null): GetObjectsResponse { + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "indexes", "*", "objects"), + isRead = true, + body = getObjectsParams, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get a rule. + * Retrieve the Rule with the specified objectID. + * @param indexName The index in which to perform the request. + * @param objectID Unique identifier of an object. + * @param requestOptions additional request configuration. + */ + public suspend fun getRule(indexName: String, objectID: String, requestOptions: RequestOptions? = null): Rule { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `getRule`." } + require(objectID.isNotBlank()) { "Parameter `objectID` is required when calling `getRule`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "indexes", "$indexName", "rules", "$objectID"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Retrieve settings of an index. + * Retrieve settings of an index. + * @param indexName The index in which to perform the request. + * @param requestOptions additional request configuration. + */ + public suspend fun getSettings(indexName: String, requestOptions: RequestOptions? = null): IndexSettings { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `getSettings`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "indexes", "$indexName", "settings"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * List all allowed sources. + * List all allowed sources. + * @param requestOptions additional request configuration. + */ + public suspend fun getSources(requestOptions: RequestOptions? = null): List { + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "security", "sources"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get synonym. + * Fetch a synonym object identified by its objectID. + * @param indexName The index in which to perform the request. + * @param objectID Unique identifier of an object. + * @param requestOptions additional request configuration. + */ + public suspend fun getSynonym(indexName: String, objectID: String, requestOptions: RequestOptions? = null): SynonymHit { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `getSynonym`." } + require(objectID.isNotBlank()) { "Parameter `objectID` is required when calling `getSynonym`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "indexes", "$indexName", "synonyms", "$objectID"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Check the status of a task. + * Check the current status of a given task. + * @param indexName The index in which to perform the request. + * @param taskID Unique identifier of an task. Numeric value (up to 64bits). + * @param requestOptions additional request configuration. + */ + public suspend fun getTask(indexName: String, taskID: Long, requestOptions: RequestOptions? = null): GetTaskResponse { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `getTask`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "indexes", "$indexName", "task", "$taskID"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get top userID. + * Get the top 10 userIDs with the highest number of records per cluster. The data returned will usually be a few seconds behind real time, because userID usage may take up to a few seconds to propagate to the different clusters. Upon success, the response is 200 OK and contains the following array of userIDs and clusters. + * @param requestOptions additional request configuration. + */ + public suspend fun getTopUserIds(requestOptions: RequestOptions? = null): GetTopUserIdsResponse { + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "clusters", "mapping", "top"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get userID. + * Returns the userID data stored in the mapping. The data returned will usually be a few seconds behind real time, because userID usage may take up to a few seconds to propagate to the different clusters. Upon success, the response is 200 OK and contains the following userID data. + * @param userID userID to assign. + * @param requestOptions additional request configuration. + */ + public suspend fun getUserId(userID: String, requestOptions: RequestOptions? = null): UserId { + require(userID.isNotBlank()) { "Parameter `userID` is required when calling `getUserId`." } + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "clusters", "mapping", "$userID"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Get migration status. + * Get the status of your clusters' migrations or user creations. Creating a large batch of users or migrating your multi-cluster may take quite some time. This method lets you retrieve the status of the migration, so you can know when it's done. Upon success, the response is 200 OK. A successful response indicates that the operation has been taken into account, and the userIDs are directly usable. + * @param getClusters If the clusters pending mapping state should be on the response. + * @param requestOptions additional request configuration. + */ + public suspend fun hasPendingMappings(getClusters: Boolean? = null, requestOptions: RequestOptions? = null): HasPendingMappingsResponse { + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "clusters", "mapping", "pending"), + query = buildMap { + getClusters?.let { put("getClusters", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * List API Keys. + * List API keys, along with their associated rights. + * @param requestOptions additional request configuration. + */ + public suspend fun listApiKeys(requestOptions: RequestOptions? = null): ListApiKeysResponse { + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "keys"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * List clusters. + * List the clusters available in a multi-clusters setup for a single appID. Upon success, the response is 200 OK and contains the following clusters. + * @param requestOptions additional request configuration. + */ + public suspend fun listClusters(requestOptions: RequestOptions? = null): ListClustersResponse { + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "clusters"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * List existing indexes. + * List existing indexes from an application. + * @param page Requested page (zero-based). When specified, will retrieve a specific page; the page size is implicitly set to 100. When null, will retrieve all indices (no pagination). + * @param requestOptions additional request configuration. + */ + public suspend fun listIndices(page: Int? = null, requestOptions: RequestOptions? = null): ListIndicesResponse { + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "indexes"), + query = buildMap { + page?.let { put("page", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * List userIDs. + * List the userIDs assigned to a multi-clusters appID. The data returned will usually be a few seconds behind real time, because userID usage may take up to a few seconds to propagate to the different clusters. Upon success, the response is 200 OK and contains the following userIDs data. + * @param page Requested page (zero-based). When specified, will retrieve a specific page; the page size is implicitly set to 100. When null, will retrieve all indices (no pagination). + * @param hitsPerPage Maximum number of objects to retrieve. (default to 100) + * @param requestOptions additional request configuration. + */ + public suspend fun listUserIds(page: Int? = null, hitsPerPage: Int? = null, requestOptions: RequestOptions? = null): ListUserIdsResponse { + val requestConfig = RequestConfig( + method = RequestMethod.GET, + path = listOf("1", "clusters", "mapping"), + query = buildMap { + page?.let { put("page", it) } + hitsPerPage?.let { put("hitsPerPage", it) } + }, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Batch operations to many indices. + * Perform multiple write operations, potentially targeting multiple indices, in a single API call. + * @param batchParams + * @param requestOptions additional request configuration. + */ + public suspend fun multipleBatch(batchParams: BatchParams, requestOptions: RequestOptions? = null): MultipleBatchResponse { + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "indexes", "*", "batch"), + body = batchParams, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Copy/move index. + * Performs a copy or a move operation on a index. + * @param indexName The index in which to perform the request. + * @param operationIndexParams + * @param requestOptions additional request configuration. + */ + public suspend fun operationIndex(indexName: String, operationIndexParams: OperationIndexParams, requestOptions: RequestOptions? = null): UpdatedAtResponse { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `operationIndex`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "indexes", "$indexName", "operation"), + body = operationIndexParams, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Partially update an object. + * Update one or more attributes of an existing object. This method lets you update only a part of an existing object, either by adding new attributes or updating existing ones. You can partially update several objects in a single method call. If the index targeted by this operation doesn't exist yet, it's automatically created. + * @param indexName The index in which to perform the request. + * @param objectID Unique identifier of an object. + * @param attributesToUpdate Map of attribute(s) to update. + * @param createIfNotExists Creates the record if it does not exist yet. (default to true) + * @param requestOptions additional request configuration. + */ + public suspend fun partialUpdateObject(indexName: String, objectID: String, attributesToUpdate: Map, createIfNotExists: Boolean? = null, requestOptions: RequestOptions? = null): UpdatedAtWithObjectIdResponse { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `partialUpdateObject`." } + require(objectID.isNotBlank()) { "Parameter `objectID` is required when calling `partialUpdateObject`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "indexes", "$indexName", "$objectID", "partial"), + query = buildMap { + createIfNotExists?.let { put("createIfNotExists", it) } + }, + body = attributesToUpdate, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param body The parameters to send with the custom request. + * @param requestOptions additional request configuration. + */ + public suspend fun post(path: String, parameters: Map? = null, body: JsonObject? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `post`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + body = body, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Send requests to the Algolia REST API. + * This method allow you to send requests to the Algolia REST API. + * @param path The path of the API endpoint to target, anything after the /1 needs to be specified. + * @param parameters Query parameters to be applied to the current query. + * @param body The parameters to send with the custom request. + * @param requestOptions additional request configuration. + */ + public suspend fun put(path: String, parameters: Map? = null, body: JsonObject? = null, requestOptions: RequestOptions? = null): JsonObject { + require(path.isNotBlank()) { "Parameter `path` is required when calling `put`." } + val requestConfig = RequestConfig( + method = RequestMethod.PUT, + path = "/1{path}".replace("{path}", path), + query = buildMap { + parameters?.let { putAll(it) } + }, + body = body, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Remove userID. + * Remove a userID and its associated data from the multi-clusters. Upon success, the response is 200 OK and a task is created to remove the userID data and mapping. + * @param userID userID to assign. + * @param requestOptions additional request configuration. + */ + public suspend fun removeUserId(userID: String, requestOptions: RequestOptions? = null): RemoveUserIdResponse { + require(userID.isNotBlank()) { "Parameter `userID` is required when calling `removeUserId`." } + val requestConfig = RequestConfig( + method = RequestMethod.DELETE, + path = listOf("1", "clusters", "mapping", "$userID"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Replace all allowed sources. + * Replace all allowed sources. + * @param source The sources to allow. + * @param requestOptions additional request configuration. + */ + public suspend fun replaceSources(source: List, requestOptions: RequestOptions? = null): ReplaceSourceResponse { + val requestConfig = RequestConfig( + method = RequestMethod.PUT, + path = listOf("1", "security", "sources"), + body = source, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Restore an API key. + * Restore a deleted API key, along with its associated rights. + * @param key API Key string. + * @param requestOptions additional request configuration. + */ + public suspend fun restoreApiKey(key: String, requestOptions: RequestOptions? = null): AddApiKeyResponse { + require(key.isNotBlank()) { "Parameter `key` is required when calling `restoreApiKey`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "keys", "$key", "restore"), + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Add an object to the index. + * Add an object to the index, automatically assigning it an object ID. + * @param indexName The index in which to perform the request. + * @param body The Algolia record. + * @param requestOptions additional request configuration. + */ + public suspend fun saveObject(indexName: String, body: JsonObject, requestOptions: RequestOptions? = null): SaveObjectResponse { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `saveObject`." } + require(body.isNotEmpty()) { "Parameter `body` is required when calling `saveObject`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "indexes", "$indexName"), + body = body, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Save/Update a rule. + * Create or update the Rule with the specified objectID. + * @param indexName The index in which to perform the request. + * @param objectID Unique identifier of an object. + * @param rule + * @param forwardToReplicas When true, changes are also propagated to replicas of the given indexName. + * @param requestOptions additional request configuration. + */ + public suspend fun saveRule(indexName: String, objectID: String, rule: Rule, forwardToReplicas: Boolean? = null, requestOptions: RequestOptions? = null): UpdatedRuleResponse { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `saveRule`." } + require(objectID.isNotBlank()) { "Parameter `objectID` is required when calling `saveRule`." } + val requestConfig = RequestConfig( + method = RequestMethod.PUT, + path = listOf("1", "indexes", "$indexName", "rules", "$objectID"), + query = buildMap { + forwardToReplicas?.let { put("forwardToReplicas", it) } + }, + body = rule, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Save a batch of rules. + * Create/update multiple rules objects at once. + * @param indexName The index in which to perform the request. + * @param rules + * @param forwardToReplicas When true, changes are also propagated to replicas of the given indexName. + * @param clearExistingRules When true, existing Rules are cleared before adding this batch. When false, existing Rules are kept. + * @param requestOptions additional request configuration. + */ + public suspend fun saveRules(indexName: String, rules: List, forwardToReplicas: Boolean? = null, clearExistingRules: Boolean? = null, requestOptions: RequestOptions? = null): UpdatedAtResponse { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `saveRules`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "indexes", "$indexName", "rules", "batch"), + query = buildMap { + forwardToReplicas?.let { put("forwardToReplicas", it) } + clearExistingRules?.let { put("clearExistingRules", it) } + }, + body = rules, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Save synonym. + * Create a new synonym object or update the existing synonym object with the given object ID. + * @param indexName The index in which to perform the request. + * @param objectID Unique identifier of an object. + * @param synonymHit + * @param forwardToReplicas When true, changes are also propagated to replicas of the given indexName. + * @param requestOptions additional request configuration. + */ + public suspend fun saveSynonym(indexName: String, objectID: String, synonymHit: SynonymHit, forwardToReplicas: Boolean? = null, requestOptions: RequestOptions? = null): SaveSynonymResponse { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `saveSynonym`." } + require(objectID.isNotBlank()) { "Parameter `objectID` is required when calling `saveSynonym`." } + val requestConfig = RequestConfig( + method = RequestMethod.PUT, + path = listOf("1", "indexes", "$indexName", "synonyms", "$objectID"), + query = buildMap { + forwardToReplicas?.let { put("forwardToReplicas", it) } + }, + body = synonymHit, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Save a batch of synonyms. + * Create/update multiple synonym objects at once, potentially replacing the entire list of synonyms if replaceExistingSynonyms is true. + * @param indexName The index in which to perform the request. + * @param synonymHit + * @param forwardToReplicas When true, changes are also propagated to replicas of the given indexName. + * @param replaceExistingSynonyms Replace all synonyms of the index with the ones sent with this request. + * @param requestOptions additional request configuration. + */ + public suspend fun saveSynonyms(indexName: String, synonymHit: List, forwardToReplicas: Boolean? = null, replaceExistingSynonyms: Boolean? = null, requestOptions: RequestOptions? = null): UpdatedAtResponse { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `saveSynonyms`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "indexes", "$indexName", "synonyms", "batch"), + query = buildMap { + forwardToReplicas?.let { put("forwardToReplicas", it) } + replaceExistingSynonyms?.let { put("replaceExistingSynonyms", it) } + }, + body = synonymHit, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Search multiple indices. + * Perform a search operation targeting one or many indices. + * @param searchMethodParams The `search` requests and strategy. + * @param requestOptions additional request configuration. + */ + public suspend fun search(searchMethodParams: SearchMethodParams, requestOptions: RequestOptions? = null): SearchResponses { + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "indexes", "*", "queries"), + isRead = true, + body = searchMethodParams, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Search a dictionary entries. + * Search the dictionary entries. + * @param dictionaryName The dictionary to search in. + * @param searchDictionaryEntriesParams + * @param requestOptions additional request configuration. + */ + public suspend fun searchDictionaryEntries(dictionaryName: DictionaryType, searchDictionaryEntriesParams: SearchDictionaryEntriesParams, requestOptions: RequestOptions? = null): UpdatedAtResponse { + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "dictionaries", "$dictionaryName", "search"), + isRead = true, + body = searchDictionaryEntriesParams, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Search for values of a given facet. + * Search for values of a given facet, optionally restricting the returned values to those contained in objects matching other search criteria. + * @param indexName The index in which to perform the request. + * @param facetName The facet name. + * @param searchForFacetValuesRequest + * @param requestOptions additional request configuration. + */ + public suspend fun searchForFacetValues(indexName: String, facetName: String, searchForFacetValuesRequest: SearchForFacetValuesRequest? = null, requestOptions: RequestOptions? = null): SearchForFacetValuesResponse { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `searchForFacetValues`." } + require(facetName.isNotBlank()) { "Parameter `facetName` is required when calling `searchForFacetValues`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "indexes", "$indexName", "facets", "$facetName", "query"), + isRead = true, + body = searchForFacetValuesRequest, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Search for rules. + * Search for rules matching various criteria. + * @param indexName The index in which to perform the request. + * @param searchRulesParams + * @param requestOptions additional request configuration. + */ + public suspend fun searchRules(indexName: String, searchRulesParams: SearchRulesParams? = null, requestOptions: RequestOptions? = null): SearchRulesResponse { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `searchRules`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "indexes", "$indexName", "rules", "search"), + isRead = true, + body = searchRulesParams, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Search in a single index. + * Perform a search operation targeting one specific index. + * @param indexName The index in which to perform the request. + * @param searchParams + * @param requestOptions additional request configuration. + */ + public suspend fun searchSingleIndex(indexName: String, searchParams: SearchParams? = null, requestOptions: RequestOptions? = null): SearchResponse { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `searchSingleIndex`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "indexes", "$indexName", "query"), + isRead = true, + body = searchParams, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Search synonyms. + * Search or browse all synonyms, optionally filtering them by type. + * @param indexName The index in which to perform the request. + * @param type Only search for specific types of synonyms. + * @param page Requested page (zero-based). When specified, will retrieve a specific page; the page size is implicitly set to 100. When null, will retrieve all indices (no pagination). (default to 0) + * @param hitsPerPage Maximum number of objects to retrieve. (default to 100) + * @param searchSynonymsParams The body of the the `searchSynonyms` method. + * @param requestOptions additional request configuration. + */ + public suspend fun searchSynonyms(indexName: String, type: SynonymType? = null, page: Int? = null, hitsPerPage: Int? = null, searchSynonymsParams: SearchSynonymsParams? = null, requestOptions: RequestOptions? = null): SearchSynonymsResponse { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `searchSynonyms`." } + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "indexes", "$indexName", "synonyms", "search"), + isRead = true, + query = buildMap { + type?.let { put("type", it) } + page?.let { put("page", it) } + hitsPerPage?.let { put("hitsPerPage", it) } + }, + body = searchSynonymsParams, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Search userID. + * Search for userIDs. The data returned will usually be a few seconds behind real time, because userID usage may take up to a few seconds propagate to the different clusters. To keep updates moving quickly, the index of userIDs isn't built synchronously with the mapping. Instead, the index is built once every 12h, at the same time as the update of userID usage. For example, when you perform a modification like adding or moving a userID, the search will report an outdated value until the next rebuild of the mapping, which takes place every 12h. Upon success, the response is 200 OK and contains the following userIDs data. + * @param searchUserIdsParams + * @param requestOptions additional request configuration. + */ + public suspend fun searchUserIds(searchUserIdsParams: SearchUserIdsParams, requestOptions: RequestOptions? = null): SearchUserIdsResponse { + val requestConfig = RequestConfig( + method = RequestMethod.POST, + path = listOf("1", "clusters", "mapping", "search"), + isRead = true, + body = searchUserIdsParams, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Set dictionaries settings. + * Set dictionaries settings. + * @param dictionarySettingsParams + * @param requestOptions additional request configuration. + */ + public suspend fun setDictionarySettings(dictionarySettingsParams: DictionarySettingsParams, requestOptions: RequestOptions? = null): UpdatedAtResponse { + val requestConfig = RequestConfig( + method = RequestMethod.PUT, + path = listOf("1", "dictionaries", "*", "settings"), + body = dictionarySettingsParams, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Update settings of an index. + * Update settings of an index. Only specified settings are overridden; unspecified settings are left unchanged. Specifying null for a setting resets it to its default value. + * @param indexName The index in which to perform the request. + * @param indexSettings + * @param forwardToReplicas When true, changes are also propagated to replicas of the given indexName. + * @param requestOptions additional request configuration. + */ + public suspend fun setSettings(indexName: String, indexSettings: IndexSettings, forwardToReplicas: Boolean? = null, requestOptions: RequestOptions? = null): UpdatedAtResponse { + require(indexName.isNotBlank()) { "Parameter `indexName` is required when calling `setSettings`." } + val requestConfig = RequestConfig( + method = RequestMethod.PUT, + path = listOf("1", "indexes", "$indexName", "settings"), + query = buildMap { + forwardToReplicas?.let { put("forwardToReplicas", it) } + }, + body = indexSettings, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } + + /** + * Update an API key. + * Replace every permission of an existing API key. + * @param key API Key string. + * @param apiKey + * @param requestOptions additional request configuration. + */ + public suspend fun updateApiKey(key: String, apiKey: ApiKey, requestOptions: RequestOptions? = null): UpdateApiKeyResponse { + require(key.isNotBlank()) { "Parameter `key` is required when calling `updateApiKey`." } + val requestConfig = RequestConfig( + method = RequestMethod.PUT, + path = listOf("1", "keys", "$key"), + body = apiKey, + ) + return requester.execute( + requestConfig = requestConfig, + requestOptions = requestOptions, + ) + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/ABTest.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/ABTest.kt new file mode 100644 index 0000000000..f327c49c8e --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/ABTest.kt @@ -0,0 +1,49 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.abtesting + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * ABTest + * + * @param abTestID The A/B test ID. + * @param clickSignificance A/B test significance based on click data. Should be > 0.95 to be considered significant (no matter which variant is winning). + * @param conversionSignificance A/B test significance based on conversion data. Should be > 0.95 to be considered significant (no matter which variant is winning). + * @param endAt End date for the A/B test expressed as YYYY-MM-DDThh:mm:ssZ. + * @param updatedAt Update date for the A/B test expressed as YYYY-MM-DDThh:mm:ssZ. + * @param createdAt Creation date for the A/B test expressed as YYYY-MM-DDThh:mm:ssZ. + * @param name A/B test name. + * @param status status of the A/B test. + * @param variants List of A/B test variant. + */ +@Serializable +public data class ABTest( + + /** The A/B test ID. */ + @SerialName(value = "abTestID") val abTestID: Int, + + /** A/B test significance based on click data. Should be > 0.95 to be considered significant (no matter which variant is winning). */ + @SerialName(value = "clickSignificance") val clickSignificance: Double, + + /** A/B test significance based on conversion data. Should be > 0.95 to be considered significant (no matter which variant is winning). */ + @SerialName(value = "conversionSignificance") val conversionSignificance: Double, + + /** End date for the A/B test expressed as YYYY-MM-DDThh:mm:ssZ. */ + @SerialName(value = "endAt") val endAt: String, + + /** Update date for the A/B test expressed as YYYY-MM-DDThh:mm:ssZ. */ + @SerialName(value = "updatedAt") val updatedAt: String, + + /** Creation date for the A/B test expressed as YYYY-MM-DDThh:mm:ssZ. */ + @SerialName(value = "createdAt") val createdAt: String, + + /** A/B test name. */ + @SerialName(value = "name") val name: String, + + /** status of the A/B test. */ + @SerialName(value = "status") val status: String, + + /** List of A/B test variant. */ + @SerialName(value = "variants") val variants: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/ABTestResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/ABTestResponse.kt new file mode 100644 index 0000000000..43f93e3b46 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/ABTestResponse.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.abtesting + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * ABTestResponse + * + * @param index The index performing the A/B test. + * @param abTestID The A/B test ID. + * @param taskID taskID of the task to wait for. + */ +@Serializable +public data class ABTestResponse( + + /** The index performing the A/B test. */ + @SerialName(value = "index") val index: String, + + /** The A/B test ID. */ + @SerialName(value = "abTestID") val abTestID: Int, + + /** taskID of the task to wait for. */ + @SerialName(value = "taskID") val taskID: Long, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/AbTestsVariant.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/AbTestsVariant.kt new file mode 100644 index 0000000000..b9c1e55dbf --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/AbTestsVariant.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.abtesting + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * AbTestsVariant + * + * @param index The index performing the A/B test. + * @param trafficPercentage The traffic percentage for the A/B test. + * @param description The A/B test description. + */ +@Serializable +public data class AbTestsVariant( + + /** The index performing the A/B test. */ + @SerialName(value = "index") val index: String, + + /** The traffic percentage for the A/B test. */ + @SerialName(value = "trafficPercentage") val trafficPercentage: Int, + + /** The A/B test description. */ + @SerialName(value = "description") val description: String? = null, +) : AddABTestsVariant diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/AbTestsVariantSearchParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/AbTestsVariantSearchParams.kt new file mode 100644 index 0000000000..386c31a0a8 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/AbTestsVariantSearchParams.kt @@ -0,0 +1,28 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.abtesting + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * AbTestsVariantSearchParams + * + * @param index The index performing the A/B test. + * @param trafficPercentage The traffic percentage for the A/B test. + * @param customSearchParameters + * @param description The A/B test description. + */ +@Serializable +public data class AbTestsVariantSearchParams( + + /** The index performing the A/B test. */ + @SerialName(value = "index") val index: String, + + /** The traffic percentage for the A/B test. */ + @SerialName(value = "trafficPercentage") val trafficPercentage: Int, + + @SerialName(value = "customSearchParameters") val customSearchParameters: JsonObject, + + /** The A/B test description. */ + @SerialName(value = "description") val description: String? = null, +) : AddABTestsVariant diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/AddABTestsRequest.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/AddABTestsRequest.kt new file mode 100644 index 0000000000..b877db6daf --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/AddABTestsRequest.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.abtesting + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * AddABTestsRequest + * + * @param name A/B test name. + * @param variant List of 2 variants for the A/B test. + * @param endAt End date for the A/B test expressed as YYYY-MM-DDThh:mm:ssZ. + */ +@Serializable +public data class AddABTestsRequest( + + /** A/B test name. */ + @SerialName(value = "name") val name: String, + + /** List of 2 variants for the A/B test. */ + @SerialName(value = "variant") val variant: List, + + /** End date for the A/B test expressed as YYYY-MM-DDThh:mm:ssZ. */ + @SerialName(value = "endAt") val endAt: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/AddABTestsVariant.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/AddABTestsVariant.kt new file mode 100644 index 0000000000..6c0846179d --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/AddABTestsVariant.kt @@ -0,0 +1,96 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.abtesting + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * AddABTestsVariant + */ +@Serializable(AddABTestsVariantSerializer::class) +public sealed interface AddABTestsVariant { + + public companion object { + + /** + * AbTestsVariant + * + * @param index The index performing the A/B test. + * @param trafficPercentage The traffic percentage for the A/B test. + * @param description The A/B test description. + */ + public fun AbTestsVariant( + index: String, + trafficPercentage: Int, + description: String? = null, + ): AbTestsVariant = com.algolia.client.model.abtesting.AbTestsVariant( + index = index, + trafficPercentage = trafficPercentage, + description = description, + ) + + /** + * AbTestsVariantSearchParams + * + * @param index The index performing the A/B test. + * @param trafficPercentage The traffic percentage for the A/B test. + * @param customSearchParameters + * @param description The A/B test description. + */ + public fun AbTestsVariantSearchParams( + index: String, + trafficPercentage: Int, + customSearchParameters: JsonObject, + description: String? = null, + ): AbTestsVariantSearchParams = com.algolia.client.model.abtesting.AbTestsVariantSearchParams( + index = index, + trafficPercentage = trafficPercentage, + customSearchParameters = customSearchParameters, + description = description, + ) + } +} + +internal class AddABTestsVariantSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("AddABTestsVariant") + + override fun serialize(encoder: Encoder, value: AddABTestsVariant) { + when (value) { + is AbTestsVariant -> AbTestsVariant.serializer().serialize(encoder, value) + is AbTestsVariantSearchParams -> AbTestsVariantSearchParams.serializer().serialize(encoder, value) + } + } + + override fun deserialize(decoder: Decoder): AddABTestsVariant { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize AbTestsVariant + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize AbTestsVariant (error: ${e.message})") + } + } + + // deserialize AbTestsVariantSearchParams + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize AbTestsVariantSearchParams (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/CustomSearchParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/CustomSearchParams.kt new file mode 100644 index 0000000000..413b69513f --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/CustomSearchParams.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.abtesting + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * CustomSearchParams + * + * @param customSearchParameters + */ +@Serializable +public data class CustomSearchParams( + + @SerialName(value = "customSearchParameters") val customSearchParameters: JsonObject, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/ErrorBase.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/ErrorBase.kt new file mode 100644 index 0000000000..721fa11942 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/ErrorBase.kt @@ -0,0 +1,46 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.abtesting + +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Error. + * + * @param message + */ +@Serializable(ErrorBaseSerializer::class) +public data class ErrorBase( + + val message: String? = null, + + val additionalProperties: Map? = null, +) + +internal object ErrorBaseSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("ErrorBase") { + element("message") + } + + override fun deserialize(decoder: Decoder): ErrorBase { + val input = decoder.asJsonDecoder() + val tree = input.decodeJsonObject() + return ErrorBase( + message = tree["message"]?.let { input.json.decodeFromJsonElement(it) }, + additionalProperties = tree.filterKeys { it !in descriptor.elementNames }, + ) + } + + override fun serialize(encoder: Encoder, value: ErrorBase) { + val output = encoder.asJsonEncoder() + val json = buildJsonObject { + value.message?.let { put("message", output.json.encodeToJsonElement(it)) } + value.additionalProperties?.onEach { (key, element) -> put(key, element) } + } + (encoder as JsonEncoder).encodeJsonElement(json) + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/ListABTestsResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/ListABTestsResponse.kt new file mode 100644 index 0000000000..8ed39e8089 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/ListABTestsResponse.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.abtesting + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * ListABTestsResponse + * + * @param abtests List of A/B tests. + * @param count Number of A/B tests found for the app. + * @param total Number of A/B tests retrievable. + */ +@Serializable +public data class ListABTestsResponse( + + /** List of A/B tests. */ + @SerialName(value = "abtests") val abtests: List, + + /** Number of A/B tests found for the app. */ + @SerialName(value = "count") val count: Int, + + /** Number of A/B tests retrievable. */ + @SerialName(value = "total") val total: Int, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/Variant.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/Variant.kt new file mode 100644 index 0000000000..585a915056 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/abtesting/Variant.kt @@ -0,0 +1,61 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.abtesting + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Variant + * + * @param averageClickPosition Average click position for the variant. + * @param clickCount Distinct click count for the variant. + * @param clickThroughRate Click through rate for the variant. + * @param conversionCount Distinct conversion count for the variant. + * @param conversionRate Conversion rate for the variant. + * @param description The A/B test description. + * @param index The index performing the A/B test. + * @param noResultCount The number of occurrences. + * @param searchCount The number of search during the A/B test. + * @param trackedSearchCount The number of tracked search click. + * @param trafficPercentage The traffic percentage for the A/B test. + * @param userCount The number of user during the A/B test. + */ +@Serializable +public data class Variant( + + /** Average click position for the variant. */ + @SerialName(value = "averageClickPosition") val averageClickPosition: Int, + + /** Distinct click count for the variant. */ + @SerialName(value = "clickCount") val clickCount: Int, + + /** Click through rate for the variant. */ + @SerialName(value = "clickThroughRate") val clickThroughRate: Double, + + /** Distinct conversion count for the variant. */ + @SerialName(value = "conversionCount") val conversionCount: Int, + + /** Conversion rate for the variant. */ + @SerialName(value = "conversionRate") val conversionRate: Double, + + /** The A/B test description. */ + @SerialName(value = "description") val description: String, + + /** The index performing the A/B test. */ + @SerialName(value = "index") val index: String, + + /** The number of occurrences. */ + @SerialName(value = "noResultCount") val noResultCount: Int, + + /** The number of search during the A/B test. */ + @SerialName(value = "searchCount") val searchCount: Int, + + /** The number of tracked search click. */ + @SerialName(value = "trackedSearchCount") val trackedSearchCount: Int, + + /** The traffic percentage for the A/B test. */ + @SerialName(value = "trafficPercentage") val trafficPercentage: Int, + + /** The number of user during the A/B test. */ + @SerialName(value = "userCount") val userCount: Int, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/AverageClickEvent.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/AverageClickEvent.kt new file mode 100644 index 0000000000..dc97d3d871 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/AverageClickEvent.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * AverageClickEvent + * + * @param average The average of all the click count event. + * @param clickCount The number of click event. + * @param date Date of the event. + */ +@Serializable +public data class AverageClickEvent( + + /** The average of all the click count event. */ + @SerialName(value = "average") val average: Double, + + /** The number of click event. */ + @SerialName(value = "clickCount") val clickCount: Int, + + /** Date of the event. */ + @SerialName(value = "date") val date: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/ClickPosition.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/ClickPosition.kt new file mode 100644 index 0000000000..d4497f6894 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/ClickPosition.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * ClickPosition + * + * @param position Range of positions with the following pattern: - Positions from 1 to 10 included are displayed in separated groups. - Positions from 11 to 20 included are grouped together. - Positions from 21 and up are grouped together. + * @param clickCount The number of click event. + */ +@Serializable +public data class ClickPosition( + + /** Range of positions with the following pattern: - Positions from 1 to 10 included are displayed in separated groups. - Positions from 11 to 20 included are grouped together. - Positions from 21 and up are grouped together. */ + @SerialName(value = "position") val position: List, + + /** The number of click event. */ + @SerialName(value = "clickCount") val clickCount: Int, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/ClickThroughRateEvent.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/ClickThroughRateEvent.kt new file mode 100644 index 0000000000..f0cc58d58b --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/ClickThroughRateEvent.kt @@ -0,0 +1,29 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * ClickThroughRateEvent + * + * @param rate The click-through rate. + * @param clickCount The number of click event. + * @param trackedSearchCount The number of tracked search click. + * @param date Date of the event. + */ +@Serializable +public data class ClickThroughRateEvent( + + /** The click-through rate. */ + @SerialName(value = "rate") val rate: Double, + + /** The number of click event. */ + @SerialName(value = "clickCount") val clickCount: Int, + + /** The number of tracked search click. */ + @SerialName(value = "trackedSearchCount") val trackedSearchCount: Int, + + /** Date of the event. */ + @SerialName(value = "date") val date: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/ConversionRateEvent.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/ConversionRateEvent.kt new file mode 100644 index 0000000000..224b300263 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/ConversionRateEvent.kt @@ -0,0 +1,29 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * ConversionRateEvent + * + * @param rate The click-through rate. + * @param trackedSearchCount The number of tracked search click. + * @param conversionCount The number of converted clicks. + * @param date Date of the event. + */ +@Serializable +public data class ConversionRateEvent( + + /** The click-through rate. */ + @SerialName(value = "rate") val rate: Double, + + /** The number of tracked search click. */ + @SerialName(value = "trackedSearchCount") val trackedSearchCount: Int, + + /** The number of converted clicks. */ + @SerialName(value = "conversionCount") val conversionCount: Int, + + /** Date of the event. */ + @SerialName(value = "date") val date: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/Direction.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/Direction.kt new file mode 100644 index 0000000000..b2c26461df --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/Direction.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* + +@Serializable +public enum class Direction(public val value: kotlin.String) { + + @SerialName(value = "asc") + Asc("asc"), + + @SerialName(value = "desc") + Desc("desc"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/ErrorBase.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/ErrorBase.kt new file mode 100644 index 0000000000..a2fd8fa643 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/ErrorBase.kt @@ -0,0 +1,46 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Error. + * + * @param message + */ +@Serializable(ErrorBaseSerializer::class) +public data class ErrorBase( + + val message: String? = null, + + val additionalProperties: Map? = null, +) + +internal object ErrorBaseSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("ErrorBase") { + element("message") + } + + override fun deserialize(decoder: Decoder): ErrorBase { + val input = decoder.asJsonDecoder() + val tree = input.decodeJsonObject() + return ErrorBase( + message = tree["message"]?.let { input.json.decodeFromJsonElement(it) }, + additionalProperties = tree.filterKeys { it !in descriptor.elementNames }, + ) + } + + override fun serialize(encoder: Encoder, value: ErrorBase) { + val output = encoder.asJsonEncoder() + val json = buildJsonObject { + value.message?.let { put("message", output.json.encodeToJsonElement(it)) } + value.additionalProperties?.onEach { (key, element) -> put(key, element) } + } + (encoder as JsonEncoder).encodeJsonElement(json) + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetAverageClickPositionResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetAverageClickPositionResponse.kt new file mode 100644 index 0000000000..06f59fad4b --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetAverageClickPositionResponse.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * GetAverageClickPositionResponse + * + * @param average The average of all the click count event. + * @param clickCount The number of click event. + * @param dates A list of average click position with their date. + */ +@Serializable +public data class GetAverageClickPositionResponse( + + /** The average of all the click count event. */ + @SerialName(value = "average") val average: Double, + + /** The number of click event. */ + @SerialName(value = "clickCount") val clickCount: Int, + + /** A list of average click position with their date. */ + @SerialName(value = "dates") val dates: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetClickPositionsResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetClickPositionsResponse.kt new file mode 100644 index 0000000000..dabaab7b24 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetClickPositionsResponse.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * GetClickPositionsResponse + * + * @param positions A list of the click positions with their click count. + */ +@Serializable +public data class GetClickPositionsResponse( + + /** A list of the click positions with their click count. */ + @SerialName(value = "positions") val positions: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetClickThroughRateResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetClickThroughRateResponse.kt new file mode 100644 index 0000000000..f784836fdf --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetClickThroughRateResponse.kt @@ -0,0 +1,29 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * GetClickThroughRateResponse + * + * @param rate The click-through rate. + * @param clickCount The number of click event. + * @param trackedSearchCount The number of tracked search click. + * @param dates A list of click-through rate events with their date. + */ +@Serializable +public data class GetClickThroughRateResponse( + + /** The click-through rate. */ + @SerialName(value = "rate") val rate: Double, + + /** The number of click event. */ + @SerialName(value = "clickCount") val clickCount: Int, + + /** The number of tracked search click. */ + @SerialName(value = "trackedSearchCount") val trackedSearchCount: Int, + + /** A list of click-through rate events with their date. */ + @SerialName(value = "dates") val dates: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetConversationRateResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetConversationRateResponse.kt new file mode 100644 index 0000000000..116c32f23d --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetConversationRateResponse.kt @@ -0,0 +1,29 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * GetConversationRateResponse + * + * @param rate The click-through rate. + * @param trackedSearchCount The number of tracked search click. + * @param conversionCount The number of converted clicks. + * @param dates A list of conversion events with their date. + */ +@Serializable +public data class GetConversationRateResponse( + + /** The click-through rate. */ + @SerialName(value = "rate") val rate: Double, + + /** The number of tracked search click. */ + @SerialName(value = "trackedSearchCount") val trackedSearchCount: Int, + + /** The number of converted clicks. */ + @SerialName(value = "conversionCount") val conversionCount: Int, + + /** A list of conversion events with their date. */ + @SerialName(value = "dates") val dates: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetNoClickRateResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetNoClickRateResponse.kt new file mode 100644 index 0000000000..f63772e87e --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetNoClickRateResponse.kt @@ -0,0 +1,29 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * GetNoClickRateResponse + * + * @param rate The click-through rate. + * @param count The number of click event. + * @param noClickCount The number of click event. + * @param dates A list of searches without clicks with their date, rate and counts. + */ +@Serializable +public data class GetNoClickRateResponse( + + /** The click-through rate. */ + @SerialName(value = "rate") val rate: Double, + + /** The number of click event. */ + @SerialName(value = "count") val count: Int, + + /** The number of click event. */ + @SerialName(value = "noClickCount") val noClickCount: Int, + + /** A list of searches without clicks with their date, rate and counts. */ + @SerialName(value = "dates") val dates: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetNoResultsRateResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetNoResultsRateResponse.kt new file mode 100644 index 0000000000..3811269b4e --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetNoResultsRateResponse.kt @@ -0,0 +1,29 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * GetNoResultsRateResponse + * + * @param rate The click-through rate. + * @param count The number of occurrences. + * @param noResultCount The number of occurrences. + * @param dates A list of searches without results with their date, rate and counts. + */ +@Serializable +public data class GetNoResultsRateResponse( + + /** The click-through rate. */ + @SerialName(value = "rate") val rate: Double, + + /** The number of occurrences. */ + @SerialName(value = "count") val count: Int, + + /** The number of occurrences. */ + @SerialName(value = "noResultCount") val noResultCount: Int, + + /** A list of searches without results with their date, rate and counts. */ + @SerialName(value = "dates") val dates: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetSearchesCountResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetSearchesCountResponse.kt new file mode 100644 index 0000000000..7d30638a78 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetSearchesCountResponse.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * GetSearchesCountResponse + * + * @param count The number of occurrences. + * @param dates A list of search events with their date and count. + */ +@Serializable +public data class GetSearchesCountResponse( + + /** The number of occurrences. */ + @SerialName(value = "count") val count: Int, + + /** A list of search events with their date and count. */ + @SerialName(value = "dates") val dates: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetSearchesNoClicksResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetSearchesNoClicksResponse.kt new file mode 100644 index 0000000000..1cadb4c140 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetSearchesNoClicksResponse.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * GetSearchesNoClicksResponse + * + * @param searches A list of searches with no clicks and their count. + */ +@Serializable +public data class GetSearchesNoClicksResponse( + + /** A list of searches with no clicks and their count. */ + @SerialName(value = "searches") val searches: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetSearchesNoResultsResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetSearchesNoResultsResponse.kt new file mode 100644 index 0000000000..6e0b578400 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetSearchesNoResultsResponse.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * GetSearchesNoResultsResponse + * + * @param searches A list of searches with no results and their count. + */ +@Serializable +public data class GetSearchesNoResultsResponse( + + /** A list of searches with no results and their count. */ + @SerialName(value = "searches") val searches: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetStatusResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetStatusResponse.kt new file mode 100644 index 0000000000..2506d07145 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetStatusResponse.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * GetStatusResponse + * + * @param updatedAt Date of last update (ISO-8601 format). + */ +@Serializable +public data class GetStatusResponse( + + /** Date of last update (ISO-8601 format). */ + @SerialName(value = "updatedAt") val updatedAt: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopCountriesResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopCountriesResponse.kt new file mode 100644 index 0000000000..b77a43dad9 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopCountriesResponse.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * GetTopCountriesResponse + * + * @param countries A list of countries with their count. + */ +@Serializable +public data class GetTopCountriesResponse( + + /** A list of countries with their count. */ + @SerialName(value = "countries") val countries: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopFilterAttribute.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopFilterAttribute.kt new file mode 100644 index 0000000000..de1b6b7fe7 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopFilterAttribute.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * GetTopFilterAttribute + * + * @param attribute The attribute. + * @param count The number of occurrences. + */ +@Serializable +public data class GetTopFilterAttribute( + + /** The attribute. */ + @SerialName(value = "attribute") val attribute: String, + + /** The number of occurrences. */ + @SerialName(value = "count") val count: Int, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopFilterAttributesResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopFilterAttributesResponse.kt new file mode 100644 index 0000000000..5e73a0dbbd --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopFilterAttributesResponse.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * GetTopFilterAttributesResponse + * + * @param attributes A list of attributes with their count. + */ +@Serializable +public data class GetTopFilterAttributesResponse( + + /** A list of attributes with their count. */ + @SerialName(value = "attributes") val attributes: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopFilterForAttribute.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopFilterForAttribute.kt new file mode 100644 index 0000000000..e29bf54bdc --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopFilterForAttribute.kt @@ -0,0 +1,29 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * GetTopFilterForAttribute + * + * @param attribute The attribute. + * @param `operator` The operator. + * @param `value` The value of the attribute. + * @param count The number of occurrences. + */ +@Serializable +public data class GetTopFilterForAttribute( + + /** The attribute. */ + @SerialName(value = "attribute") val attribute: String, + + /** The operator. */ + @SerialName(value = "operator") val `operator`: String, + + /** The value of the attribute. */ + @SerialName(value = "value") val `value`: String, + + /** The number of occurrences. */ + @SerialName(value = "count") val count: Int, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopFilterForAttributeResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopFilterForAttributeResponse.kt new file mode 100644 index 0000000000..e51a218529 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopFilterForAttributeResponse.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * GetTopFilterForAttributeResponse + * + * @param values A list of filters for the given attributes. + */ +@Serializable +public data class GetTopFilterForAttributeResponse( + + /** A list of filters for the given attributes. */ + @SerialName(value = "values") val values: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopFiltersNoResultsResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopFiltersNoResultsResponse.kt new file mode 100644 index 0000000000..6ab0236b0c --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopFiltersNoResultsResponse.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * GetTopFiltersNoResultsResponse + * + * @param values A list of filters without results. + */ +@Serializable +public data class GetTopFiltersNoResultsResponse( + + /** A list of filters without results. */ + @SerialName(value = "values") val values: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopFiltersNoResultsValue.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopFiltersNoResultsValue.kt new file mode 100644 index 0000000000..112599d116 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopFiltersNoResultsValue.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * GetTopFiltersNoResultsValue + * + * @param attribute The attribute. + * @param `operator` The operator. + * @param `value` The value of the attribute. + */ +@Serializable +public data class GetTopFiltersNoResultsValue( + + /** The attribute. */ + @SerialName(value = "attribute") val attribute: String, + + /** The operator. */ + @SerialName(value = "operator") val `operator`: String, + + /** The value of the attribute. */ + @SerialName(value = "value") val `value`: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopFiltersNoResultsValues.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopFiltersNoResultsValues.kt new file mode 100644 index 0000000000..c56a722954 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopFiltersNoResultsValues.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * GetTopFiltersNoResultsValues + * + * @param count The number of occurrences. + * @param values A list of filters without results. + */ +@Serializable +public data class GetTopFiltersNoResultsValues( + + /** The number of occurrences. */ + @SerialName(value = "count") val count: Int, + + /** A list of filters without results. */ + @SerialName(value = "values") val values: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopHitsResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopHitsResponse.kt new file mode 100644 index 0000000000..721890d87a --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopHitsResponse.kt @@ -0,0 +1,81 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * GetTopHitsResponse + */ +@Serializable(GetTopHitsResponseSerializer::class) +public sealed interface GetTopHitsResponse { + + public companion object { + + /** + * TopHitsResponse + * + * @param hits A list of top hits with their count. + */ + public fun TopHitsResponse( + hits: List, + ): TopHitsResponse = com.algolia.client.model.analytics.TopHitsResponse( + hits = hits, + ) + + /** + * TopHitsResponseWithAnalytics + * + * @param hits A list of top hits with their count and analytics. + */ + public fun TopHitsResponseWithAnalytics( + hits: List, + ): TopHitsResponseWithAnalytics = com.algolia.client.model.analytics.TopHitsResponseWithAnalytics( + hits = hits, + ) + } +} + +internal class GetTopHitsResponseSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("GetTopHitsResponse") + + override fun serialize(encoder: Encoder, value: GetTopHitsResponse) { + when (value) { + is TopHitsResponse -> TopHitsResponse.serializer().serialize(encoder, value) + is TopHitsResponseWithAnalytics -> TopHitsResponseWithAnalytics.serializer().serialize(encoder, value) + } + } + + override fun deserialize(decoder: Decoder): GetTopHitsResponse { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize TopHitsResponse + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize TopHitsResponse (error: ${e.message})") + } + } + + // deserialize TopHitsResponseWithAnalytics + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize TopHitsResponseWithAnalytics (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopSearchesResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopSearchesResponse.kt new file mode 100644 index 0000000000..c684744a1f --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetTopSearchesResponse.kt @@ -0,0 +1,81 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * GetTopSearchesResponse + */ +@Serializable(GetTopSearchesResponseSerializer::class) +public sealed interface GetTopSearchesResponse { + + public companion object { + + /** + * TopSearchesResponse + * + * @param searches A list of top searches with their count. + */ + public fun TopSearchesResponse( + searches: List, + ): TopSearchesResponse = com.algolia.client.model.analytics.TopSearchesResponse( + searches = searches, + ) + + /** + * TopSearchesResponseWithAnalytics + * + * @param searches A list of top searches with their count and analytics. + */ + public fun TopSearchesResponseWithAnalytics( + searches: List, + ): TopSearchesResponseWithAnalytics = com.algolia.client.model.analytics.TopSearchesResponseWithAnalytics( + searches = searches, + ) + } +} + +internal class GetTopSearchesResponseSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("GetTopSearchesResponse") + + override fun serialize(encoder: Encoder, value: GetTopSearchesResponse) { + when (value) { + is TopSearchesResponse -> TopSearchesResponse.serializer().serialize(encoder, value) + is TopSearchesResponseWithAnalytics -> TopSearchesResponseWithAnalytics.serializer().serialize(encoder, value) + } + } + + override fun deserialize(decoder: Decoder): GetTopSearchesResponse { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize TopSearchesResponse + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize TopSearchesResponse (error: ${e.message})") + } + } + + // deserialize TopSearchesResponseWithAnalytics + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize TopSearchesResponseWithAnalytics (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetUsersCountResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetUsersCountResponse.kt new file mode 100644 index 0000000000..72a4c57396 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetUsersCountResponse.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * GetUsersCountResponse + * + * @param count The number of occurrences. + * @param dates A list of users count with their date. + */ +@Serializable +public data class GetUsersCountResponse( + + /** The number of occurrences. */ + @SerialName(value = "count") val count: Int, + + /** A list of users count with their date. */ + @SerialName(value = "dates") val dates: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/NoClickRateEvent.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/NoClickRateEvent.kt new file mode 100644 index 0000000000..0ccc3354c7 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/NoClickRateEvent.kt @@ -0,0 +1,29 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * NoClickRateEvent + * + * @param rate The click-through rate. + * @param count The number of click event. + * @param noClickCount The number of click event. + * @param date Date of the event. + */ +@Serializable +public data class NoClickRateEvent( + + /** The click-through rate. */ + @SerialName(value = "rate") val rate: Double, + + /** The number of click event. */ + @SerialName(value = "count") val count: Int, + + /** The number of click event. */ + @SerialName(value = "noClickCount") val noClickCount: Int, + + /** Date of the event. */ + @SerialName(value = "date") val date: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/NoResultsRateEvent.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/NoResultsRateEvent.kt new file mode 100644 index 0000000000..c7d86338a5 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/NoResultsRateEvent.kt @@ -0,0 +1,29 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * NoResultsRateEvent + * + * @param date Date of the event. + * @param noResultCount The number of occurrences. + * @param count The number of occurrences. + * @param rate The click-through rate. + */ +@Serializable +public data class NoResultsRateEvent( + + /** Date of the event. */ + @SerialName(value = "date") val date: String, + + /** The number of occurrences. */ + @SerialName(value = "noResultCount") val noResultCount: Int, + + /** The number of occurrences. */ + @SerialName(value = "count") val count: Int, + + /** The click-through rate. */ + @SerialName(value = "rate") val rate: Double, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/OrderBy.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/OrderBy.kt new file mode 100644 index 0000000000..d36764017e --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/OrderBy.kt @@ -0,0 +1,22 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* + +@Serializable +public enum class OrderBy(public val value: kotlin.String) { + + @SerialName(value = "searchCount") + SearchCount("searchCount"), + + @SerialName(value = "clickThroughRate") + ClickThroughRate("clickThroughRate"), + + @SerialName(value = "conversionRate") + ConversionRate("conversionRate"), + + @SerialName(value = "averageClickPosition") + AverageClickPosition("averageClickPosition"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/SearchEvent.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/SearchEvent.kt new file mode 100644 index 0000000000..9703699d8f --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/SearchEvent.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SearchEvent + * + * @param date Date of the event. + * @param count The number of occurrences. + */ +@Serializable +public data class SearchEvent( + + /** Date of the event. */ + @SerialName(value = "date") val date: String, + + /** The number of occurrences. */ + @SerialName(value = "count") val count: Int, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/SearchNoClickEvent.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/SearchNoClickEvent.kt new file mode 100644 index 0000000000..2b40e4e730 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/SearchNoClickEvent.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SearchNoClickEvent + * + * @param search The search query. + * @param count The number of occurrences. + * @param withFilterCount The number of occurrences. + */ +@Serializable +public data class SearchNoClickEvent( + + /** The search query. */ + @SerialName(value = "search") val search: String, + + /** The number of occurrences. */ + @SerialName(value = "count") val count: Int, + + /** The number of occurrences. */ + @SerialName(value = "withFilterCount") val withFilterCount: Int, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/SearchNoResultEvent.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/SearchNoResultEvent.kt new file mode 100644 index 0000000000..a3e3caf4f7 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/SearchNoResultEvent.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SearchNoResultEvent + * + * @param search The search query. + * @param count The number of occurrences. + * @param nbHits Number of hits that the search query matched. + */ +@Serializable +public data class SearchNoResultEvent( + + /** The search query. */ + @SerialName(value = "search") val search: String, + + /** The number of occurrences. */ + @SerialName(value = "count") val count: Int, + + /** Number of hits that the search query matched. */ + @SerialName(value = "nbHits") val nbHits: Int, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopCountry.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopCountry.kt new file mode 100644 index 0000000000..2c06947136 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopCountry.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * TopCountry + * + * @param country The country. + * @param count The number of occurrences. + */ +@Serializable +public data class TopCountry( + + /** The country. */ + @SerialName(value = "country") val country: String, + + /** The number of occurrences. */ + @SerialName(value = "count") val count: Int, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopHit.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopHit.kt new file mode 100644 index 0000000000..f6faeebd22 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopHit.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * TopHit + * + * @param hit The hit. + * @param count The number of occurrences. + */ +@Serializable +public data class TopHit( + + /** The hit. */ + @SerialName(value = "hit") val hit: String, + + /** The number of occurrences. */ + @SerialName(value = "count") val count: Int, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopHitWithAnalytics.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopHitWithAnalytics.kt new file mode 100644 index 0000000000..4f8a8bc409 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopHitWithAnalytics.kt @@ -0,0 +1,41 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * TopHitWithAnalytics + * + * @param hit The hit. + * @param count The number of occurrences. + * @param clickThroughRate The click-through rate. + * @param conversionRate The conversion rate. + * @param trackedSearchCount The number of tracked search click. + * @param clickCount The number of click event. + * @param conversionCount The number of converted clicks. + */ +@Serializable +public data class TopHitWithAnalytics( + + /** The hit. */ + @SerialName(value = "hit") val hit: String, + + /** The number of occurrences. */ + @SerialName(value = "count") val count: Int, + + /** The click-through rate. */ + @SerialName(value = "clickThroughRate") val clickThroughRate: Double, + + /** The conversion rate. */ + @SerialName(value = "conversionRate") val conversionRate: Double, + + /** The number of tracked search click. */ + @SerialName(value = "trackedSearchCount") val trackedSearchCount: Int, + + /** The number of click event. */ + @SerialName(value = "clickCount") val clickCount: Int, + + /** The number of converted clicks. */ + @SerialName(value = "conversionCount") val conversionCount: Int, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopHitsResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopHitsResponse.kt new file mode 100644 index 0000000000..40e87f52c0 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopHitsResponse.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * TopHitsResponse + * + * @param hits A list of top hits with their count. + */ +@Serializable +public data class TopHitsResponse( + + /** A list of top hits with their count. */ + @SerialName(value = "hits") val hits: List, +) : GetTopHitsResponse diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopHitsResponseWithAnalytics.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopHitsResponseWithAnalytics.kt new file mode 100644 index 0000000000..b878ea414f --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopHitsResponseWithAnalytics.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * TopHitsResponseWithAnalytics + * + * @param hits A list of top hits with their count and analytics. + */ +@Serializable +public data class TopHitsResponseWithAnalytics( + + /** A list of top hits with their count and analytics. */ + @SerialName(value = "hits") val hits: List, +) : GetTopHitsResponse diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopSearch.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopSearch.kt new file mode 100644 index 0000000000..c4268a4041 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopSearch.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * TopSearch + * + * @param search The search query. + * @param count The number of occurrences. + * @param nbHits Number of hits that the search query matched. + */ +@Serializable +public data class TopSearch( + + /** The search query. */ + @SerialName(value = "search") val search: String, + + /** The number of occurrences. */ + @SerialName(value = "count") val count: Int, + + /** Number of hits that the search query matched. */ + @SerialName(value = "nbHits") val nbHits: Int, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopSearchWithAnalytics.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopSearchWithAnalytics.kt new file mode 100644 index 0000000000..b338082227 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopSearchWithAnalytics.kt @@ -0,0 +1,49 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * TopSearchWithAnalytics + * + * @param search The search query. + * @param count The number of occurrences. + * @param clickThroughRate The click-through rate. + * @param averageClickPosition The average position of all the click count event. + * @param conversionRate The conversion rate. + * @param trackedSearchCount The number of tracked search click. + * @param clickCount The number of click event. + * @param conversionCount The number of converted clicks. + * @param nbHits Number of hits that the search query matched. + */ +@Serializable +public data class TopSearchWithAnalytics( + + /** The search query. */ + @SerialName(value = "search") val search: String, + + /** The number of occurrences. */ + @SerialName(value = "count") val count: Int, + + /** The click-through rate. */ + @SerialName(value = "clickThroughRate") val clickThroughRate: Double, + + /** The average position of all the click count event. */ + @SerialName(value = "averageClickPosition") val averageClickPosition: Int, + + /** The conversion rate. */ + @SerialName(value = "conversionRate") val conversionRate: Double, + + /** The number of tracked search click. */ + @SerialName(value = "trackedSearchCount") val trackedSearchCount: Int, + + /** The number of click event. */ + @SerialName(value = "clickCount") val clickCount: Int, + + /** The number of converted clicks. */ + @SerialName(value = "conversionCount") val conversionCount: Int, + + /** Number of hits that the search query matched. */ + @SerialName(value = "nbHits") val nbHits: Int, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopSearchesResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopSearchesResponse.kt new file mode 100644 index 0000000000..ef6556ee55 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopSearchesResponse.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * TopSearchesResponse + * + * @param searches A list of top searches with their count. + */ +@Serializable +public data class TopSearchesResponse( + + /** A list of top searches with their count. */ + @SerialName(value = "searches") val searches: List, +) : GetTopSearchesResponse diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopSearchesResponseWithAnalytics.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopSearchesResponseWithAnalytics.kt new file mode 100644 index 0000000000..a24e882eba --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/TopSearchesResponseWithAnalytics.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * TopSearchesResponseWithAnalytics + * + * @param searches A list of top searches with their count and analytics. + */ +@Serializable +public data class TopSearchesResponseWithAnalytics( + + /** A list of top searches with their count and analytics. */ + @SerialName(value = "searches") val searches: List, +) : GetTopSearchesResponse diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/UserWithDate.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/UserWithDate.kt new file mode 100644 index 0000000000..51766cb9fc --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/analytics/UserWithDate.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.analytics + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * UserWithDate + * + * @param date Date of the event. + * @param count The number of occurrences. + */ +@Serializable +public data class UserWithDate( + + /** Date of the event. */ + @SerialName(value = "date") val date: String, + + /** The number of occurrences. */ + @SerialName(value = "count") val count: Int, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ActionType.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ActionType.kt new file mode 100644 index 0000000000..41ced8967c --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ActionType.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* + +/** + * The action to perform on the Algolia index. + */ +@Serializable +public enum class ActionType(public val value: kotlin.String) { + + @SerialName(value = "replace") + Replace("replace"), + + @SerialName(value = "save") + Save("save"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthAPIKey.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthAPIKey.kt new file mode 100644 index 0000000000..7ea0a193ba --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthAPIKey.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Authentication input used for token credentials. + * + * @param key + */ +@Serializable +public data class AuthAPIKey( + + @SerialName(value = "key") val key: String, +) : AuthInput diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthAlgolia.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthAlgolia.kt new file mode 100644 index 0000000000..e8fac46966 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthAlgolia.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * AuthAlgolia + * + * @param appID Algolia Application ID. + * @param apiKey Algolia API Key, with the correct rights to push to an index and change settings. + */ +@Serializable +public data class AuthAlgolia( + + /** Algolia Application ID. */ + @SerialName(value = "appID") val appID: String, + + /** Algolia API Key, with the correct rights to push to an index and change settings. */ + @SerialName(value = "apiKey") val apiKey: String, +) : AuthInput diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthBasic.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthBasic.kt new file mode 100644 index 0000000000..4ea5e8624d --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthBasic.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Authentication input for Basic login with username and password. + * + * @param username + * @param password + */ +@Serializable +public data class AuthBasic( + + @SerialName(value = "username") val username: String, + + @SerialName(value = "password") val password: String, +) : AuthInput diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthGoogleServiceAccount.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthGoogleServiceAccount.kt new file mode 100644 index 0000000000..d5734c1d96 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthGoogleServiceAccount.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Authentication input to connect to a Google service (e.g. BigQuery). + * + * @param clientEmail Email address of the Service Account. + * @param privateKey Private key of the Service Account. + */ +@Serializable +public data class AuthGoogleServiceAccount( + + /** Email address of the Service Account. */ + @SerialName(value = "clientEmail") val clientEmail: String, + + /** Private key of the Service Account. */ + @SerialName(value = "privateKey") val privateKey: String, +) : AuthInput diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthInput.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthInput.kt new file mode 100644 index 0000000000..2203443730 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthInput.kt @@ -0,0 +1,162 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * AuthInput + */ +@Serializable(AuthInputSerializer::class) +public sealed interface AuthInput { + + public companion object { + + /** + * Authentication input used for token credentials. + * + * @param key + */ + public fun AuthAPIKey( + key: String, + ): AuthAPIKey = com.algolia.client.model.ingestion.AuthAPIKey( + key = key, + ) + + /** + * AuthAlgolia + * + * @param appID Algolia Application ID. + * @param apiKey Algolia API Key, with the correct rights to push to an index and change settings. + */ + public fun AuthAlgolia( + appID: String, + apiKey: String, + ): AuthAlgolia = com.algolia.client.model.ingestion.AuthAlgolia( + appID = appID, + apiKey = apiKey, + ) + + /** + * Authentication input for Basic login with username and password. + * + * @param username + * @param password + */ + public fun AuthBasic( + username: String, + password: String, + ): AuthBasic = com.algolia.client.model.ingestion.AuthBasic( + username = username, + password = password, + ) + + /** + * Authentication input to connect to a Google service (e.g. BigQuery). + * + * @param clientEmail Email address of the Service Account. + * @param privateKey Private key of the Service Account. + */ + public fun AuthGoogleServiceAccount( + clientEmail: String, + privateKey: String, + ): AuthGoogleServiceAccount = com.algolia.client.model.ingestion.AuthGoogleServiceAccount( + clientEmail = clientEmail, + privateKey = privateKey, + ) + + /** + * Authentication input for OAuth login. + * + * @param url The OAuth endpoint URL. + * @param clientId The clientID. + * @param clientSecret The secret. + */ + public fun AuthOAuth( + url: String, + clientId: String, + clientSecret: String, + ): AuthOAuth = com.algolia.client.model.ingestion.AuthOAuth( + url = url, + clientId = clientId, + clientSecret = clientSecret, + ) + } +} + +internal class AuthInputSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("AuthInput") + + override fun serialize(encoder: Encoder, value: AuthInput) { + when (value) { + is AuthAPIKey -> AuthAPIKey.serializer().serialize(encoder, value) + is AuthAlgolia -> AuthAlgolia.serializer().serialize(encoder, value) + is AuthBasic -> AuthBasic.serializer().serialize(encoder, value) + is AuthGoogleServiceAccount -> AuthGoogleServiceAccount.serializer().serialize(encoder, value) + is AuthOAuth -> AuthOAuth.serializer().serialize(encoder, value) + } + } + + override fun deserialize(decoder: Decoder): AuthInput { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize AuthAPIKey + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize AuthAPIKey (error: ${e.message})") + } + } + + // deserialize AuthAlgolia + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize AuthAlgolia (error: ${e.message})") + } + } + + // deserialize AuthBasic + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize AuthBasic (error: ${e.message})") + } + } + + // deserialize AuthGoogleServiceAccount + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize AuthGoogleServiceAccount (error: ${e.message})") + } + } + + // deserialize AuthOAuth + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize AuthOAuth (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthOAuth.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthOAuth.kt new file mode 100644 index 0000000000..eb5c859430 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthOAuth.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Authentication input for OAuth login. + * + * @param url The OAuth endpoint URL. + * @param clientId The clientID. + * @param clientSecret The secret. + */ +@Serializable +public data class AuthOAuth( + + /** The OAuth endpoint URL. */ + @SerialName(value = "url") val url: String, + + /** The clientID. */ + @SerialName(value = "client_id") val clientId: String, + + /** The secret. */ + @SerialName(value = "client_secret") val clientSecret: String, +) : AuthInput diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Authentication.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Authentication.kt new file mode 100644 index 0000000000..698df3418e --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Authentication.kt @@ -0,0 +1,35 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * An authentication is used to login into a Source or a Destination. + * + * @param authenticationID The authentication UUID. + * @param type + * @param name An human readable name describing the object. + * @param createdAt Date of creation (RFC3339 format). + * @param platform + * @param updatedAt Date of last update (RFC3339 format). + */ +@Serializable +public data class Authentication( + + /** The authentication UUID. */ + @SerialName(value = "authenticationID") val authenticationID: String, + + @SerialName(value = "type") val type: AuthenticationType, + + /** An human readable name describing the object. */ + @SerialName(value = "name") val name: String, + + /** Date of creation (RFC3339 format). */ + @SerialName(value = "createdAt") val createdAt: String, + + @SerialName(value = "platform") val platform: Platform? = null, + + /** Date of last update (RFC3339 format). */ + @SerialName(value = "updatedAt") val updatedAt: String? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationCreate.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationCreate.kt new file mode 100644 index 0000000000..703ec84d1a --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationCreate.kt @@ -0,0 +1,26 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The payload when creating an authentication. + * + * @param type + * @param name An human readable name describing the object. + * @param input + * @param platform + */ +@Serializable +public data class AuthenticationCreate( + + @SerialName(value = "type") val type: AuthenticationType, + + /** An human readable name describing the object. */ + @SerialName(value = "name") val name: String, + + @SerialName(value = "input") val input: AuthInput, + + @SerialName(value = "platform") val platform: Platform? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationCreateResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationCreateResponse.kt new file mode 100644 index 0000000000..1ac08d4e60 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationCreateResponse.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Response from the API when the Authentication is successfully created. + * + * @param authenticationID The authentication UUID. + * @param name An human readable name describing the object. + * @param createdAt Date of creation (RFC3339 format). + */ +@Serializable +public data class AuthenticationCreateResponse( + + /** The authentication UUID. */ + @SerialName(value = "authenticationID") val authenticationID: String, + + /** An human readable name describing the object. */ + @SerialName(value = "name") val name: String, + + /** Date of creation (RFC3339 format). */ + @SerialName(value = "createdAt") val createdAt: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationInput.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationInput.kt new file mode 100644 index 0000000000..f3d28cf1b4 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationInput.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The authentication input property stores the (encrypted) credentials. + * + * @param input + */ +@Serializable +public data class AuthenticationInput( + + @SerialName(value = "input") val input: AuthInput, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationSearch.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationSearch.kt new file mode 100644 index 0000000000..218b3fa78c --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationSearch.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Payload to search for multiple authentications, based on the given `authenticationIDs`. + * + * @param authenticationIDs + */ +@Serializable +public data class AuthenticationSearch( + + @SerialName(value = "authenticationIDs") val authenticationIDs: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationSortKeys.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationSortKeys.kt new file mode 100644 index 0000000000..1baa7a1e04 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationSortKeys.kt @@ -0,0 +1,28 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* + +/** + * Used to sort the Authentication list endpoint. + */ +@Serializable +public enum class AuthenticationSortKeys(public val value: kotlin.String) { + + @SerialName(value = "name") + Name("name"), + + @SerialName(value = "auth_type") + AuthType("auth_type"), + + @SerialName(value = "platform") + Platform("platform"), + + @SerialName(value = "updatedAt") + UpdatedAt("updatedAt"), + + @SerialName(value = "createdAt") + CreatedAt("createdAt"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationType.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationType.kt new file mode 100644 index 0000000000..4eaa12b6ce --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationType.kt @@ -0,0 +1,28 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* + +/** + * Type of the Authentication, defines what kind of object is stored in the input. + */ +@Serializable +public enum class AuthenticationType(public val value: kotlin.String) { + + @SerialName(value = "googleServiceAccount") + GoogleServiceAccount("googleServiceAccount"), + + @SerialName(value = "basic") + Basic("basic"), + + @SerialName(value = "apiKey") + ApiKey("apiKey"), + + @SerialName(value = "oauth") + Oauth("oauth"), + + @SerialName(value = "algolia") + Algolia("algolia"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationUpdate.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationUpdate.kt new file mode 100644 index 0000000000..b63da500c7 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationUpdate.kt @@ -0,0 +1,26 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Payload to partialy update an Authentication. + * + * @param type + * @param name An human readable name describing the object. + * @param platform + * @param input + */ +@Serializable +public data class AuthenticationUpdate( + + @SerialName(value = "type") val type: AuthenticationType? = null, + + /** An human readable name describing the object. */ + @SerialName(value = "name") val name: String? = null, + + @SerialName(value = "platform") val platform: Platform? = null, + + @SerialName(value = "input") val input: AuthInput? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationUpdateResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationUpdateResponse.kt new file mode 100644 index 0000000000..cde5838a69 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationUpdateResponse.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Response from the API when the Authentication is successfully updated. + * + * @param authenticationID The authentication UUID. + * @param name An human readable name describing the object. + * @param updatedAt Date of last update (RFC3339 format). + */ +@Serializable +public data class AuthenticationUpdateResponse( + + /** The authentication UUID. */ + @SerialName(value = "authenticationID") val authenticationID: String, + + /** An human readable name describing the object. */ + @SerialName(value = "name") val name: String, + + /** Date of last update (RFC3339 format). */ + @SerialName(value = "updatedAt") val updatedAt: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationWithInput.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationWithInput.kt new file mode 100644 index 0000000000..11c49236f6 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/AuthenticationWithInput.kt @@ -0,0 +1,38 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * AuthenticationWithInput + * + * @param authenticationID The authentication UUID. + * @param type + * @param name An human readable name describing the object. + * @param createdAt Date of creation (RFC3339 format). + * @param input + * @param platform + * @param updatedAt Date of last update (RFC3339 format). + */ +@Serializable +public data class AuthenticationWithInput( + + /** The authentication UUID. */ + @SerialName(value = "authenticationID") val authenticationID: String, + + @SerialName(value = "type") val type: AuthenticationType, + + /** An human readable name describing the object. */ + @SerialName(value = "name") val name: String, + + /** Date of creation (RFC3339 format). */ + @SerialName(value = "createdAt") val createdAt: String, + + @SerialName(value = "input") val input: AuthInput, + + @SerialName(value = "platform") val platform: Platform? = null, + + /** Date of last update (RFC3339 format). */ + @SerialName(value = "updatedAt") val updatedAt: String? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/BigCommerceChannel.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/BigCommerceChannel.kt new file mode 100644 index 0000000000..5058d4a1d1 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/BigCommerceChannel.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * BigCommerceChannel + * + * @param id The ID of the bigcommerce channel. + * @param currencies An array of currencies for the given channel `ID`, a currency is a trigram string that represents the currency code. + */ +@Serializable +public data class BigCommerceChannel( + + /** The ID of the bigcommerce channel. */ + @SerialName(value = "id") val id: Int, + + /** An array of currencies for the given channel `ID`, a currency is a trigram string that represents the currency code. */ + @SerialName(value = "currencies") val currencies: List? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/BigQueryDataType.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/BigQueryDataType.kt new file mode 100644 index 0000000000..e7470c07f4 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/BigQueryDataType.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* + +@Serializable +public enum class BigQueryDataType(public val value: kotlin.String) { + + @SerialName(value = "ga4") + Ga4("ga4"), + + @SerialName(value = "ga360") + Ga360("ga360"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DeleteResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DeleteResponse.kt new file mode 100644 index 0000000000..63106de99f --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DeleteResponse.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * DeleteResponse + * + * @param deletedAt Date of deletion (RFC3339 format). + */ +@Serializable +public data class DeleteResponse( + + /** Date of deletion (RFC3339 format). */ + @SerialName(value = "deletedAt") val deletedAt: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Destination.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Destination.kt new file mode 100644 index 0000000000..d90277e05a --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Destination.kt @@ -0,0 +1,38 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * A destination describe how the data is indexed on the Algolia side. + * + * @param destinationID The destination UUID. + * @param type + * @param name An human readable name describing the object. + * @param input + * @param createdAt Date of creation (RFC3339 format). + * @param updatedAt Date of last update (RFC3339 format). + * @param authenticationID + */ +@Serializable +public data class Destination( + + /** The destination UUID. */ + @SerialName(value = "destinationID") val destinationID: String, + + @SerialName(value = "type") val type: DestinationType, + + /** An human readable name describing the object. */ + @SerialName(value = "name") val name: String, + + @SerialName(value = "input") val input: DestinationInput, + + /** Date of creation (RFC3339 format). */ + @SerialName(value = "createdAt") val createdAt: String, + + /** Date of last update (RFC3339 format). */ + @SerialName(value = "updatedAt") val updatedAt: String? = null, + + @SerialName(value = "authenticationID") val authenticationID: String? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationCreate.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationCreate.kt new file mode 100644 index 0000000000..0183e97b19 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationCreate.kt @@ -0,0 +1,27 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The payload when creating a destination. + * + * @param type + * @param name An human readable name describing the object. + * @param input + * @param authenticationID The authentication UUID. + */ +@Serializable +public data class DestinationCreate( + + @SerialName(value = "type") val type: DestinationType, + + /** An human readable name describing the object. */ + @SerialName(value = "name") val name: String, + + @SerialName(value = "input") val input: DestinationInput, + + /** The authentication UUID. */ + @SerialName(value = "authenticationID") val authenticationID: String? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationCreateResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationCreateResponse.kt new file mode 100644 index 0000000000..5556169546 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationCreateResponse.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Response from the API when the Destination is successfully created. + * + * @param destinationID The destination UUID. + * @param name An human readable name describing the object. + * @param createdAt Date of creation (RFC3339 format). + */ +@Serializable +public data class DestinationCreateResponse( + + /** The destination UUID. */ + @SerialName(value = "destinationID") val destinationID: String, + + /** An human readable name describing the object. */ + @SerialName(value = "name") val name: String, + + /** Date of creation (RFC3339 format). */ + @SerialName(value = "createdAt") val createdAt: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationIndexName.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationIndexName.kt new file mode 100644 index 0000000000..75b6ac771c --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationIndexName.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * DestinationIndexName + * + * @param indexName The index name to store data in. + */ +@Serializable +public data class DestinationIndexName( + + /** The index name to store data in. */ + @SerialName(value = "indexName") val indexName: String, +) : DestinationInput diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationIndexPrefix.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationIndexPrefix.kt new file mode 100644 index 0000000000..cf9e7f9554 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationIndexPrefix.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * DestinationIndexPrefix + * + * @param indexPrefix The prefix of the final index name. + */ +@Serializable +public data class DestinationIndexPrefix( + + /** The prefix of the final index name. */ + @SerialName(value = "indexPrefix") val indexPrefix: String, +) : DestinationInput diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationInput.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationInput.kt new file mode 100644 index 0000000000..0342bd7496 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationInput.kt @@ -0,0 +1,81 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * DestinationInput + */ +@Serializable(DestinationInputSerializer::class) +public sealed interface DestinationInput { + + public companion object { + + /** + * DestinationIndexName + * + * @param indexName The index name to store data in. + */ + public fun DestinationIndexName( + indexName: String, + ): DestinationIndexName = com.algolia.client.model.ingestion.DestinationIndexName( + indexName = indexName, + ) + + /** + * DestinationIndexPrefix + * + * @param indexPrefix The prefix of the final index name. + */ + public fun DestinationIndexPrefix( + indexPrefix: String, + ): DestinationIndexPrefix = com.algolia.client.model.ingestion.DestinationIndexPrefix( + indexPrefix = indexPrefix, + ) + } +} + +internal class DestinationInputSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("DestinationInput") + + override fun serialize(encoder: Encoder, value: DestinationInput) { + when (value) { + is DestinationIndexName -> DestinationIndexName.serializer().serialize(encoder, value) + is DestinationIndexPrefix -> DestinationIndexPrefix.serializer().serialize(encoder, value) + } + } + + override fun deserialize(decoder: Decoder): DestinationInput { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize DestinationIndexName + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize DestinationIndexName (error: ${e.message})") + } + } + + // deserialize DestinationIndexPrefix + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize DestinationIndexPrefix (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationSearch.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationSearch.kt new file mode 100644 index 0000000000..f639831a25 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationSearch.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Payload to search for multiple destinations, based on the given `destinationIDs`. + * + * @param destinationIDs + */ +@Serializable +public data class DestinationSearch( + + @SerialName(value = "destinationIDs") val destinationIDs: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationSortKeys.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationSortKeys.kt new file mode 100644 index 0000000000..69218fcb9a --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationSortKeys.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* + +/** + * Used to sort the Destination list endpoint. + */ +@Serializable +public enum class DestinationSortKeys(public val value: kotlin.String) { + + @SerialName(value = "name") + Name("name"), + + @SerialName(value = "type") + Type("type"), + + @SerialName(value = "updatedAt") + UpdatedAt("updatedAt"), + + @SerialName(value = "createdAt") + CreatedAt("createdAt"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationType.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationType.kt new file mode 100644 index 0000000000..b33d108032 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationType.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* + +/** + * Type of the Destination, defines in which Algolia product the data will be stored. + */ +@Serializable +public enum class DestinationType(public val value: kotlin.String) { + + @SerialName(value = "search") + Search("search"), + + @SerialName(value = "insights") + Insights("insights"), + + @SerialName(value = "flow") + Flow("flow"), + + @SerialName(value = "predict") + Predict("predict"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationUpdate.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationUpdate.kt new file mode 100644 index 0000000000..3a324449f9 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationUpdate.kt @@ -0,0 +1,26 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Payload to partialy update a Destination. + * + * @param type + * @param name An human readable name describing the object. + * @param input + * @param authenticationID + */ +@Serializable +public data class DestinationUpdate( + + @SerialName(value = "type") val type: DestinationType? = null, + + /** An human readable name describing the object. */ + @SerialName(value = "name") val name: String? = null, + + @SerialName(value = "input") val input: DestinationInput? = null, + + @SerialName(value = "authenticationID") val authenticationID: String? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationUpdateResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationUpdateResponse.kt new file mode 100644 index 0000000000..0beab7484d --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/DestinationUpdateResponse.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Response from the API when the Destination is successfully updated. + * + * @param destinationID The destination UUID. + * @param name An human readable name describing the object. + * @param updatedAt Date of last update (RFC3339 format). + */ +@Serializable +public data class DestinationUpdateResponse( + + /** The destination UUID. */ + @SerialName(value = "destinationID") val destinationID: String, + + /** An human readable name describing the object. */ + @SerialName(value = "name") val name: String, + + /** Date of last update (RFC3339 format). */ + @SerialName(value = "updatedAt") val updatedAt: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ErrorBase.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ErrorBase.kt new file mode 100644 index 0000000000..dfbc24b055 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ErrorBase.kt @@ -0,0 +1,46 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Error. + * + * @param message + */ +@Serializable(ErrorBaseSerializer::class) +public data class ErrorBase( + + val message: String? = null, + + val additionalProperties: Map? = null, +) + +internal object ErrorBaseSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("ErrorBase") { + element("message") + } + + override fun deserialize(decoder: Decoder): ErrorBase { + val input = decoder.asJsonDecoder() + val tree = input.decodeJsonObject() + return ErrorBase( + message = tree["message"]?.let { input.json.decodeFromJsonElement(it) }, + additionalProperties = tree.filterKeys { it !in descriptor.elementNames }, + ) + } + + override fun serialize(encoder: Encoder, value: ErrorBase) { + val output = encoder.asJsonEncoder() + val json = buildJsonObject { + value.message?.let { put("message", output.json.encodeToJsonElement(it)) } + value.additionalProperties?.onEach { (key, element) -> put(key, element) } + } + (encoder as JsonEncoder).encodeJsonElement(json) + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Event.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Event.kt new file mode 100644 index 0000000000..09baf3b82e --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Event.kt @@ -0,0 +1,38 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * An event describe a step of the task execution flow.. + * + * @param eventID The event UUID. + * @param runID The run UUID. + * @param status + * @param type + * @param publishedAt Date of publish (RFC3339 format). + * @param parentID The parent event, the cause of this event. + * @param `data` + */ +@Serializable +public data class Event( + + /** The event UUID. */ + @SerialName(value = "eventID") val eventID: String, + + /** The run UUID. */ + @SerialName(value = "runID") val runID: String, + + @SerialName(value = "status") val status: EventStatus, + + @SerialName(value = "type") val type: EventType, + + /** Date of publish (RFC3339 format). */ + @SerialName(value = "publishedAt") val publishedAt: String, + + /** The parent event, the cause of this event. */ + @SerialName(value = "parentID") val parentID: String? = null, + + @SerialName(value = "data") val `data`: JsonObject? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/EventSortKeys.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/EventSortKeys.kt new file mode 100644 index 0000000000..37c9366f71 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/EventSortKeys.kt @@ -0,0 +1,22 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* + +/** + * Used to sort the Event list endpoint. + */ +@Serializable +public enum class EventSortKeys(public val value: kotlin.String) { + + @SerialName(value = "status") + Status("status"), + + @SerialName(value = "type") + Type("type"), + + @SerialName(value = "publishedAt") + PublishedAt("publishedAt"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/EventStatus.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/EventStatus.kt new file mode 100644 index 0000000000..77e8910179 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/EventStatus.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* + +@Serializable +public enum class EventStatus(public val value: kotlin.String) { + + @SerialName(value = "created") + Created("created"), + + @SerialName(value = "started") + Started("started"), + + @SerialName(value = "retried") + Retried("retried"), + + @SerialName(value = "failed") + Failed("failed"), + + @SerialName(value = "succeeded") + Succeeded("succeeded"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/EventType.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/EventType.kt new file mode 100644 index 0000000000..0b3a34ce9f --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/EventType.kt @@ -0,0 +1,22 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* + +@Serializable +public enum class EventType(public val value: kotlin.String) { + + @SerialName(value = "fetch") + Fetch("fetch"), + + @SerialName(value = "record") + Record("record"), + + @SerialName(value = "log") + Log("log"), + + @SerialName(value = "transform") + Transform("transform"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ListAuthenticationsResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ListAuthenticationsResponse.kt new file mode 100644 index 0000000000..8a9b3386b0 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ListAuthenticationsResponse.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * ListAuthenticationsResponse + * + * @param authentications + * @param pagination + */ +@Serializable +public data class ListAuthenticationsResponse( + + @SerialName(value = "authentications") val authentications: List, + + @SerialName(value = "pagination") val pagination: Pagination, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ListDestinationsResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ListDestinationsResponse.kt new file mode 100644 index 0000000000..1890914292 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ListDestinationsResponse.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * ListDestinationsResponse + * + * @param destinations + * @param pagination + */ +@Serializable +public data class ListDestinationsResponse( + + @SerialName(value = "destinations") val destinations: List, + + @SerialName(value = "pagination") val pagination: Pagination, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ListEventsResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ListEventsResponse.kt new file mode 100644 index 0000000000..437097c586 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ListEventsResponse.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * ListEventsResponse + * + * @param events + * @param pagination + */ +@Serializable +public data class ListEventsResponse( + + @SerialName(value = "events") val events: List, + + @SerialName(value = "pagination") val pagination: Pagination, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ListSourcesResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ListSourcesResponse.kt new file mode 100644 index 0000000000..61ac69c80b --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ListSourcesResponse.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * ListSourcesResponse + * + * @param sources + * @param pagination + */ +@Serializable +public data class ListSourcesResponse( + + @SerialName(value = "sources") val sources: List, + + @SerialName(value = "pagination") val pagination: Pagination, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ListTasksResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ListTasksResponse.kt new file mode 100644 index 0000000000..85b936158e --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ListTasksResponse.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * A list of tasks with pagination details. + * + * @param tasks + * @param pagination + */ +@Serializable +public data class ListTasksResponse( + + @SerialName(value = "tasks") val tasks: List, + + @SerialName(value = "pagination") val pagination: Pagination, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/MappingTypeCSV.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/MappingTypeCSV.kt new file mode 100644 index 0000000000..36d6cb3734 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/MappingTypeCSV.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* + +@Serializable +public enum class MappingTypeCSV(public val value: kotlin.String) { + + @SerialName(value = "string") + String("string"), + + @SerialName(value = "integer") + Integer("integer"), + + @SerialName(value = "float") + Float("float"), + + @SerialName(value = "boolean") + Boolean("boolean"), + + @SerialName(value = "json") + Json("json"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/MethodType.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/MethodType.kt new file mode 100644 index 0000000000..51d3f71c35 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/MethodType.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* + +@Serializable +public enum class MethodType(public val value: kotlin.String) { + + @SerialName(value = "GET") + GET("GET"), + + @SerialName(value = "POST") + POST("POST"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/OnDemandTrigger.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/OnDemandTrigger.kt new file mode 100644 index 0000000000..6759e5b90c --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/OnDemandTrigger.kt @@ -0,0 +1,20 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The trigger information of a task of type `onDemand`. + * + * @param type + * @param lastRun The last time the scheduled task ran (RFC3339 format). + */ +@Serializable +public data class OnDemandTrigger( + + @SerialName(value = "type") val type: OnDemandTriggerType, + + /** The last time the scheduled task ran (RFC3339 format). */ + @SerialName(value = "lastRun") val lastRun: String? = null, +) : Trigger diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/OnDemandTriggerInput.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/OnDemandTriggerInput.kt new file mode 100644 index 0000000000..7a6724c1ab --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/OnDemandTriggerInput.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The trigger information of a task of type `onDemand`. + * + * @param type + */ +@Serializable +public data class OnDemandTriggerInput( + + @SerialName(value = "type") val type: OnDemandTriggerType, +) : TaskCreateTrigger diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/OnDemandTriggerType.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/OnDemandTriggerType.kt new file mode 100644 index 0000000000..6b8e938668 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/OnDemandTriggerType.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* + +/** + * A task which is manually executed via the run task endpoint. + */ +@Serializable +public enum class OnDemandTriggerType(public val value: kotlin.String) { + + @SerialName(value = "onDemand") + OnDemand("onDemand"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/OrderKeys.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/OrderKeys.kt new file mode 100644 index 0000000000..81e0552543 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/OrderKeys.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* + +/** + * Used to order a sorted request. + */ +@Serializable +public enum class OrderKeys(public val value: kotlin.String) { + + @SerialName(value = "asc") + Asc("asc"), + + @SerialName(value = "desc") + Desc("desc"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Pagination.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Pagination.kt new file mode 100644 index 0000000000..9d869b28c5 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Pagination.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Pagination + * + * @param nbPages + * @param page + * @param nbItems + * @param itemsPerPage + */ +@Serializable +public data class Pagination( + + @SerialName(value = "nbPages") val nbPages: Int, + + @SerialName(value = "page") val page: Int, + + @SerialName(value = "nbItems") val nbItems: Int, + + @SerialName(value = "itemsPerPage") val itemsPerPage: Int, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Platform.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Platform.kt new file mode 100644 index 0000000000..eae2fca0e0 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Platform.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* + +/** + * Describe which platform the Authentication is used for. + */ +@Serializable +public enum class Platform(public val value: kotlin.String) : PlatformWithNone { + + @SerialName(value = "bigcommerce") + Bigcommerce("bigcommerce"), + + @SerialName(value = "commercetools") + Commercetools("commercetools"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/PlatformNone.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/PlatformNone.kt new file mode 100644 index 0000000000..beee331636 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/PlatformNone.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* + +/** + * Used to filter Authentication without platform property. + */ +@Serializable +public enum class PlatformNone(public val value: kotlin.String) : PlatformWithNone { + + @SerialName(value = "none") + None("none"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/PlatformWithNone.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/PlatformWithNone.kt new file mode 100644 index 0000000000..c4e3277b51 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/PlatformWithNone.kt @@ -0,0 +1,69 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * PlatformWithNone + */ +@Serializable(PlatformWithNoneSerializer::class) +public sealed interface PlatformWithNone { + + public companion object { + + /** + * Describe which platform the Authentication is used for. + */ + public fun of(value: Platform): Platform = value + + /** + * Used to filter Authentication without platform property. + */ + public fun of(value: PlatformNone): PlatformNone = value + } +} + +internal class PlatformWithNoneSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("PlatformWithNone") + + override fun serialize(encoder: Encoder, value: PlatformWithNone) { + when (value) { + is Platform -> Platform.serializer().serialize(encoder, value) + is PlatformNone -> PlatformNone.serializer().serialize(encoder, value) + } + } + + override fun deserialize(decoder: Decoder): PlatformWithNone { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize Platform + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize Platform (error: ${e.message})") + } + } + + // deserialize PlatformNone + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize PlatformNone (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Run.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Run.kt new file mode 100644 index 0000000000..db998e27b5 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Run.kt @@ -0,0 +1,56 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Run + * + * @param runID The run UUID. + * @param appID + * @param taskID The task UUID. + * @param status + * @param type + * @param createdAt Date of creation (RFC3339 format). + * @param updatedAt Date of last update (RFC3339 format). + * @param progress + * @param outcome + * @param reason Explains the result of outcome. + * @param startedAt Date of start (RFC3339 format). + * @param finishedAt Date of finish (RFC3339 format). + */ +@Serializable +public data class Run( + + /** The run UUID. */ + @SerialName(value = "runID") val runID: String, + + @SerialName(value = "appID") val appID: String, + + /** The task UUID. */ + @SerialName(value = "taskID") val taskID: String, + + @SerialName(value = "status") val status: RunStatus, + + @SerialName(value = "type") val type: RunType, + + /** Date of creation (RFC3339 format). */ + @SerialName(value = "createdAt") val createdAt: String, + + /** Date of last update (RFC3339 format). */ + @SerialName(value = "updatedAt") val updatedAt: String, + + @SerialName(value = "progress") val progress: RunProgress? = null, + + @SerialName(value = "outcome") val outcome: RunOutcome? = null, + + /** Explains the result of outcome. */ + @SerialName(value = "reason") val reason: String? = null, + + /** Date of start (RFC3339 format). */ + @SerialName(value = "startedAt") val startedAt: String? = null, + + /** Date of finish (RFC3339 format). */ + @SerialName(value = "finishedAt") val finishedAt: String? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/RunListResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/RunListResponse.kt new file mode 100644 index 0000000000..b611f84886 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/RunListResponse.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * RunListResponse + * + * @param runs + * @param pagination + */ +@Serializable +public data class RunListResponse( + + @SerialName(value = "runs") val runs: List, + + @SerialName(value = "pagination") val pagination: Pagination, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/RunOutcome.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/RunOutcome.kt new file mode 100644 index 0000000000..346db19e1d --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/RunOutcome.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* + +@Serializable +public enum class RunOutcome(public val value: kotlin.String) { + + @SerialName(value = "success") + Success("success"), + + @SerialName(value = "failure") + Failure("failure"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/RunProgress.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/RunProgress.kt new file mode 100644 index 0000000000..443dd9e01e --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/RunProgress.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * RunProgress + * + * @param expectedNbOfEvents + * @param receivedNbOfEvents + */ +@Serializable +public data class RunProgress( + + @SerialName(value = "expectedNbOfEvents") val expectedNbOfEvents: Int? = null, + + @SerialName(value = "receivedNbOfEvents") val receivedNbOfEvents: Int? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/RunResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/RunResponse.kt new file mode 100644 index 0000000000..feab43e62a --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/RunResponse.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The response from the run task API, containing an Observability Run ID and the time it was created at. + * + * @param runID The run UUID. + * @param createdAt Date of creation (RFC3339 format). + */ +@Serializable +public data class RunResponse( + + /** The run UUID. */ + @SerialName(value = "runID") val runID: String, + + /** Date of creation (RFC3339 format). */ + @SerialName(value = "createdAt") val createdAt: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/RunSortKeys.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/RunSortKeys.kt new file mode 100644 index 0000000000..170fd67244 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/RunSortKeys.kt @@ -0,0 +1,22 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* + +/** + * Used to sort the Run list endpoint. + */ +@Serializable +public enum class RunSortKeys(public val value: kotlin.String) { + + @SerialName(value = "status") + Status("status"), + + @SerialName(value = "updatedAt") + UpdatedAt("updatedAt"), + + @SerialName(value = "createdAt") + CreatedAt("createdAt"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/RunStatus.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/RunStatus.kt new file mode 100644 index 0000000000..a21b7ff336 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/RunStatus.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* + +@Serializable +public enum class RunStatus(public val value: kotlin.String) { + + @SerialName(value = "created") + Created("created"), + + @SerialName(value = "started") + Started("started"), + + @SerialName(value = "idled") + Idled("idled"), + + @SerialName(value = "finished") + Finished("finished"), + + @SerialName(value = "skipped") + Skipped("skipped"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/RunType.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/RunType.kt new file mode 100644 index 0000000000..bfc28288cf --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/RunType.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* + +@Serializable +public enum class RunType(public val value: kotlin.String) { + + @SerialName(value = "reindex") + Reindex("reindex"), + + @SerialName(value = "update") + Update("update"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ScheduleTrigger.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ScheduleTrigger.kt new file mode 100644 index 0000000000..ec4b6044b1 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ScheduleTrigger.kt @@ -0,0 +1,28 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The trigger information for a task of type 'schedule'. + * + * @param type + * @param cron A cron expression that represent at which regularity the task should run. + * @param nextRun The next scheduled run of the task (RFC3339 format). + * @param lastRun The last time the scheduled task ran (RFC3339 format). + */ +@Serializable +public data class ScheduleTrigger( + + @SerialName(value = "type") val type: ScheduleTriggerType, + + /** A cron expression that represent at which regularity the task should run. */ + @SerialName(value = "cron") val cron: String, + + /** The next scheduled run of the task (RFC3339 format). */ + @SerialName(value = "nextRun") val nextRun: String, + + /** The last time the scheduled task ran (RFC3339 format). */ + @SerialName(value = "lastRun") val lastRun: String? = null, +) : Trigger diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ScheduleTriggerInput.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ScheduleTriggerInput.kt new file mode 100644 index 0000000000..c593b21e0b --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ScheduleTriggerInput.kt @@ -0,0 +1,20 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The trigger input for a task of type 'schedule'. + * + * @param type + * @param cron A cron expression that represent at which regularity the task should run. + */ +@Serializable +public data class ScheduleTriggerInput( + + @SerialName(value = "type") val type: ScheduleTriggerType, + + /** A cron expression that represent at which regularity the task should run. */ + @SerialName(value = "cron") val cron: String, +) : TaskCreateTrigger diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ScheduleTriggerType.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ScheduleTriggerType.kt new file mode 100644 index 0000000000..00f54c3fe2 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/ScheduleTriggerType.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* + +/** + * A task which is triggered by a schedule (cron expression). + */ +@Serializable +public enum class ScheduleTriggerType(public val value: kotlin.String) { + + @SerialName(value = "schedule") + Schedule("schedule"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Source.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Source.kt new file mode 100644 index 0000000000..8601f16471 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Source.kt @@ -0,0 +1,38 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Source + * + * @param sourceID The source UUID. + * @param type + * @param name + * @param input + * @param createdAt Date of creation (RFC3339 format). + * @param authenticationID The authentication UUID. + * @param updatedAt Date of last update (RFC3339 format). + */ +@Serializable +public data class Source( + + /** The source UUID. */ + @SerialName(value = "sourceID") val sourceID: String, + + @SerialName(value = "type") val type: SourceType, + + @SerialName(value = "name") val name: String, + + @SerialName(value = "input") val input: SourceInput, + + /** Date of creation (RFC3339 format). */ + @SerialName(value = "createdAt") val createdAt: String, + + /** The authentication UUID. */ + @SerialName(value = "authenticationID") val authenticationID: String? = null, + + /** Date of last update (RFC3339 format). */ + @SerialName(value = "updatedAt") val updatedAt: String? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceBigCommerce.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceBigCommerce.kt new file mode 100644 index 0000000000..be1d6ce09a --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceBigCommerce.kt @@ -0,0 +1,20 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SourceBigCommerce + * + * @param storeHash The store hash identifying the store the shopper is signing in to. + * @param channel + */ +@Serializable +public data class SourceBigCommerce( + + /** The store hash identifying the store the shopper is signing in to. */ + @SerialName(value = "storeHash") val storeHash: String? = null, + + @SerialName(value = "channel") val channel: BigCommerceChannel? = null, +) : SourceInput diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceBigQuery.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceBigQuery.kt new file mode 100644 index 0000000000..e9111e1d26 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceBigQuery.kt @@ -0,0 +1,32 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SourceBigQuery + * + * @param projectID Project ID of the BigQuery Source. + * @param datasetID Dataset ID of the BigQuery Source. + * @param dataType + * @param table Table name (for default BQ). + * @param tablePrefix Table prefix (for Google Analytics). + */ +@Serializable +public data class SourceBigQuery( + + /** Project ID of the BigQuery Source. */ + @SerialName(value = "projectID") val projectID: String, + + /** Dataset ID of the BigQuery Source. */ + @SerialName(value = "datasetID") val datasetID: String, + + @SerialName(value = "dataType") val dataType: BigQueryDataType? = null, + + /** Table name (for default BQ). */ + @SerialName(value = "table") val table: String? = null, + + /** Table prefix (for Google Analytics). */ + @SerialName(value = "tablePrefix") val tablePrefix: String? = null, +) : SourceUpdateInput, SourceInput diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceCSV.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceCSV.kt new file mode 100644 index 0000000000..c63857880f --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceCSV.kt @@ -0,0 +1,32 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SourceCSV + * + * @param url The URL of the file. + * @param uniqueIDColumn The name of the column that contains the unique ID, used as `objectID` in Algolia. + * @param mapping Mapping of type for every column. For example {\"myColumn\": \"boolean\", \"myOtherColumn\": \"json\"}. + * @param method + * @param delimiter The character used to split the value on each line, default to a comma (\\r, \\n, 0xFFFD, and space are forbidden). + */ +@Serializable +public data class SourceCSV( + + /** The URL of the file. */ + @SerialName(value = "url") val url: String, + + /** The name of the column that contains the unique ID, used as `objectID` in Algolia. */ + @SerialName(value = "uniqueIDColumn") val uniqueIDColumn: String? = null, + + /** Mapping of type for every column. For example {\"myColumn\": \"boolean\", \"myOtherColumn\": \"json\"}. */ + @SerialName(value = "mapping") val mapping: Map? = null, + + @SerialName(value = "method") val method: MethodType? = null, + + /** The character used to split the value on each line, default to a comma (\\r, \\n, 0xFFFD, and space are forbidden). */ + @SerialName(value = "delimiter") val delimiter: String? = null, +) : SourceUpdateInput, SourceInput diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceCommercetools.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceCommercetools.kt new file mode 100644 index 0000000000..6249f4a05f --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceCommercetools.kt @@ -0,0 +1,26 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SourceCommercetools + * + * @param url + * @param projectKey + * @param storeKeys + * @param locales Array of locales that must match the following pattern: ^[a-z]{2}(-[A-Z]{2})?$. For example [\"fr-FR\", \"en\"]. + */ +@Serializable +public data class SourceCommercetools( + + @SerialName(value = "url") val url: String, + + @SerialName(value = "projectKey") val projectKey: String, + + @SerialName(value = "storeKeys") val storeKeys: List? = null, + + /** Array of locales that must match the following pattern: ^[a-z]{2}(-[A-Z]{2})?$. For example [\"fr-FR\", \"en\"]. */ + @SerialName(value = "locales") val locales: List? = null, +) : SourceInput diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceCreate.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceCreate.kt new file mode 100644 index 0000000000..708995b525 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceCreate.kt @@ -0,0 +1,26 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SourceCreate + * + * @param type + * @param name + * @param input + * @param authenticationID The authentication UUID. + */ +@Serializable +public data class SourceCreate( + + @SerialName(value = "type") val type: SourceType, + + @SerialName(value = "name") val name: String, + + @SerialName(value = "input") val input: SourceInput, + + /** The authentication UUID. */ + @SerialName(value = "authenticationID") val authenticationID: String? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceCreateResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceCreateResponse.kt new file mode 100644 index 0000000000..cbc8c3592c --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceCreateResponse.kt @@ -0,0 +1,24 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SourceCreateResponse + * + * @param sourceID The source UUID. + * @param name + * @param createdAt Date of creation (RFC3339 format). + */ +@Serializable +public data class SourceCreateResponse( + + /** The source UUID. */ + @SerialName(value = "sourceID") val sourceID: String, + + @SerialName(value = "name") val name: String, + + /** Date of creation (RFC3339 format). */ + @SerialName(value = "createdAt") val createdAt: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceInput.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceInput.kt new file mode 100644 index 0000000000..d6c3e73505 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceInput.kt @@ -0,0 +1,189 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * SourceInput + */ +@Serializable(SourceInputSerializer::class) +public sealed interface SourceInput { + + public companion object { + + /** + * SourceBigCommerce + * + * @param storeHash The store hash identifying the store the shopper is signing in to. + * @param channel + */ + public fun SourceBigCommerce( + storeHash: String? = null, + channel: BigCommerceChannel? = null, + ): SourceBigCommerce = com.algolia.client.model.ingestion.SourceBigCommerce( + storeHash = storeHash, + channel = channel, + ) + + /** + * SourceBigQuery + * + * @param projectID Project ID of the BigQuery Source. + * @param datasetID Dataset ID of the BigQuery Source. + * @param dataType + * @param table Table name (for default BQ). + * @param tablePrefix Table prefix (for Google Analytics). + */ + public fun SourceBigQuery( + projectID: String, + datasetID: String, + dataType: BigQueryDataType? = null, + table: String? = null, + tablePrefix: String? = null, + ): SourceBigQuery = com.algolia.client.model.ingestion.SourceBigQuery( + projectID = projectID, + datasetID = datasetID, + dataType = dataType, + table = table, + tablePrefix = tablePrefix, + ) + + /** + * SourceCSV + * + * @param url The URL of the file. + * @param uniqueIDColumn The name of the column that contains the unique ID, used as `objectID` in Algolia. + * @param mapping Mapping of type for every column. For example {\"myColumn\": \"boolean\", \"myOtherColumn\": \"json\"}. + * @param method + * @param delimiter The character used to split the value on each line, default to a comma (\\r, \\n, 0xFFFD, and space are forbidden). + */ + public fun SourceCSV( + url: String, + uniqueIDColumn: String? = null, + mapping: Map? = null, + method: MethodType? = null, + delimiter: String? = null, + ): SourceCSV = com.algolia.client.model.ingestion.SourceCSV( + url = url, + uniqueIDColumn = uniqueIDColumn, + mapping = mapping, + method = method, + delimiter = delimiter, + ) + + /** + * SourceCommercetools + * + * @param url + * @param projectKey + * @param storeKeys + * @param locales Array of locales that must match the following pattern: ^[a-z]{2}(-[A-Z]{2})?$. For example [\"fr-FR\", \"en\"]. + */ + public fun SourceCommercetools( + url: String, + projectKey: String, + storeKeys: List? = null, + locales: List? = null, + ): SourceCommercetools = com.algolia.client.model.ingestion.SourceCommercetools( + url = url, + projectKey = projectKey, + storeKeys = storeKeys, + locales = locales, + ) + + /** + * SourceJSON + * + * @param url The URL of the file. + * @param uniqueIDColumn The name of the column that contains the unique ID, used as `objectID` in Algolia. + * @param method + */ + public fun SourceJSON( + url: String, + uniqueIDColumn: String? = null, + method: MethodType? = null, + ): SourceJSON = com.algolia.client.model.ingestion.SourceJSON( + url = url, + uniqueIDColumn = uniqueIDColumn, + method = method, + ) + } +} + +internal class SourceInputSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("SourceInput") + + override fun serialize(encoder: Encoder, value: SourceInput) { + when (value) { + is SourceBigCommerce -> SourceBigCommerce.serializer().serialize(encoder, value) + is SourceBigQuery -> SourceBigQuery.serializer().serialize(encoder, value) + is SourceCSV -> SourceCSV.serializer().serialize(encoder, value) + is SourceCommercetools -> SourceCommercetools.serializer().serialize(encoder, value) + is SourceJSON -> SourceJSON.serializer().serialize(encoder, value) + } + } + + override fun deserialize(decoder: Decoder): SourceInput { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize SourceBigCommerce + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize SourceBigCommerce (error: ${e.message})") + } + } + + // deserialize SourceBigQuery + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize SourceBigQuery (error: ${e.message})") + } + } + + // deserialize SourceCSV + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize SourceCSV (error: ${e.message})") + } + } + + // deserialize SourceCommercetools + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize SourceCommercetools (error: ${e.message})") + } + } + + // deserialize SourceJSON + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize SourceJSON (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceJSON.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceJSON.kt new file mode 100644 index 0000000000..d252c2753b --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceJSON.kt @@ -0,0 +1,24 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SourceJSON + * + * @param url The URL of the file. + * @param uniqueIDColumn The name of the column that contains the unique ID, used as `objectID` in Algolia. + * @param method + */ +@Serializable +public data class SourceJSON( + + /** The URL of the file. */ + @SerialName(value = "url") val url: String, + + /** The name of the column that contains the unique ID, used as `objectID` in Algolia. */ + @SerialName(value = "uniqueIDColumn") val uniqueIDColumn: String? = null, + + @SerialName(value = "method") val method: MethodType? = null, +) : SourceUpdateInput, SourceInput diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceSearch.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceSearch.kt new file mode 100644 index 0000000000..0ba3030d8b --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceSearch.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SourceSearch + * + * @param sourceIDs + */ +@Serializable +public data class SourceSearch( + + @SerialName(value = "sourceIDs") val sourceIDs: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceSortKeys.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceSortKeys.kt new file mode 100644 index 0000000000..ca0728e4ca --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceSortKeys.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* + +/** + * Used to sort the Source list endpoint. + */ +@Serializable +public enum class SourceSortKeys(public val value: kotlin.String) { + + @SerialName(value = "name") + Name("name"), + + @SerialName(value = "type") + Type("type"), + + @SerialName(value = "updatedAt") + UpdatedAt("updatedAt"), + + @SerialName(value = "createdAt") + CreatedAt("createdAt"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceType.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceType.kt new file mode 100644 index 0000000000..103ed1e443 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceType.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* + +@Serializable +public enum class SourceType(public val value: kotlin.String) { + + @SerialName(value = "bigcommerce") + Bigcommerce("bigcommerce"), + + @SerialName(value = "commercetools") + Commercetools("commercetools"), + + @SerialName(value = "json") + Json("json"), + + @SerialName(value = "csv") + Csv("csv"), + + @SerialName(value = "bigquery") + Bigquery("bigquery"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceUpdate.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceUpdate.kt new file mode 100644 index 0000000000..886efc0fed --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceUpdate.kt @@ -0,0 +1,23 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SourceUpdate + * + * @param name + * @param input + * @param authenticationID The authentication UUID. + */ +@Serializable +public data class SourceUpdate( + + @SerialName(value = "name") val name: String? = null, + + @SerialName(value = "input") val input: SourceUpdateInput? = null, + + /** The authentication UUID. */ + @SerialName(value = "authenticationID") val authenticationID: String? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceUpdateCommercetools.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceUpdateCommercetools.kt new file mode 100644 index 0000000000..af2ee67eed --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceUpdateCommercetools.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SourceUpdateCommercetools + * + * @param storeKeys Unique and immutable key of the referenced Store. + * @param locales Array of locales that must match the following pattern: ^[a-z]{2}(-[A-Z]{2})?$. For example [\"fr-FR\", \"en\"]. + */ +@Serializable +public data class SourceUpdateCommercetools( + + /** Unique and immutable key of the referenced Store. */ + @SerialName(value = "storeKeys") val storeKeys: List? = null, + + /** Array of locales that must match the following pattern: ^[a-z]{2}(-[A-Z]{2})?$. For example [\"fr-FR\", \"en\"]. */ + @SerialName(value = "locales") val locales: List? = null, +) : SourceUpdateInput diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceUpdateInput.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceUpdateInput.kt new file mode 100644 index 0000000000..94850eda30 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceUpdateInput.kt @@ -0,0 +1,158 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * SourceUpdateInput + */ +@Serializable(SourceUpdateInputSerializer::class) +public sealed interface SourceUpdateInput { + + public companion object { + + /** + * SourceBigQuery + * + * @param projectID Project ID of the BigQuery Source. + * @param datasetID Dataset ID of the BigQuery Source. + * @param dataType + * @param table Table name (for default BQ). + * @param tablePrefix Table prefix (for Google Analytics). + */ + public fun SourceBigQuery( + projectID: String, + datasetID: String, + dataType: BigQueryDataType? = null, + table: String? = null, + tablePrefix: String? = null, + ): SourceBigQuery = com.algolia.client.model.ingestion.SourceBigQuery( + projectID = projectID, + datasetID = datasetID, + dataType = dataType, + table = table, + tablePrefix = tablePrefix, + ) + + /** + * SourceCSV + * + * @param url The URL of the file. + * @param uniqueIDColumn The name of the column that contains the unique ID, used as `objectID` in Algolia. + * @param mapping Mapping of type for every column. For example {\"myColumn\": \"boolean\", \"myOtherColumn\": \"json\"}. + * @param method + * @param delimiter The character used to split the value on each line, default to a comma (\\r, \\n, 0xFFFD, and space are forbidden). + */ + public fun SourceCSV( + url: String, + uniqueIDColumn: String? = null, + mapping: Map? = null, + method: MethodType? = null, + delimiter: String? = null, + ): SourceCSV = com.algolia.client.model.ingestion.SourceCSV( + url = url, + uniqueIDColumn = uniqueIDColumn, + mapping = mapping, + method = method, + delimiter = delimiter, + ) + + /** + * SourceJSON + * + * @param url The URL of the file. + * @param uniqueIDColumn The name of the column that contains the unique ID, used as `objectID` in Algolia. + * @param method + */ + public fun SourceJSON( + url: String, + uniqueIDColumn: String? = null, + method: MethodType? = null, + ): SourceJSON = com.algolia.client.model.ingestion.SourceJSON( + url = url, + uniqueIDColumn = uniqueIDColumn, + method = method, + ) + + /** + * SourceUpdateCommercetools + * + * @param storeKeys Unique and immutable key of the referenced Store. + * @param locales Array of locales that must match the following pattern: ^[a-z]{2}(-[A-Z]{2})?$. For example [\"fr-FR\", \"en\"]. + */ + public fun SourceUpdateCommercetools( + storeKeys: List? = null, + locales: List? = null, + ): SourceUpdateCommercetools = com.algolia.client.model.ingestion.SourceUpdateCommercetools( + storeKeys = storeKeys, + locales = locales, + ) + } +} + +internal class SourceUpdateInputSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("SourceUpdateInput") + + override fun serialize(encoder: Encoder, value: SourceUpdateInput) { + when (value) { + is SourceBigQuery -> SourceBigQuery.serializer().serialize(encoder, value) + is SourceCSV -> SourceCSV.serializer().serialize(encoder, value) + is SourceJSON -> SourceJSON.serializer().serialize(encoder, value) + is SourceUpdateCommercetools -> SourceUpdateCommercetools.serializer().serialize(encoder, value) + } + } + + override fun deserialize(decoder: Decoder): SourceUpdateInput { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize SourceBigQuery + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize SourceBigQuery (error: ${e.message})") + } + } + + // deserialize SourceCSV + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize SourceCSV (error: ${e.message})") + } + } + + // deserialize SourceJSON + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize SourceJSON (error: ${e.message})") + } + } + + // deserialize SourceUpdateCommercetools + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize SourceUpdateCommercetools (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceUpdateResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceUpdateResponse.kt new file mode 100644 index 0000000000..731f972c66 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SourceUpdateResponse.kt @@ -0,0 +1,24 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SourceUpdateResponse + * + * @param sourceID The source UUID. + * @param name + * @param updatedAt Date of last update (RFC3339 format). + */ +@Serializable +public data class SourceUpdateResponse( + + /** The source UUID. */ + @SerialName(value = "sourceID") val sourceID: String, + + @SerialName(value = "name") val name: String, + + /** Date of last update (RFC3339 format). */ + @SerialName(value = "updatedAt") val updatedAt: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SubscriptionTrigger.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SubscriptionTrigger.kt new file mode 100644 index 0000000000..1953352684 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SubscriptionTrigger.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The trigger input for a task of type 'subscription'. + * + * @param type + */ +@Serializable +public data class SubscriptionTrigger( + + @SerialName(value = "type") val type: SubscriptionTriggerType, +) : Trigger, TaskCreateTrigger diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SubscriptionTriggerType.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SubscriptionTriggerType.kt new file mode 100644 index 0000000000..6167d9e1d8 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/SubscriptionTriggerType.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* + +/** + * A task which is triggered by an external subscription (e.g. Webhook). + */ +@Serializable +public enum class SubscriptionTriggerType(public val value: kotlin.String) { + + @SerialName(value = "subscription") + Subscription("subscription"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Task.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Task.kt new file mode 100644 index 0000000000..e59e983c48 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Task.kt @@ -0,0 +1,47 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Task + * + * @param taskID The task UUID. + * @param sourceID The source UUID. + * @param destinationID The destination UUID. + * @param trigger + * @param enabled Whether the task is enabled or not. + * @param action + * @param createdAt Date of creation (RFC3339 format). + * @param input The input that holds information specific to the task. + * @param updatedAt Date of last update (RFC3339 format). + */ +@Serializable +public data class Task( + + /** The task UUID. */ + @SerialName(value = "taskID") val taskID: String, + + /** The source UUID. */ + @SerialName(value = "sourceID") val sourceID: String, + + /** The destination UUID. */ + @SerialName(value = "destinationID") val destinationID: String, + + @SerialName(value = "trigger") val trigger: Trigger, + + /** Whether the task is enabled or not. */ + @SerialName(value = "enabled") val enabled: Boolean, + + @SerialName(value = "action") val action: ActionType, + + /** Date of creation (RFC3339 format). */ + @SerialName(value = "createdAt") val createdAt: String, + + /** The input that holds information specific to the task. */ + @SerialName(value = "input") val input: JsonObject? = null, + + /** Date of last update (RFC3339 format). */ + @SerialName(value = "updatedAt") val updatedAt: String? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TaskCreate.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TaskCreate.kt new file mode 100644 index 0000000000..36f701e145 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TaskCreate.kt @@ -0,0 +1,31 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The payload for a task creation. + * + * @param sourceID The source UUID. + * @param destinationID The destination UUID. + * @param trigger + * @param action + * @param enabled Whether the task is enabled or not. + */ +@Serializable +public data class TaskCreate( + + /** The source UUID. */ + @SerialName(value = "sourceID") val sourceID: String, + + /** The destination UUID. */ + @SerialName(value = "destinationID") val destinationID: String, + + @SerialName(value = "trigger") val trigger: TaskCreateTrigger, + + @SerialName(value = "action") val action: ActionType, + + /** Whether the task is enabled or not. */ + @SerialName(value = "enabled") val enabled: Boolean? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TaskCreateResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TaskCreateResponse.kt new file mode 100644 index 0000000000..f1afecb6e9 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TaskCreateResponse.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The response from the API after a task creation. + * + * @param taskID The task UUID. + * @param createdAt Date of creation (RFC3339 format). + */ +@Serializable +public data class TaskCreateResponse( + + /** The task UUID. */ + @SerialName(value = "taskID") val taskID: String, + + /** Date of creation (RFC3339 format). */ + @SerialName(value = "createdAt") val createdAt: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TaskCreateTrigger.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TaskCreateTrigger.kt new file mode 100644 index 0000000000..ca24da7df2 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TaskCreateTrigger.kt @@ -0,0 +1,106 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * TaskCreateTrigger + */ +@Serializable(TaskCreateTriggerSerializer::class) +public sealed interface TaskCreateTrigger { + + public companion object { + + /** + * The trigger information of a task of type `onDemand`. + * + * @param type + */ + public fun OnDemandTriggerInput( + type: OnDemandTriggerType, + ): OnDemandTriggerInput = com.algolia.client.model.ingestion.OnDemandTriggerInput( + type = type, + ) + + /** + * The trigger input for a task of type 'schedule'. + * + * @param type + * @param cron A cron expression that represent at which regularity the task should run. + */ + public fun ScheduleTriggerInput( + type: ScheduleTriggerType, + cron: String, + ): ScheduleTriggerInput = com.algolia.client.model.ingestion.ScheduleTriggerInput( + type = type, + cron = cron, + ) + + /** + * The trigger input for a task of type 'subscription'. + * + * @param type + */ + public fun SubscriptionTrigger( + type: SubscriptionTriggerType, + ): SubscriptionTrigger = com.algolia.client.model.ingestion.SubscriptionTrigger( + type = type, + ) + } +} + +internal class TaskCreateTriggerSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("TaskCreateTrigger") + + override fun serialize(encoder: Encoder, value: TaskCreateTrigger) { + when (value) { + is OnDemandTriggerInput -> OnDemandTriggerInput.serializer().serialize(encoder, value) + is ScheduleTriggerInput -> ScheduleTriggerInput.serializer().serialize(encoder, value) + is SubscriptionTrigger -> SubscriptionTrigger.serializer().serialize(encoder, value) + } + } + + override fun deserialize(decoder: Decoder): TaskCreateTrigger { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize OnDemandTriggerInput + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize OnDemandTriggerInput (error: ${e.message})") + } + } + + // deserialize ScheduleTriggerInput + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize ScheduleTriggerInput (error: ${e.message})") + } + } + + // deserialize SubscriptionTrigger + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize SubscriptionTrigger (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TaskSearch.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TaskSearch.kt new file mode 100644 index 0000000000..c3ffc3fd1b --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TaskSearch.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * TaskSearch + * + * @param taskIDs + */ +@Serializable +public data class TaskSearch( + + @SerialName(value = "taskIDs") val taskIDs: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TaskSortKeys.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TaskSortKeys.kt new file mode 100644 index 0000000000..3c2ad07f8a --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TaskSortKeys.kt @@ -0,0 +1,28 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* + +/** + * Used to sort the Task list endpoint. + */ +@Serializable +public enum class TaskSortKeys(public val value: kotlin.String) { + + @SerialName(value = "enabled") + Enabled("enabled"), + + @SerialName(value = "triggerType") + TriggerType("triggerType"), + + @SerialName(value = "action") + Action("action"), + + @SerialName(value = "updatedAt") + UpdatedAt("updatedAt"), + + @SerialName(value = "createdAt") + CreatedAt("createdAt"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TaskUpdate.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TaskUpdate.kt new file mode 100644 index 0000000000..b8fcd8b929 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TaskUpdate.kt @@ -0,0 +1,24 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The payload for a task update. + * + * @param destinationID The destination UUID. + * @param trigger + * @param enabled Whether the task is enabled or not. + */ +@Serializable +public data class TaskUpdate( + + /** The destination UUID. */ + @SerialName(value = "destinationID") val destinationID: String? = null, + + @SerialName(value = "trigger") val trigger: TriggerInput? = null, + + /** Whether the task is enabled or not. */ + @SerialName(value = "enabled") val enabled: Boolean? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TaskUpdateResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TaskUpdateResponse.kt new file mode 100644 index 0000000000..f85494ed17 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TaskUpdateResponse.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The response from the API after a task update. + * + * @param taskID The task UUID. + * @param updatedAt Date of last update (RFC3339 format). + */ +@Serializable +public data class TaskUpdateResponse( + + /** The task UUID. */ + @SerialName(value = "taskID") val taskID: String, + + /** Date of last update (RFC3339 format). */ + @SerialName(value = "updatedAt") val updatedAt: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Trigger.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Trigger.kt new file mode 100644 index 0000000000..d0a41c54ac --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/Trigger.kt @@ -0,0 +1,115 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Trigger + */ +@Serializable(TriggerSerializer::class) +public sealed interface Trigger { + + public companion object { + + /** + * The trigger information of a task of type `onDemand`. + * + * @param type + * @param lastRun The last time the scheduled task ran (RFC3339 format). + */ + public fun OnDemandTrigger( + type: OnDemandTriggerType, + lastRun: String? = null, + ): OnDemandTrigger = com.algolia.client.model.ingestion.OnDemandTrigger( + type = type, + lastRun = lastRun, + ) + + /** + * The trigger information for a task of type 'schedule'. + * + * @param type + * @param cron A cron expression that represent at which regularity the task should run. + * @param nextRun The next scheduled run of the task (RFC3339 format). + * @param lastRun The last time the scheduled task ran (RFC3339 format). + */ + public fun ScheduleTrigger( + type: ScheduleTriggerType, + cron: String, + nextRun: String, + lastRun: String? = null, + ): ScheduleTrigger = com.algolia.client.model.ingestion.ScheduleTrigger( + type = type, + cron = cron, + nextRun = nextRun, + lastRun = lastRun, + ) + + /** + * The trigger input for a task of type 'subscription'. + * + * @param type + */ + public fun SubscriptionTrigger( + type: SubscriptionTriggerType, + ): SubscriptionTrigger = com.algolia.client.model.ingestion.SubscriptionTrigger( + type = type, + ) + } +} + +internal class TriggerSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("Trigger") + + override fun serialize(encoder: Encoder, value: Trigger) { + when (value) { + is OnDemandTrigger -> OnDemandTrigger.serializer().serialize(encoder, value) + is ScheduleTrigger -> ScheduleTrigger.serializer().serialize(encoder, value) + is SubscriptionTrigger -> SubscriptionTrigger.serializer().serialize(encoder, value) + } + } + + override fun deserialize(decoder: Decoder): Trigger { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize OnDemandTrigger + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize OnDemandTrigger (error: ${e.message})") + } + } + + // deserialize ScheduleTrigger + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize ScheduleTrigger (error: ${e.message})") + } + } + + // deserialize SubscriptionTrigger + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize SubscriptionTrigger (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TriggerInput.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TriggerInput.kt new file mode 100644 index 0000000000..124d518f6a --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TriggerInput.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The trigger input of a task. + * + * @param type + */ +@Serializable +public data class TriggerInput( + + @SerialName(value = "type") val type: TriggerType, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TriggerType.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TriggerType.kt new file mode 100644 index 0000000000..f3cffaee5b --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/ingestion/TriggerType.kt @@ -0,0 +1,22 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.ingestion + +import kotlinx.serialization.* + +/** + * The type of the task reflect how it can be used: - onDemand: a task that runs manually - schedule: a task that runs regularly, following a given cron expression - subscription: a task that runs after a subscription event is received from an integration (e.g. Webhook). + */ +@Serializable +public enum class TriggerType(public val value: kotlin.String) { + + @SerialName(value = "onDemand") + OnDemand("onDemand"), + + @SerialName(value = "schedule") + Schedule("schedule"), + + @SerialName(value = "subscription") + Subscription("subscription"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/insights/ErrorBase.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/insights/ErrorBase.kt new file mode 100644 index 0000000000..c0302a99f8 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/insights/ErrorBase.kt @@ -0,0 +1,46 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.insights + +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Error. + * + * @param message + */ +@Serializable(ErrorBaseSerializer::class) +public data class ErrorBase( + + val message: String? = null, + + val additionalProperties: Map? = null, +) + +internal object ErrorBaseSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("ErrorBase") { + element("message") + } + + override fun deserialize(decoder: Decoder): ErrorBase { + val input = decoder.asJsonDecoder() + val tree = input.decodeJsonObject() + return ErrorBase( + message = tree["message"]?.let { input.json.decodeFromJsonElement(it) }, + additionalProperties = tree.filterKeys { it !in descriptor.elementNames }, + ) + } + + override fun serialize(encoder: Encoder, value: ErrorBase) { + val output = encoder.asJsonEncoder() + val json = buildJsonObject { + value.message?.let { put("message", output.json.encodeToJsonElement(it)) } + value.additionalProperties?.onEach { (key, element) -> put(key, element) } + } + (encoder as JsonEncoder).encodeJsonElement(json) + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/insights/EventType.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/insights/EventType.kt new file mode 100644 index 0000000000..89ac32891e --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/insights/EventType.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.insights + +import kotlinx.serialization.* + +@Serializable +public enum class EventType(public val value: kotlin.String) { + + @SerialName(value = "click") + Click("click"), + + @SerialName(value = "conversion") + Conversion("conversion"), + + @SerialName(value = "view") + View("view"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/insights/InsightEvent.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/insights/InsightEvent.kt new file mode 100644 index 0000000000..4e083a12ef --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/insights/InsightEvent.kt @@ -0,0 +1,48 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.insights + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Insights event. + * + * @param eventType + * @param eventName A user-defined string used to categorize events. + * @param index Name of the targeted index. + * @param userToken A user identifier. Depending if the user is logged-in or not, several strategies can be used from a sessionId to a technical identifier. You should always send pseudonymous or anonymous userTokens. + * @param timestamp Time of the event expressed in milliseconds since the Unix epoch. + * @param queryID Algolia queryID. This is required when an event is tied to a search. + * @param objectIDs An array of index objectID. Limited to 20 objects. An event can’t have both objectIDs and filters at the same time. + * @param filters An array of filters. Limited to 10 filters. An event can’t have both objectIDs and filters at the same time. + * @param positions Position of the click in the list of Algolia search results. This field is required if a queryID is provided. One position must be provided for each objectID. + */ +@Serializable +public data class InsightEvent( + + @SerialName(value = "eventType") val eventType: EventType, + + /** A user-defined string used to categorize events. */ + @SerialName(value = "eventName") val eventName: String, + + /** Name of the targeted index. */ + @SerialName(value = "index") val index: String, + + /** A user identifier. Depending if the user is logged-in or not, several strategies can be used from a sessionId to a technical identifier. You should always send pseudonymous or anonymous userTokens. */ + @SerialName(value = "userToken") val userToken: String, + + /** Time of the event expressed in milliseconds since the Unix epoch. */ + @SerialName(value = "timestamp") val timestamp: Long? = null, + + /** Algolia queryID. This is required when an event is tied to a search. */ + @SerialName(value = "queryID") val queryID: String? = null, + + /** An array of index objectID. Limited to 20 objects. An event can’t have both objectIDs and filters at the same time. */ + @SerialName(value = "objectIDs") val objectIDs: List? = null, + + /** An array of filters. Limited to 10 filters. An event can’t have both objectIDs and filters at the same time. */ + @SerialName(value = "filters") val filters: List? = null, + + /** Position of the click in the list of Algolia search results. This field is required if a queryID is provided. One position must be provided for each objectID. */ + @SerialName(value = "positions") val positions: List? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/insights/InsightEvents.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/insights/InsightEvents.kt new file mode 100644 index 0000000000..5108a8d5ea --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/insights/InsightEvents.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.insights + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Object containing the events sent. + * + * @param events Array of events sent. + */ +@Serializable +public data class InsightEvents( + + /** Array of events sent. */ + @SerialName(value = "events") val events: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/insights/PushEventsResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/insights/PushEventsResponse.kt new file mode 100644 index 0000000000..b09cae0462 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/insights/PushEventsResponse.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.insights + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * PushEventsResponse + * + * @param message A message confirming the event push. + */ +@Serializable +public data class PushEventsResponse( + + /** A message confirming the event push. */ + @SerialName(value = "message") val message: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/personalization/DeleteUserProfileResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/personalization/DeleteUserProfileResponse.kt new file mode 100644 index 0000000000..72932b3ea3 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/personalization/DeleteUserProfileResponse.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.personalization + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * DeleteUserProfileResponse + * + * @param userToken userToken representing the user for which to fetch the Personalization profile. + * @param deletedUntil A date until which the data can safely be considered as deleted for the given user. Any data received after the `deletedUntil` date will start building a new user profile. + */ +@Serializable +public data class DeleteUserProfileResponse( + + /** userToken representing the user for which to fetch the Personalization profile. */ + @SerialName(value = "userToken") val userToken: String, + + /** A date until which the data can safely be considered as deleted for the given user. Any data received after the `deletedUntil` date will start building a new user profile. */ + @SerialName(value = "deletedUntil") val deletedUntil: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/personalization/ErrorBase.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/personalization/ErrorBase.kt new file mode 100644 index 0000000000..1955ae3a52 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/personalization/ErrorBase.kt @@ -0,0 +1,46 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.personalization + +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Error. + * + * @param message + */ +@Serializable(ErrorBaseSerializer::class) +public data class ErrorBase( + + val message: String? = null, + + val additionalProperties: Map? = null, +) + +internal object ErrorBaseSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("ErrorBase") { + element("message") + } + + override fun deserialize(decoder: Decoder): ErrorBase { + val input = decoder.asJsonDecoder() + val tree = input.decodeJsonObject() + return ErrorBase( + message = tree["message"]?.let { input.json.decodeFromJsonElement(it) }, + additionalProperties = tree.filterKeys { it !in descriptor.elementNames }, + ) + } + + override fun serialize(encoder: Encoder, value: ErrorBase) { + val output = encoder.asJsonEncoder() + val json = buildJsonObject { + value.message?.let { put("message", output.json.encodeToJsonElement(it)) } + value.additionalProperties?.onEach { (key, element) -> put(key, element) } + } + (encoder as JsonEncoder).encodeJsonElement(json) + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/personalization/EventScoring.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/personalization/EventScoring.kt new file mode 100644 index 0000000000..d17b83b522 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/personalization/EventScoring.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.personalization + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * EventScoring + * + * @param score The score for the event. + * @param eventName The name of the event. + * @param eventType The type of the event. + */ +@Serializable +public data class EventScoring( + + /** The score for the event. */ + @SerialName(value = "score") val score: Int, + + /** The name of the event. */ + @SerialName(value = "eventName") val eventName: String, + + /** The type of the event. */ + @SerialName(value = "eventType") val eventType: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/personalization/FacetScoring.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/personalization/FacetScoring.kt new file mode 100644 index 0000000000..ab56c807f6 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/personalization/FacetScoring.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.personalization + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * FacetScoring + * + * @param score The score for the event. + * @param facetName The name of the facet. + */ +@Serializable +public data class FacetScoring( + + /** The score for the event. */ + @SerialName(value = "score") val score: Int, + + /** The name of the facet. */ + @SerialName(value = "facetName") val facetName: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/personalization/GetUserTokenResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/personalization/GetUserTokenResponse.kt new file mode 100644 index 0000000000..83f5af96f1 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/personalization/GetUserTokenResponse.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.personalization + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * GetUserTokenResponse + * + * @param userToken userToken representing the user for which to fetch the Personalization profile. + * @param lastEventAt Date of last event update. (ISO-8601 format). + * @param scores The userToken scores. + */ +@Serializable +public data class GetUserTokenResponse( + + /** userToken representing the user for which to fetch the Personalization profile. */ + @SerialName(value = "userToken") val userToken: String, + + /** Date of last event update. (ISO-8601 format). */ + @SerialName(value = "lastEventAt") val lastEventAt: String, + + /** The userToken scores. */ + @SerialName(value = "scores") val scores: JsonObject, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/personalization/PersonalizationStrategyParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/personalization/PersonalizationStrategyParams.kt new file mode 100644 index 0000000000..c10139956a --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/personalization/PersonalizationStrategyParams.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.personalization + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * PersonalizationStrategyParams + * + * @param eventScoring Scores associated with the events. + * @param facetScoring Scores associated with the facets. + * @param personalizationImpact The impact that personalization has on search results: a number between 0 (personalization disabled) and 100 (personalization fully enabled). + */ +@Serializable +public data class PersonalizationStrategyParams( + + /** Scores associated with the events. */ + @SerialName(value = "eventScoring") val eventScoring: List, + + /** Scores associated with the facets. */ + @SerialName(value = "facetScoring") val facetScoring: List, + + /** The impact that personalization has on search results: a number between 0 (personalization disabled) and 100 (personalization fully enabled). */ + @SerialName(value = "personalizationImpact") val personalizationImpact: Int, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/personalization/SetPersonalizationStrategyResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/personalization/SetPersonalizationStrategyResponse.kt new file mode 100644 index 0000000000..82da4bd3dc --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/personalization/SetPersonalizationStrategyResponse.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.personalization + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SetPersonalizationStrategyResponse + * + * @param message A message confirming the strategy update. + */ +@Serializable +public data class SetPersonalizationStrategyResponse( + + /** A message confirming the strategy update. */ + @SerialName(value = "message") val message: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ActivateModelInstanceResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ActivateModelInstanceResponse.kt new file mode 100644 index 0000000000..cebd9f1492 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ActivateModelInstanceResponse.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * ActivateModelInstanceResponse + * + * @param modelID The ID of the model. + * @param updatedAt Date of last update (ISO-8601 format). + */ +@Serializable +public data class ActivateModelInstanceResponse( + + /** The ID of the model. */ + @SerialName(value = "modelID") val modelID: String, + + /** Date of last update (ISO-8601 format). */ + @SerialName(value = "updatedAt") val updatedAt: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ActivateModelParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ActivateModelParams.kt new file mode 100644 index 0000000000..7ba8ad3f90 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ActivateModelParams.kt @@ -0,0 +1,31 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * ActivateModelParams + * + * @param type + * @param name The model’s instance name. + * @param sourceID The data source ID, as returned by the (external) sources API. + * @param index The index name. + * @param modelAttributes + */ +@Serializable +public data class ActivateModelParams( + + @SerialName(value = "type") val type: ModelsToRetrieve, + + /** The model’s instance name. */ + @SerialName(value = "name") val name: String, + + /** The data source ID, as returned by the (external) sources API. */ + @SerialName(value = "sourceID") val sourceID: String, + + /** The index name. */ + @SerialName(value = "index") val index: String, + + @SerialName(value = "modelAttributes") val modelAttributes: List? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/Affinity.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/Affinity.kt new file mode 100644 index 0000000000..77b9d9c734 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/Affinity.kt @@ -0,0 +1,22 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Affinity + * + * @param name + * @param `value` + * @param probability + */ +@Serializable +public data class Affinity( + + @SerialName(value = "name") val name: String, + + @SerialName(value = "value") val `value`: PredictionAffinityValue, + + @SerialName(value = "probability") val probability: Double, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/AllParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/AllParams.kt new file mode 100644 index 0000000000..44052f3906 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/AllParams.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * AllParams + * + * @param modelsToRetrieve + * @param typesToRetrieve + */ +@Serializable +public data class AllParams( + + @SerialName(value = "modelsToRetrieve") val modelsToRetrieve: List? = null, + + @SerialName(value = "typesToRetrieve") val typesToRetrieve: List? = null, +) : Params diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/AllUpdateSegmentParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/AllUpdateSegmentParams.kt new file mode 100644 index 0000000000..be853f4120 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/AllUpdateSegmentParams.kt @@ -0,0 +1,20 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * AllUpdateSegmentParams + * + * @param name The name or description of the segment. + * @param conditions + */ +@Serializable +public data class AllUpdateSegmentParams( + + /** The name or description of the segment. */ + @SerialName(value = "name") val name: String? = null, + + @SerialName(value = "conditions") val conditions: SegmentParentConditions? = null, +) : UpdateSegmentParams diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/CompatibleSources.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/CompatibleSources.kt new file mode 100644 index 0000000000..02da4cc015 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/CompatibleSources.kt @@ -0,0 +1,13 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* + +@Serializable +public enum class CompatibleSources(public val value: kotlin.String) { + + @SerialName(value = "bigquery") + Bigquery("bigquery"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/CreateSegmentParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/CreateSegmentParams.kt new file mode 100644 index 0000000000..593a57e150 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/CreateSegmentParams.kt @@ -0,0 +1,20 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * CreateSegmentParams + * + * @param name The name or description of the segment. + * @param conditions + */ +@Serializable +public data class CreateSegmentParams( + + /** The name or description of the segment. */ + @SerialName(value = "name") val name: String, + + @SerialName(value = "conditions") val conditions: SegmentParentConditions, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/CreateSegmentResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/CreateSegmentResponse.kt new file mode 100644 index 0000000000..4e65221b08 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/CreateSegmentResponse.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * CreateSegmentResponse + * + * @param segmentID The ID of the segment. + * @param updatedAt The date and time at which the segment was updated (RFC3339). + * @param size The approximate number of users that matched the segment conditions when it was created, last updated, or when model inference last ran. + */ +@Serializable +public data class CreateSegmentResponse( + + /** The ID of the segment. */ + @SerialName(value = "segmentID") val segmentID: String, + + /** The date and time at which the segment was updated (RFC3339). */ + @SerialName(value = "updatedAt") val updatedAt: String, + + /** The approximate number of users that matched the segment conditions when it was created, last updated, or when model inference last ran. */ + @SerialName(value = "size") val size: Double? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/DeleteModelInstanceResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/DeleteModelInstanceResponse.kt new file mode 100644 index 0000000000..cbfd2f99ae --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/DeleteModelInstanceResponse.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * DeleteModelInstanceResponse + * + * @param modelID The ID of the model. + * @param deletedUntil The date until which you can safely consider the data as being deleted. + */ +@Serializable +public data class DeleteModelInstanceResponse( + + /** The ID of the model. */ + @SerialName(value = "modelID") val modelID: String, + + /** The date until which you can safely consider the data as being deleted. */ + @SerialName(value = "deletedUntil") val deletedUntil: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/DeleteSegmentResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/DeleteSegmentResponse.kt new file mode 100644 index 0000000000..607f510167 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/DeleteSegmentResponse.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * DeleteSegmentResponse + * + * @param segmentID The ID of the segment. + * @param deletedUntil The date and time at which the segment will be re-ingested. + */ +@Serializable +public data class DeleteSegmentResponse( + + /** The ID of the segment. */ + @SerialName(value = "segmentID") val segmentID: String, + + /** The date and time at which the segment will be re-ingested. */ + @SerialName(value = "deletedUntil") val deletedUntil: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/DeleteUserProfileResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/DeleteUserProfileResponse.kt new file mode 100644 index 0000000000..0f8ea80395 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/DeleteUserProfileResponse.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * DeleteUserProfileResponse + * + * @param user The ID of the user that was deleted. + * @param deletedUntil The time the same user ID will be imported again when the data is ingested. + */ +@Serializable +public data class DeleteUserProfileResponse( + + /** The ID of the user that was deleted. */ + @SerialName(value = "user") val user: String, + + /** The time the same user ID will be imported again when the data is ingested. */ + @SerialName(value = "deletedUntil") val deletedUntil: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/Error.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/Error.kt new file mode 100644 index 0000000000..ad667f8f81 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/Error.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The error when the model is not available. + * + * @param error + */ +@Serializable +public data class Error( + + @SerialName(value = "error") val error: String, +) : PredictionsAffinities, PredictionsOrderValue, PredictionsFunnelStage diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ErrorBase.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ErrorBase.kt new file mode 100644 index 0000000000..1ed4d9d70f --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ErrorBase.kt @@ -0,0 +1,46 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Error. + * + * @param message + */ +@Serializable(ErrorBaseSerializer::class) +public data class ErrorBase( + + val message: String? = null, + + val additionalProperties: Map? = null, +) + +internal object ErrorBaseSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("ErrorBase") { + element("message") + } + + override fun deserialize(decoder: Decoder): ErrorBase { + val input = decoder.asJsonDecoder() + val tree = input.decodeJsonObject() + return ErrorBase( + message = tree["message"]?.let { input.json.decodeFromJsonElement(it) }, + additionalProperties = tree.filterKeys { it !in descriptor.elementNames }, + ) + } + + override fun serialize(encoder: Encoder, value: ErrorBase) { + val output = encoder.asJsonEncoder() + val json = buildJsonObject { + value.message?.let { put("message", output.json.encodeToJsonElement(it)) } + value.additionalProperties?.onEach { (key, element) -> put(key, element) } + } + (encoder as JsonEncoder).encodeJsonElement(json) + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/FetchAllUserProfilesParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/FetchAllUserProfilesParams.kt new file mode 100644 index 0000000000..9b7747c429 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/FetchAllUserProfilesParams.kt @@ -0,0 +1,147 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * FetchAllUserProfilesParams + */ +@Serializable(FetchAllUserProfilesParamsSerializer::class) +public sealed interface FetchAllUserProfilesParams { + + public companion object { + + /** + * LimitParam + * + * @param limit + */ + public fun LimitParam( + limit: Int? = null, + ): LimitParam = com.algolia.client.model.predict.LimitParam( + limit = limit, + ) + + /** + * ModelsToRetrieveParam + * + * @param modelsToRetrieve + */ + public fun ModelsToRetrieveParam( + modelsToRetrieve: List? = null, + ): ModelsToRetrieveParam = com.algolia.client.model.predict.ModelsToRetrieveParam( + modelsToRetrieve = modelsToRetrieve, + ) + + /** + * NextPageTokenParam + * + * @param nextPageToken The token is used to navigate forward in the user list. To navigate from the current user list to the next page, the API generates the next page token and it sends the token in the response, beside the current user list. NOTE: This body param cannot be used with `previousPageToken` at the same time. + */ + public fun NextPageTokenParam( + nextPageToken: String? = null, + ): NextPageTokenParam = com.algolia.client.model.predict.NextPageTokenParam( + nextPageToken = nextPageToken, + ) + + /** + * PreviousPageTokenParam + * + * @param previousPageToken The token is used to navigate backward in the user list. To navigate from the current user list to the previous page, the API generates the previous page token and it sends the token in the response, beside the current user list. NOTE: This body param cannot be used with `nextPageToken` at the same time. + */ + public fun PreviousPageTokenParam( + previousPageToken: String? = null, + ): PreviousPageTokenParam = com.algolia.client.model.predict.PreviousPageTokenParam( + previousPageToken = previousPageToken, + ) + + /** + * TypesToRetrieveParam + * + * @param typesToRetrieve + */ + public fun TypesToRetrieveParam( + typesToRetrieve: List? = null, + ): TypesToRetrieveParam = com.algolia.client.model.predict.TypesToRetrieveParam( + typesToRetrieve = typesToRetrieve, + ) + } +} + +internal class FetchAllUserProfilesParamsSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("FetchAllUserProfilesParams") + + override fun serialize(encoder: Encoder, value: FetchAllUserProfilesParams) { + when (value) { + is LimitParam -> LimitParam.serializer().serialize(encoder, value) + is ModelsToRetrieveParam -> ModelsToRetrieveParam.serializer().serialize(encoder, value) + is NextPageTokenParam -> NextPageTokenParam.serializer().serialize(encoder, value) + is PreviousPageTokenParam -> PreviousPageTokenParam.serializer().serialize(encoder, value) + is TypesToRetrieveParam -> TypesToRetrieveParam.serializer().serialize(encoder, value) + } + } + + override fun deserialize(decoder: Decoder): FetchAllUserProfilesParams { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize LimitParam + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize LimitParam (error: ${e.message})") + } + } + + // deserialize ModelsToRetrieveParam + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize ModelsToRetrieveParam (error: ${e.message})") + } + } + + // deserialize NextPageTokenParam + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize NextPageTokenParam (error: ${e.message})") + } + } + + // deserialize PreviousPageTokenParam + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize PreviousPageTokenParam (error: ${e.message})") + } + } + + // deserialize TypesToRetrieveParam + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize TypesToRetrieveParam (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/FetchAllUserProfilesResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/FetchAllUserProfilesResponse.kt new file mode 100644 index 0000000000..51abcce46c --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/FetchAllUserProfilesResponse.kt @@ -0,0 +1,24 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * FetchAllUserProfilesResponse + * + * @param users + * @param previousPageToken The token is used to navigate backward in the user list. To navigate from the current user list to the previous page, the API generates the previous page token and it sends the token in the response, beside the current user list. NOTE: This body param cannot be used with `nextPageToken` at the same time. + * @param nextPageToken The token is used to navigate forward in the user list. To navigate from the current user list to the next page, the API generates the next page token and it sends the token in the response, beside the current user list. NOTE: This body param cannot be used with `previousPageToken` at the same time. + */ +@Serializable +public data class FetchAllUserProfilesResponse( + + @SerialName(value = "users") val users: List, + + /** The token is used to navigate backward in the user list. To navigate from the current user list to the previous page, the API generates the previous page token and it sends the token in the response, beside the current user list. NOTE: This body param cannot be used with `nextPageToken` at the same time. */ + @SerialName(value = "previousPageToken") val previousPageToken: String? = null, + + /** The token is used to navigate forward in the user list. To navigate from the current user list to the next page, the API generates the next page token and it sends the token in the response, beside the current user list. NOTE: This body param cannot be used with `previousPageToken` at the same time. */ + @SerialName(value = "nextPageToken") val nextPageToken: String? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/FunnelStage.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/FunnelStage.kt new file mode 100644 index 0000000000..097ae5766b --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/FunnelStage.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * FunnelStage + * + * @param name + * @param probability + */ +@Serializable +public data class FunnelStage( + + @SerialName(value = "name") val name: String, + + @SerialName(value = "probability") val probability: Double, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/GetAvailableModelTypesResponseInner.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/GetAvailableModelTypesResponseInner.kt new file mode 100644 index 0000000000..f4c6d148d7 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/GetAvailableModelTypesResponseInner.kt @@ -0,0 +1,27 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * GetAvailableModelTypesResponseInner + * + * @param name Name of the model. + * @param type Description of the model. + * @param compatibleSources + * @param dataRequirements + */ +@Serializable +public data class GetAvailableModelTypesResponseInner( + + /** Name of the model. */ + @SerialName(value = "name") val name: String, + + /** Description of the model. */ + @SerialName(value = "type") val type: String, + + @SerialName(value = "compatibleSources") val compatibleSources: List, + + @SerialName(value = "dataRequirements") val dataRequirements: GetAvailableModelTypesResponseInnerDataRequirements, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/GetAvailableModelTypesResponseInnerDataRequirements.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/GetAvailableModelTypesResponseInnerDataRequirements.kt new file mode 100644 index 0000000000..a578d746d5 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/GetAvailableModelTypesResponseInnerDataRequirements.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * GetAvailableModelTypesResponseInnerDataRequirements + * + * @param minUsers Minimum number of users required for this model. + * @param minDays Minimum number of days model needs to run. + */ +@Serializable +public data class GetAvailableModelTypesResponseInnerDataRequirements( + + /** Minimum number of users required for this model. */ + @SerialName(value = "minUsers") val minUsers: Int, + + /** Minimum number of days model needs to run. */ + @SerialName(value = "minDays") val minDays: Int, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/GetModelInstanceConfigStatus.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/GetModelInstanceConfigStatus.kt new file mode 100644 index 0000000000..50492ce531 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/GetModelInstanceConfigStatus.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* + +/** + * `pending` - model has just been created and the pipelines are being set up for the first train & inference. \\ `active` - model is running and generating predictions. \\ `invalid` - model has failed training (ex. can’t retrieve data from source). An additional `errorMessage` field will be set for this status. \\ `inactive` - model has been deactivated from the dashboard. Pipelines still exist but they are not currently running. + */ +@Serializable +public enum class GetModelInstanceConfigStatus(public val value: kotlin.String) { + + @SerialName(value = "pending") + Pending("pending"), + + @SerialName(value = "active") + Active("active"), + + @SerialName(value = "invalid") + Invalid("invalid"), + + @SerialName(value = "inactive") + Inactive("inactive"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/GetModelMetricsResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/GetModelMetricsResponse.kt new file mode 100644 index 0000000000..d3fac1faa0 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/GetModelMetricsResponse.kt @@ -0,0 +1,20 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * GetModelMetricsResponse + * + * @param modelID The ID of the model. + * @param metrics + */ +@Serializable +public data class GetModelMetricsResponse( + + /** The ID of the model. */ + @SerialName(value = "modelID") val modelID: String, + + @SerialName(value = "metrics") val metrics: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/GetSegmentUsersResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/GetSegmentUsersResponse.kt new file mode 100644 index 0000000000..16ac8041ad --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/GetSegmentUsersResponse.kt @@ -0,0 +1,28 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * GetSegmentUsersResponse + * + * @param segmentID The ID of the segment. + * @param users + * @param previousPageToken The token is used to navigate backward in the user list. To navigate from the current user list to the previous page, the API generates the previous page token and it sends the token in the response, beside the current user list. NOTE: This body param cannot be used with `nextPageToken` at the same time. + * @param nextPageToken The token is used to navigate forward in the user list. To navigate from the current user list to the next page, the API generates the next page token and it sends the token in the response, beside the current user list. NOTE: This body param cannot be used with `previousPageToken` at the same time. + */ +@Serializable +public data class GetSegmentUsersResponse( + + /** The ID of the segment. */ + @SerialName(value = "segmentID") val segmentID: String, + + @SerialName(value = "users") val users: List, + + /** The token is used to navigate backward in the user list. To navigate from the current user list to the previous page, the API generates the previous page token and it sends the token in the response, beside the current user list. NOTE: This body param cannot be used with `nextPageToken` at the same time. */ + @SerialName(value = "previousPageToken") val previousPageToken: String? = null, + + /** The token is used to navigate forward in the user list. To navigate from the current user list to the next page, the API generates the next page token and it sends the token in the response, beside the current user list. NOTE: This body param cannot be used with `previousPageToken` at the same time. */ + @SerialName(value = "nextPageToken") val nextPageToken: String? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/LimitParam.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/LimitParam.kt new file mode 100644 index 0000000000..65f0b21948 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/LimitParam.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * LimitParam + * + * @param limit + */ +@Serializable +public data class LimitParam( + + @SerialName(value = "limit") val limit: Int? = null, +) : FetchAllUserProfilesParams diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ModelAttributes.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ModelAttributes.kt new file mode 100644 index 0000000000..da5aac4f42 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ModelAttributes.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * ModelAttributes + * + * @param name + * @param values + */ +@Serializable +public data class ModelAttributes( + + @SerialName(value = "name") val name: String, + + @SerialName(value = "values") val values: List? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ModelInstance.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ModelInstance.kt new file mode 100644 index 0000000000..ab49f4c6c6 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ModelInstance.kt @@ -0,0 +1,47 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * ModelInstance + * + * @param modelID ID of the model. + * @param name Name of model instance. + * @param type + * @param sourceID + * @param index + * @param lastTrained The date and time this model instance was last trained. + * @param lastInference The date and time this model instance generated its last inference. + * @param modelStatus + * @param modelAttributes + * @param errorMessage + */ +@Serializable +public data class ModelInstance( + + /** ID of the model. */ + @SerialName(value = "modelID") val modelID: String, + + /** Name of model instance. */ + @SerialName(value = "name") val name: String, + + @SerialName(value = "type") val type: ModelsToRetrieve, + + @SerialName(value = "sourceID") val sourceID: String, + + @SerialName(value = "index") val index: String, + + /** The date and time this model instance was last trained. */ + @SerialName(value = "lastTrained") val lastTrained: String, + + /** The date and time this model instance generated its last inference. */ + @SerialName(value = "lastInference") val lastInference: String, + + @SerialName(value = "modelStatus") val modelStatus: GetModelInstanceConfigStatus, + + @SerialName(value = "modelAttributes") val modelAttributes: List? = null, + + @SerialName(value = "errorMessage") val errorMessage: String? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ModelMetrics.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ModelMetrics.kt new file mode 100644 index 0000000000..a2a61457e1 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ModelMetrics.kt @@ -0,0 +1,32 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * ModelMetrics + * + * @param precision + * @param recall + * @param mrr + * @param coverage + * @param f1Score + * @param updatedAt Date of last update (ISO-8601 format). + */ +@Serializable +public data class ModelMetrics( + + @SerialName(value = "precision") val precision: Double? = null, + + @SerialName(value = "recall") val recall: Double? = null, + + @SerialName(value = "mrr") val mrr: Double? = null, + + @SerialName(value = "coverage") val coverage: Double? = null, + + @SerialName(value = "f1_score") val f1Score: Double? = null, + + /** Date of last update (ISO-8601 format). */ + @SerialName(value = "updatedAt") val updatedAt: String? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ModelStatus.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ModelStatus.kt new file mode 100644 index 0000000000..f316d22cfa --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ModelStatus.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* + +/** + * `active` - model is running and generating predictions. The active value is allowed only if the current status of the model is `inactive`. \\ `inactive` - model training and inference have been paused. The inactive value is allowed only if the current status of the model is `active`. + */ +@Serializable +public enum class ModelStatus(public val value: kotlin.String) { + + @SerialName(value = "active") + Active("active"), + + @SerialName(value = "inactive") + Inactive("inactive"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ModelsToRetrieve.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ModelsToRetrieve.kt new file mode 100644 index 0000000000..318989a752 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ModelsToRetrieve.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* + +@Serializable +public enum class ModelsToRetrieve(public val value: kotlin.String) { + + @SerialName(value = "funnel_stage") + FunnelStage("funnel_stage"), + + @SerialName(value = "order_value") + OrderValue("order_value"), + + @SerialName(value = "affinities") + Affinities("affinities"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ModelsToRetrieveParam.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ModelsToRetrieveParam.kt new file mode 100644 index 0000000000..95bd6f5924 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/ModelsToRetrieveParam.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * ModelsToRetrieveParam + * + * @param modelsToRetrieve + */ +@Serializable +public data class ModelsToRetrieveParam( + + @SerialName(value = "modelsToRetrieve") val modelsToRetrieve: List? = null, +) : FetchAllUserProfilesParams, Params diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/NextPageTokenParam.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/NextPageTokenParam.kt new file mode 100644 index 0000000000..78000b475f --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/NextPageTokenParam.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * NextPageTokenParam + * + * @param nextPageToken The token is used to navigate forward in the user list. To navigate from the current user list to the next page, the API generates the next page token and it sends the token in the response, beside the current user list. NOTE: This body param cannot be used with `previousPageToken` at the same time. + */ +@Serializable +public data class NextPageTokenParam( + + /** The token is used to navigate forward in the user list. To navigate from the current user list to the next page, the API generates the next page token and it sends the token in the response, beside the current user list. NOTE: This body param cannot be used with `previousPageToken` at the same time. */ + @SerialName(value = "nextPageToken") val nextPageToken: String? = null, +) : FetchAllUserProfilesParams diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/Params.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/Params.kt new file mode 100644 index 0000000000..03e3644dcd --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/Params.kt @@ -0,0 +1,106 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Params + */ +@Serializable(ParamsSerializer::class) +public sealed interface Params { + + public companion object { + + /** + * AllParams + * + * @param modelsToRetrieve + * @param typesToRetrieve + */ + public fun AllParams( + modelsToRetrieve: List? = null, + typesToRetrieve: List? = null, + ): AllParams = com.algolia.client.model.predict.AllParams( + modelsToRetrieve = modelsToRetrieve, + typesToRetrieve = typesToRetrieve, + ) + + /** + * ModelsToRetrieveParam + * + * @param modelsToRetrieve + */ + public fun ModelsToRetrieveParam( + modelsToRetrieve: List? = null, + ): ModelsToRetrieveParam = com.algolia.client.model.predict.ModelsToRetrieveParam( + modelsToRetrieve = modelsToRetrieve, + ) + + /** + * TypesToRetrieveParam + * + * @param typesToRetrieve + */ + public fun TypesToRetrieveParam( + typesToRetrieve: List? = null, + ): TypesToRetrieveParam = com.algolia.client.model.predict.TypesToRetrieveParam( + typesToRetrieve = typesToRetrieve, + ) + } +} + +internal class ParamsSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("Params") + + override fun serialize(encoder: Encoder, value: Params) { + when (value) { + is AllParams -> AllParams.serializer().serialize(encoder, value) + is ModelsToRetrieveParam -> ModelsToRetrieveParam.serializer().serialize(encoder, value) + is TypesToRetrieveParam -> TypesToRetrieveParam.serializer().serialize(encoder, value) + } + } + + override fun deserialize(decoder: Decoder): Params { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize AllParams + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize AllParams (error: ${e.message})") + } + } + + // deserialize ModelsToRetrieveParam + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize ModelsToRetrieveParam (error: ${e.message})") + } + } + + // deserialize TypesToRetrieveParam + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize TypesToRetrieveParam (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PredictionAffinityValue.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PredictionAffinityValue.kt new file mode 100644 index 0000000000..395a59c220 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PredictionAffinityValue.kt @@ -0,0 +1,106 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * PredictionAffinityValue + */ +@Serializable(PredictionAffinityValueSerializer::class) +public sealed interface PredictionAffinityValue { + + public data class BooleanWrapper(val value: Boolean) : PredictionAffinityValue + + public data class DoubleWrapper(val value: Double) : PredictionAffinityValue + + public data class StringWrapper(val value: String) : PredictionAffinityValue + + public companion object { + + /** + * PredictionAffinityValue as Boolean + * + */ + public fun Boolean( + value: Boolean, + ): BooleanWrapper = BooleanWrapper( + value = value, + ) + + /** + * PredictionAffinityValue as Double + * + */ + public fun Number( + value: Double, + ): DoubleWrapper = DoubleWrapper( + value = value, + ) + + /** + * PredictionAffinityValue as String + * + */ + public fun String( + value: String, + ): StringWrapper = StringWrapper( + value = value, + ) + } +} + +internal class PredictionAffinityValueSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("PredictionAffinityValue") + + override fun serialize(encoder: Encoder, value: PredictionAffinityValue) { + when (value) { + is PredictionAffinityValue.BooleanWrapper -> Boolean.serializer().serialize(encoder, value.value) + is PredictionAffinityValue.DoubleWrapper -> Double.serializer().serialize(encoder, value.value) + is PredictionAffinityValue.StringWrapper -> String.serializer().serialize(encoder, value.value) + } + } + + override fun deserialize(decoder: Decoder): PredictionAffinityValue { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize Boolean + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize Boolean (error: ${e.message})") + } + } + + // deserialize Double + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize Double (error: ${e.message})") + } + } + + // deserialize String + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize String (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/Predictions.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/Predictions.kt new file mode 100644 index 0000000000..7dd4bf392a --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/Predictions.kt @@ -0,0 +1,22 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Predictions + * + * @param funnelStage + * @param orderValue + * @param affinities + */ +@Serializable +public data class Predictions( + + @SerialName(value = "funnel_stage") val funnelStage: PredictionsFunnelStage? = null, + + @SerialName(value = "order_value") val orderValue: PredictionsOrderValue? = null, + + @SerialName(value = "affinities") val affinities: PredictionsAffinities? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PredictionsAffinities.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PredictionsAffinities.kt new file mode 100644 index 0000000000..28e066f4eb --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PredictionsAffinities.kt @@ -0,0 +1,84 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * PredictionsAffinities + */ +@Serializable(PredictionsAffinitiesSerializer::class) +public sealed interface PredictionsAffinities { + + public companion object { + + /** + * The error when the model is not available. + * + * @param error + */ + public fun Error( + error: String, + ): Error = com.algolia.client.model.predict.Error( + error = error, + ) + + /** + * Prediction for the **affinities** model. + * + * @param `value` + * @param lastUpdatedAt + */ + public fun PredictionsAffinitiesSuccess( + `value`: List, + lastUpdatedAt: String, + ): PredictionsAffinitiesSuccess = com.algolia.client.model.predict.PredictionsAffinitiesSuccess( + `value` = `value`, + lastUpdatedAt = lastUpdatedAt, + ) + } +} + +internal class PredictionsAffinitiesSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("PredictionsAffinities") + + override fun serialize(encoder: Encoder, value: PredictionsAffinities) { + when (value) { + is Error -> Error.serializer().serialize(encoder, value) + is PredictionsAffinitiesSuccess -> PredictionsAffinitiesSuccess.serializer().serialize(encoder, value) + } + } + + override fun deserialize(decoder: Decoder): PredictionsAffinities { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize Error + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize Error (error: ${e.message})") + } + } + + // deserialize PredictionsAffinitiesSuccess + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize PredictionsAffinitiesSuccess (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PredictionsAffinitiesSuccess.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PredictionsAffinitiesSuccess.kt new file mode 100644 index 0000000000..d4307cf833 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PredictionsAffinitiesSuccess.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Prediction for the **affinities** model. + * + * @param `value` + * @param lastUpdatedAt + */ +@Serializable +public data class PredictionsAffinitiesSuccess( + + @SerialName(value = "value") val `value`: List, + + @SerialName(value = "lastUpdatedAt") val lastUpdatedAt: String, +) : PredictionsAffinities diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PredictionsFunnelStage.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PredictionsFunnelStage.kt new file mode 100644 index 0000000000..51a39dd7a9 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PredictionsFunnelStage.kt @@ -0,0 +1,84 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * PredictionsFunnelStage + */ +@Serializable(PredictionsFunnelStageSerializer::class) +public sealed interface PredictionsFunnelStage { + + public companion object { + + /** + * The error when the model is not available. + * + * @param error + */ + public fun Error( + error: String, + ): Error = com.algolia.client.model.predict.Error( + error = error, + ) + + /** + * Prediction for the **funnel_stage** model. + * + * @param `value` + * @param lastUpdatedAt + */ + public fun PredictionsFunnelStageSuccess( + `value`: List, + lastUpdatedAt: String, + ): PredictionsFunnelStageSuccess = com.algolia.client.model.predict.PredictionsFunnelStageSuccess( + `value` = `value`, + lastUpdatedAt = lastUpdatedAt, + ) + } +} + +internal class PredictionsFunnelStageSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("PredictionsFunnelStage") + + override fun serialize(encoder: Encoder, value: PredictionsFunnelStage) { + when (value) { + is Error -> Error.serializer().serialize(encoder, value) + is PredictionsFunnelStageSuccess -> PredictionsFunnelStageSuccess.serializer().serialize(encoder, value) + } + } + + override fun deserialize(decoder: Decoder): PredictionsFunnelStage { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize Error + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize Error (error: ${e.message})") + } + } + + // deserialize PredictionsFunnelStageSuccess + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize PredictionsFunnelStageSuccess (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PredictionsFunnelStageSuccess.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PredictionsFunnelStageSuccess.kt new file mode 100644 index 0000000000..f66d4b5183 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PredictionsFunnelStageSuccess.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Prediction for the **funnel_stage** model. + * + * @param `value` + * @param lastUpdatedAt + */ +@Serializable +public data class PredictionsFunnelStageSuccess( + + @SerialName(value = "value") val `value`: List, + + @SerialName(value = "lastUpdatedAt") val lastUpdatedAt: String, +) : PredictionsFunnelStage diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PredictionsOrderValue.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PredictionsOrderValue.kt new file mode 100644 index 0000000000..6b8a2ac987 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PredictionsOrderValue.kt @@ -0,0 +1,84 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * PredictionsOrderValue + */ +@Serializable(PredictionsOrderValueSerializer::class) +public sealed interface PredictionsOrderValue { + + public companion object { + + /** + * The error when the model is not available. + * + * @param error + */ + public fun Error( + error: String, + ): Error = com.algolia.client.model.predict.Error( + error = error, + ) + + /** + * Prediction for the **order_value** model. + * + * @param `value` + * @param lastUpdatedAt + */ + public fun PredictionsOrderValueSuccess( + `value`: Double, + lastUpdatedAt: String, + ): PredictionsOrderValueSuccess = com.algolia.client.model.predict.PredictionsOrderValueSuccess( + `value` = `value`, + lastUpdatedAt = lastUpdatedAt, + ) + } +} + +internal class PredictionsOrderValueSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("PredictionsOrderValue") + + override fun serialize(encoder: Encoder, value: PredictionsOrderValue) { + when (value) { + is Error -> Error.serializer().serialize(encoder, value) + is PredictionsOrderValueSuccess -> PredictionsOrderValueSuccess.serializer().serialize(encoder, value) + } + } + + override fun deserialize(decoder: Decoder): PredictionsOrderValue { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize Error + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize Error (error: ${e.message})") + } + } + + // deserialize PredictionsOrderValueSuccess + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize PredictionsOrderValueSuccess (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PredictionsOrderValueSuccess.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PredictionsOrderValueSuccess.kt new file mode 100644 index 0000000000..fde097f67f --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PredictionsOrderValueSuccess.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Prediction for the **order_value** model. + * + * @param `value` + * @param lastUpdatedAt + */ +@Serializable +public data class PredictionsOrderValueSuccess( + + @SerialName(value = "value") val `value`: Double, + + @SerialName(value = "lastUpdatedAt") val lastUpdatedAt: String, +) : PredictionsOrderValue diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PreviousPageTokenParam.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PreviousPageTokenParam.kt new file mode 100644 index 0000000000..344e49ff7e --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/PreviousPageTokenParam.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * PreviousPageTokenParam + * + * @param previousPageToken The token is used to navigate backward in the user list. To navigate from the current user list to the previous page, the API generates the previous page token and it sends the token in the response, beside the current user list. NOTE: This body param cannot be used with `nextPageToken` at the same time. + */ +@Serializable +public data class PreviousPageTokenParam( + + /** The token is used to navigate backward in the user list. To navigate from the current user list to the previous page, the API generates the previous page token and it sends the token in the response, beside the current user list. NOTE: This body param cannot be used with `nextPageToken` at the same time. */ + @SerialName(value = "previousPageToken") val previousPageToken: String? = null, +) : FetchAllUserProfilesParams diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/Properties.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/Properties.kt new file mode 100644 index 0000000000..e2446604fa --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/Properties.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Properties for the user profile. + * + * @param raw Raw user properties (key-value pairs). + * @param computed Computed user properties (key-value pairs). + * @param custom Custom user properties (key-value pairs). + */ +@Serializable +public data class Properties( + + /** Raw user properties (key-value pairs). */ + @SerialName(value = "raw") val raw: JsonObject? = null, + + /** Computed user properties (key-value pairs). */ + @SerialName(value = "computed") val computed: JsonObject? = null, + + /** Custom user properties (key-value pairs). */ + @SerialName(value = "custom") val custom: JsonObject? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/Segment.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/Segment.kt new file mode 100644 index 0000000000..65ecb3d7f7 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/Segment.kt @@ -0,0 +1,41 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Segment + * + * @param segmentID The ID of the segment. + * @param name The name of the segment. + * @param conditions + * @param size The approximate number of users that matched the segment conditions when it was created, last updated, or when model inference last ran. + * @param segmentStatus + * @param type + * @param lastUpdatedAt The date and time at which the segment was last updated (RFC3339). + * @param errorMessage + */ +@Serializable +public data class Segment( + + /** The ID of the segment. */ + @SerialName(value = "segmentID") val segmentID: String, + + /** The name of the segment. */ + @SerialName(value = "name") val name: String, + + @SerialName(value = "conditions") val conditions: SegmentParentConditions, + + /** The approximate number of users that matched the segment conditions when it was created, last updated, or when model inference last ran. */ + @SerialName(value = "size") val size: Double, + + @SerialName(value = "segmentStatus") val segmentStatus: SegmentStatus, + + @SerialName(value = "type") val type: SegmentType, + + /** The date and time at which the segment was last updated (RFC3339). */ + @SerialName(value = "lastUpdatedAt") val lastUpdatedAt: String, + + @SerialName(value = "errorMessage") val errorMessage: String? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentAffinityFilter.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentAffinityFilter.kt new file mode 100644 index 0000000000..c0f8a62fff --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentAffinityFilter.kt @@ -0,0 +1,22 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Filter for affinity model predictions. + * + * @param `operator` + * @param `value` + * @param probability + */ +@Serializable +public data class SegmentAffinityFilter( + + @SerialName(value = "operator") val `operator`: SegmentFilterOperatorNumerical, + + @SerialName(value = "value") val `value`: SegmentAffinityFilterValue, + + @SerialName(value = "probability") val probability: SegmentFilterProbability? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentAffinityFilterValue.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentAffinityFilterValue.kt new file mode 100644 index 0000000000..a9d8e57c4f --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentAffinityFilterValue.kt @@ -0,0 +1,129 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * SegmentAffinityFilterValue + */ +@Serializable(SegmentAffinityFilterValueSerializer::class) +public sealed interface SegmentAffinityFilterValue { + + public data class BooleanWrapper(val value: Boolean) : SegmentAffinityFilterValue + + public data class DoubleWrapper(val value: Double) : SegmentAffinityFilterValue + + public data class ListOfStringWrapper(val value: List) : SegmentAffinityFilterValue + + public data class StringWrapper(val value: String) : SegmentAffinityFilterValue + + public companion object { + + /** + * SegmentAffinityFilterValue as Boolean + * + */ + public fun Boolean( + value: Boolean, + ): BooleanWrapper = BooleanWrapper( + value = value, + ) + + /** + * SegmentAffinityFilterValue as Double + * + */ + public fun Number( + value: Double, + ): DoubleWrapper = DoubleWrapper( + value = value, + ) + + /** + * SegmentAffinityFilterValue as List + * + */ + public fun ListOfString( + value: List, + ): ListOfStringWrapper = ListOfStringWrapper( + value = value, + ) + + /** + * SegmentAffinityFilterValue as String + * + */ + public fun String( + value: String, + ): StringWrapper = StringWrapper( + value = value, + ) + } +} + +internal class SegmentAffinityFilterValueSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("SegmentAffinityFilterValue") + + override fun serialize(encoder: Encoder, value: SegmentAffinityFilterValue) { + when (value) { + is SegmentAffinityFilterValue.BooleanWrapper -> Boolean.serializer().serialize(encoder, value.value) + is SegmentAffinityFilterValue.DoubleWrapper -> Double.serializer().serialize(encoder, value.value) + is SegmentAffinityFilterValue.ListOfStringWrapper -> ListSerializer(String.serializer()).serialize(encoder, value.value) + is SegmentAffinityFilterValue.StringWrapper -> String.serializer().serialize(encoder, value.value) + } + } + + override fun deserialize(decoder: Decoder): SegmentAffinityFilterValue { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize Boolean + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize Boolean (error: ${e.message})") + } + } + + // deserialize Double + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize Double (error: ${e.message})") + } + } + + // deserialize List + if (tree is JsonArray) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize List (error: ${e.message})") + } + } + + // deserialize String + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize String (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentChildConditionOperands.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentChildConditionOperands.kt new file mode 100644 index 0000000000..c30c224e18 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentChildConditionOperands.kt @@ -0,0 +1,137 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * SegmentChildConditionOperands + */ +@Serializable(SegmentChildConditionOperandsSerializer::class) +public sealed interface SegmentChildConditionOperands { + + public companion object { + + /** + * Operand for affinity model predictions. + * + * @param name + * @param filters + */ + public fun SegmentOperandAffinity( + name: String, + filters: List, + ): SegmentOperandAffinity = com.algolia.client.model.predict.SegmentOperandAffinity( + name = name, + filters = filters, + ) + + /** + * Operand for funnel stage model predictions. + * + * @param name + * @param filters + */ + public fun SegmentOperandFunnelStage( + name: String, + filters: List, + ): SegmentOperandFunnelStage = com.algolia.client.model.predict.SegmentOperandFunnelStage( + name = name, + filters = filters, + ) + + /** + * Operand for order value model predictions. + * + * @param name + * @param filters + */ + public fun SegmentOperandOrderValue( + name: String, + filters: List, + ): SegmentOperandOrderValue = com.algolia.client.model.predict.SegmentOperandOrderValue( + name = name, + filters = filters, + ) + + /** + * Operand for user profile properties. + * + * @param name + * @param filters + */ + public fun SegmentOperandProperty( + name: String, + filters: List, + ): SegmentOperandProperty = com.algolia.client.model.predict.SegmentOperandProperty( + name = name, + filters = filters, + ) + } +} + +internal class SegmentChildConditionOperandsSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("SegmentChildConditionOperands") + + override fun serialize(encoder: Encoder, value: SegmentChildConditionOperands) { + when (value) { + is SegmentOperandAffinity -> SegmentOperandAffinity.serializer().serialize(encoder, value) + is SegmentOperandFunnelStage -> SegmentOperandFunnelStage.serializer().serialize(encoder, value) + is SegmentOperandOrderValue -> SegmentOperandOrderValue.serializer().serialize(encoder, value) + is SegmentOperandProperty -> SegmentOperandProperty.serializer().serialize(encoder, value) + } + } + + override fun deserialize(decoder: Decoder): SegmentChildConditionOperands { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize SegmentOperandAffinity + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize SegmentOperandAffinity (error: ${e.message})") + } + } + + // deserialize SegmentOperandFunnelStage + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize SegmentOperandFunnelStage (error: ${e.message})") + } + } + + // deserialize SegmentOperandOrderValue + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize SegmentOperandOrderValue (error: ${e.message})") + } + } + + // deserialize SegmentOperandProperty + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize SegmentOperandProperty (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentChildConditions.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentChildConditions.kt new file mode 100644 index 0000000000..fc347fd01f --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentChildConditions.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Nested segment conditions that only contain operands. + * + * @param `operator` + * @param operands + */ +@Serializable +public data class SegmentChildConditions( + + @SerialName(value = "operator") val `operator`: SegmentConditionOperator, + + @SerialName(value = "operands") val operands: List, +) : SegmentParentConditionOperands diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentConditionOperator.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentConditionOperator.kt new file mode 100644 index 0000000000..e63bca2053 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentConditionOperator.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* + +/** + * Operator used to combine the operands. + */ +@Serializable +public enum class SegmentConditionOperator(public val value: kotlin.String) { + + @SerialName(value = "AND") + AND("AND"), + + @SerialName(value = "OR") + OR("OR"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentConditionsParam.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentConditionsParam.kt new file mode 100644 index 0000000000..becfe9ef21 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentConditionsParam.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SegmentConditionsParam + * + * @param conditions + */ +@Serializable +public data class SegmentConditionsParam( + + @SerialName(value = "conditions") val conditions: SegmentParentConditions? = null, +) : UpdateSegmentParams diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentFilterOperatorBoolean.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentFilterOperatorBoolean.kt new file mode 100644 index 0000000000..e84332a97e --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentFilterOperatorBoolean.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* + +/** + * The operator used on the boolean filter value. + */ +@Serializable +public enum class SegmentFilterOperatorBoolean(public val value: kotlin.String) { + + @SerialName(value = "EQ") + EQ("EQ"), + + @SerialName(value = "NEQ") + NEQ("NEQ"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentFilterOperatorNumerical.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentFilterOperatorNumerical.kt new file mode 100644 index 0000000000..006583c12a --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentFilterOperatorNumerical.kt @@ -0,0 +1,31 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* + +/** + * The operator used on the numerical filter value. + */ +@Serializable +public enum class SegmentFilterOperatorNumerical(public val value: kotlin.String) { + + @SerialName(value = "EQ") + EQ("EQ"), + + @SerialName(value = "NEQ") + NEQ("NEQ"), + + @SerialName(value = "GT") + GT("GT"), + + @SerialName(value = "GTE") + GTE("GTE"), + + @SerialName(value = "LT") + LT("LT"), + + @SerialName(value = "LTE") + LTE("LTE"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentFilterProbability.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentFilterProbability.kt new file mode 100644 index 0000000000..8342220c2e --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentFilterProbability.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Probability of the filter. + * + * @param lt + * @param lte + * @param gt + * @param gte + */ +@Serializable +public data class SegmentFilterProbability( + + @SerialName(value = "LT") val lt: Double? = null, + + @SerialName(value = "LTE") val lte: Double? = null, + + @SerialName(value = "GT") val gt: Double? = null, + + @SerialName(value = "GTE") val gte: Double? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentFunnelStageFilter.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentFunnelStageFilter.kt new file mode 100644 index 0000000000..fa4215a010 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentFunnelStageFilter.kt @@ -0,0 +1,22 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Filter for funnel stage model predictions. + * + * @param `value` + * @param probability + * @param `operator` + */ +@Serializable +public data class SegmentFunnelStageFilter( + + @SerialName(value = "value") val `value`: String, + + @SerialName(value = "probability") val probability: SegmentFilterProbability, + + @SerialName(value = "operator") val `operator`: SegmentFilterOperatorBoolean? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentNameParam.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentNameParam.kt new file mode 100644 index 0000000000..974b00f4de --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentNameParam.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SegmentNameParam + * + * @param name The name or description of the segment. + */ +@Serializable +public data class SegmentNameParam( + + /** The name or description of the segment. */ + @SerialName(value = "name") val name: String? = null, +) : UpdateSegmentParams diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentOperandAffinity.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentOperandAffinity.kt new file mode 100644 index 0000000000..64cc2ed1f5 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentOperandAffinity.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Operand for affinity model predictions. + * + * @param name + * @param filters + */ +@Serializable +public data class SegmentOperandAffinity( + + @SerialName(value = "name") val name: String, + + @SerialName(value = "filters") val filters: List, +) : SegmentParentConditionOperands, SegmentChildConditionOperands diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentOperandFunnelStage.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentOperandFunnelStage.kt new file mode 100644 index 0000000000..f6f63c3b26 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentOperandFunnelStage.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Operand for funnel stage model predictions. + * + * @param name + * @param filters + */ +@Serializable +public data class SegmentOperandFunnelStage( + + @SerialName(value = "name") val name: String, + + @SerialName(value = "filters") val filters: List, +) : SegmentParentConditionOperands, SegmentChildConditionOperands diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentOperandOrderValue.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentOperandOrderValue.kt new file mode 100644 index 0000000000..e4a3f5628f --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentOperandOrderValue.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Operand for order value model predictions. + * + * @param name + * @param filters + */ +@Serializable +public data class SegmentOperandOrderValue( + + @SerialName(value = "name") val name: String, + + @SerialName(value = "filters") val filters: List, +) : SegmentParentConditionOperands, SegmentChildConditionOperands diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentOperandProperty.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentOperandProperty.kt new file mode 100644 index 0000000000..24623bc3a0 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentOperandProperty.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Operand for user profile properties. + * + * @param name + * @param filters + */ +@Serializable +public data class SegmentOperandProperty( + + @SerialName(value = "name") val name: String, + + @SerialName(value = "filters") val filters: List, +) : SegmentParentConditionOperands, SegmentChildConditionOperands diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentOrderValueFilter.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentOrderValueFilter.kt new file mode 100644 index 0000000000..a62c0866a2 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentOrderValueFilter.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Filter for order value model predictions. + * + * @param `value` + * @param `operator` + */ +@Serializable +public data class SegmentOrderValueFilter( + + @SerialName(value = "value") val `value`: Double, + + @SerialName(value = "operator") val `operator`: SegmentFilterOperatorNumerical? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentParentConditionOperands.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentParentConditionOperands.kt new file mode 100644 index 0000000000..4487a2c688 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentParentConditionOperands.kt @@ -0,0 +1,162 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * SegmentParentConditionOperands + */ +@Serializable(SegmentParentConditionOperandsSerializer::class) +public sealed interface SegmentParentConditionOperands { + + public companion object { + + /** + * Nested segment conditions that only contain operands. + * + * @param `operator` + * @param operands + */ + public fun SegmentChildConditions( + `operator`: SegmentConditionOperator, + operands: List, + ): SegmentChildConditions = com.algolia.client.model.predict.SegmentChildConditions( + `operator` = `operator`, + operands = operands, + ) + + /** + * Operand for affinity model predictions. + * + * @param name + * @param filters + */ + public fun SegmentOperandAffinity( + name: String, + filters: List, + ): SegmentOperandAffinity = com.algolia.client.model.predict.SegmentOperandAffinity( + name = name, + filters = filters, + ) + + /** + * Operand for funnel stage model predictions. + * + * @param name + * @param filters + */ + public fun SegmentOperandFunnelStage( + name: String, + filters: List, + ): SegmentOperandFunnelStage = com.algolia.client.model.predict.SegmentOperandFunnelStage( + name = name, + filters = filters, + ) + + /** + * Operand for order value model predictions. + * + * @param name + * @param filters + */ + public fun SegmentOperandOrderValue( + name: String, + filters: List, + ): SegmentOperandOrderValue = com.algolia.client.model.predict.SegmentOperandOrderValue( + name = name, + filters = filters, + ) + + /** + * Operand for user profile properties. + * + * @param name + * @param filters + */ + public fun SegmentOperandProperty( + name: String, + filters: List, + ): SegmentOperandProperty = com.algolia.client.model.predict.SegmentOperandProperty( + name = name, + filters = filters, + ) + } +} + +internal class SegmentParentConditionOperandsSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("SegmentParentConditionOperands") + + override fun serialize(encoder: Encoder, value: SegmentParentConditionOperands) { + when (value) { + is SegmentChildConditions -> SegmentChildConditions.serializer().serialize(encoder, value) + is SegmentOperandAffinity -> SegmentOperandAffinity.serializer().serialize(encoder, value) + is SegmentOperandFunnelStage -> SegmentOperandFunnelStage.serializer().serialize(encoder, value) + is SegmentOperandOrderValue -> SegmentOperandOrderValue.serializer().serialize(encoder, value) + is SegmentOperandProperty -> SegmentOperandProperty.serializer().serialize(encoder, value) + } + } + + override fun deserialize(decoder: Decoder): SegmentParentConditionOperands { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize SegmentChildConditions + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize SegmentChildConditions (error: ${e.message})") + } + } + + // deserialize SegmentOperandAffinity + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize SegmentOperandAffinity (error: ${e.message})") + } + } + + // deserialize SegmentOperandFunnelStage + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize SegmentOperandFunnelStage (error: ${e.message})") + } + } + + // deserialize SegmentOperandOrderValue + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize SegmentOperandOrderValue (error: ${e.message})") + } + } + + // deserialize SegmentOperandProperty + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize SegmentOperandProperty (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentParentConditions.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentParentConditions.kt new file mode 100644 index 0000000000..53996678c8 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentParentConditions.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The conditions that define which user profiles are included in the segment. Can contain operands and a maximum of 1 level of nested conditions. + * + * @param `operator` + * @param operands + */ +@Serializable +public data class SegmentParentConditions( + + @SerialName(value = "operator") val `operator`: SegmentConditionOperator, + + @SerialName(value = "operands") val operands: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentPropertyFilter.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentPropertyFilter.kt new file mode 100644 index 0000000000..cbf8eb1e37 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentPropertyFilter.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Filter for user profile properties. + * + * @param `value` + * @param `operator` + */ +@Serializable +public data class SegmentPropertyFilter( + + @SerialName(value = "value") val `value`: SegmentPropertyFilterValue, + + @SerialName(value = "operator") val `operator`: SegmentFilterOperatorNumerical? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentPropertyFilterValue.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentPropertyFilterValue.kt new file mode 100644 index 0000000000..a97edfb26d --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentPropertyFilterValue.kt @@ -0,0 +1,7 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +/** + * SegmentPropertyFilterValue + */ +public typealias SegmentPropertyFilterValue = SegmentAffinityFilterValue diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentStatus.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentStatus.kt new file mode 100644 index 0000000000..78c2848ccd --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentStatus.kt @@ -0,0 +1,22 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* + +/** + * The status of the segment. + */ +@Serializable +public enum class SegmentStatus(public val value: kotlin.String) { + + @SerialName(value = "active") + Active("active"), + + @SerialName(value = "pending") + Pending("pending"), + + @SerialName(value = "failed") + Failed("failed"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentType.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentType.kt new file mode 100644 index 0000000000..f77529288c --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/SegmentType.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* + +/** + * The type of the segment. + */ +@Serializable +public enum class SegmentType(public val value: kotlin.String) { + + @SerialName(value = "computed") + Computed("computed"), + + @SerialName(value = "custom") + Custom("custom"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/Segments.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/Segments.kt new file mode 100644 index 0000000000..6aaefdfd50 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/Segments.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Segments that the user belongs to. + * + * @param computed List of computed segments IDs. + * @param custom List of custom segments IDs. + */ +@Serializable +public data class Segments( + + /** List of computed segments IDs. */ + @SerialName(value = "computed") val computed: List, + + /** List of custom segments IDs. */ + @SerialName(value = "custom") val custom: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/TypesToRetrieve.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/TypesToRetrieve.kt new file mode 100644 index 0000000000..61ab4d8a09 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/TypesToRetrieve.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* + +@Serializable +public enum class TypesToRetrieve(public val value: kotlin.String) { + + @SerialName(value = "properties") + Properties("properties"), + + @SerialName(value = "segments") + Segments("segments"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/TypesToRetrieveParam.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/TypesToRetrieveParam.kt new file mode 100644 index 0000000000..163ff652a2 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/TypesToRetrieveParam.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * TypesToRetrieveParam + * + * @param typesToRetrieve + */ +@Serializable +public data class TypesToRetrieveParam( + + @SerialName(value = "typesToRetrieve") val typesToRetrieve: List? = null, +) : FetchAllUserProfilesParams, Params diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/UpdateModelInstanceResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/UpdateModelInstanceResponse.kt new file mode 100644 index 0000000000..17a35493c2 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/UpdateModelInstanceResponse.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * UpdateModelInstanceResponse + * + * @param modelID The ID of the model. + * @param updatedAt Date of last update (ISO-8601 format). + */ +@Serializable +public data class UpdateModelInstanceResponse( + + /** The ID of the model. */ + @SerialName(value = "modelID") val modelID: String, + + /** Date of last update (ISO-8601 format). */ + @SerialName(value = "updatedAt") val updatedAt: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/UpdateModelParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/UpdateModelParams.kt new file mode 100644 index 0000000000..8f364a3948 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/UpdateModelParams.kt @@ -0,0 +1,23 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * UpdateModelParams + * + * @param name The model’s instance name. + * @param modelAttributes + * @param modelStatus + */ +@Serializable +public data class UpdateModelParams( + + /** The model’s instance name. */ + @SerialName(value = "name") val name: String? = null, + + @SerialName(value = "modelAttributes") val modelAttributes: List? = null, + + @SerialName(value = "modelStatus") val modelStatus: ModelStatus? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/UpdateSegmentParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/UpdateSegmentParams.kt new file mode 100644 index 0000000000..bfccacd3f3 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/UpdateSegmentParams.kt @@ -0,0 +1,106 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * UpdateSegmentParams + */ +@Serializable(UpdateSegmentParamsSerializer::class) +public sealed interface UpdateSegmentParams { + + public companion object { + + /** + * AllUpdateSegmentParams + * + * @param name The name or description of the segment. + * @param conditions + */ + public fun AllUpdateSegmentParams( + name: String? = null, + conditions: SegmentParentConditions? = null, + ): AllUpdateSegmentParams = com.algolia.client.model.predict.AllUpdateSegmentParams( + name = name, + conditions = conditions, + ) + + /** + * SegmentConditionsParam + * + * @param conditions + */ + public fun SegmentConditionsParam( + conditions: SegmentParentConditions? = null, + ): SegmentConditionsParam = com.algolia.client.model.predict.SegmentConditionsParam( + conditions = conditions, + ) + + /** + * SegmentNameParam + * + * @param name The name or description of the segment. + */ + public fun SegmentNameParam( + name: String? = null, + ): SegmentNameParam = com.algolia.client.model.predict.SegmentNameParam( + name = name, + ) + } +} + +internal class UpdateSegmentParamsSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("UpdateSegmentParams") + + override fun serialize(encoder: Encoder, value: UpdateSegmentParams) { + when (value) { + is AllUpdateSegmentParams -> AllUpdateSegmentParams.serializer().serialize(encoder, value) + is SegmentConditionsParam -> SegmentConditionsParam.serializer().serialize(encoder, value) + is SegmentNameParam -> SegmentNameParam.serializer().serialize(encoder, value) + } + } + + override fun deserialize(decoder: Decoder): UpdateSegmentParams { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize AllUpdateSegmentParams + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize AllUpdateSegmentParams (error: ${e.message})") + } + } + + // deserialize SegmentConditionsParam + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize SegmentConditionsParam (error: ${e.message})") + } + } + + // deserialize SegmentNameParam + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize SegmentNameParam (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/UpdateSegmentResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/UpdateSegmentResponse.kt new file mode 100644 index 0000000000..a8ce5960eb --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/UpdateSegmentResponse.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * UpdateSegmentResponse + * + * @param segmentID The ID of the segment. + * @param updatedAt The date and time at which the segment was updated (RFC3339). + * @param size The approximate number of users that matched the segment conditions when it was created, last updated, or when model inference last ran. + */ +@Serializable +public data class UpdateSegmentResponse( + + /** The ID of the segment. */ + @SerialName(value = "segmentID") val segmentID: String, + + /** The date and time at which the segment was updated (RFC3339). */ + @SerialName(value = "updatedAt") val updatedAt: String, + + /** The approximate number of users that matched the segment conditions when it was created, last updated, or when model inference last ran. */ + @SerialName(value = "size") val size: Double? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/UserProfile.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/UserProfile.kt new file mode 100644 index 0000000000..15721ff05e --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/UserProfile.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.predict + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * UserProfile + * + * @param user + * @param predictions + * @param properties + * @param segments + */ +@Serializable +public data class UserProfile( + + @SerialName(value = "user") val user: String, + + @SerialName(value = "predictions") val predictions: Predictions? = null, + + @SerialName(value = "properties") val properties: Properties? = null, + + @SerialName(value = "segments") val segments: Segments? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/ErrorBase.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/ErrorBase.kt new file mode 100644 index 0000000000..5839312033 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/ErrorBase.kt @@ -0,0 +1,46 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.querysuggestions + +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Error. + * + * @param message + */ +@Serializable(ErrorBaseSerializer::class) +public data class ErrorBase( + + val message: String? = null, + + val additionalProperties: Map? = null, +) + +internal object ErrorBaseSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("ErrorBase") { + element("message") + } + + override fun deserialize(decoder: Decoder): ErrorBase { + val input = decoder.asJsonDecoder() + val tree = input.decodeJsonObject() + return ErrorBase( + message = tree["message"]?.let { input.json.decodeFromJsonElement(it) }, + additionalProperties = tree.filterKeys { it !in descriptor.elementNames }, + ) + } + + override fun serialize(encoder: Encoder, value: ErrorBase) { + val output = encoder.asJsonEncoder() + val json = buildJsonObject { + value.message?.let { put("message", output.json.encodeToJsonElement(it)) } + value.additionalProperties?.onEach { (key, element) -> put(key, element) } + } + (encoder as JsonEncoder).encodeJsonElement(json) + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/IndexName.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/IndexName.kt new file mode 100644 index 0000000000..50f41d4362 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/IndexName.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.querysuggestions + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * IndexName + * + * @param indexName Index name to target. + */ +@Serializable +public data class IndexName( + + /** Index name to target. */ + @SerialName(value = "indexName") val indexName: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/LogFile.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/LogFile.kt new file mode 100644 index 0000000000..d354303881 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/LogFile.kt @@ -0,0 +1,28 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.querysuggestions + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * LogFile + * + * @param timestamp date and time of creation of the record. + * @param level + * @param message detailed description of what happened. + * @param contextLevel indicates the hierarchy of the records. For example, a record with contextLevel=1 belongs to a preceding record with contextLevel=0. + */ +@Serializable +public data class LogFile( + + /** date and time of creation of the record. */ + @SerialName(value = "timestamp") val timestamp: String, + + @SerialName(value = "level") val level: LogLevel, + + /** detailed description of what happened. */ + @SerialName(value = "message") val message: String, + + /** indicates the hierarchy of the records. For example, a record with contextLevel=1 belongs to a preceding record with contextLevel=0. */ + @SerialName(value = "contextLevel") val contextLevel: Int, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/LogLevel.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/LogLevel.kt new file mode 100644 index 0000000000..971de3ed8b --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/LogLevel.kt @@ -0,0 +1,22 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.querysuggestions + +import kotlinx.serialization.* + +/** + * type of the record, can be one of three values (INFO, SKIP or ERROR). + */ +@Serializable +public enum class LogLevel(public val value: kotlin.String) { + + @SerialName(value = "INFO") + INFO("INFO"), + + @SerialName(value = "SKIP") + SKIP("SKIP"), + + @SerialName(value = "ERROR") + ERROR("ERROR"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/QuerySuggestionsIndex.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/QuerySuggestionsIndex.kt new file mode 100644 index 0000000000..4758410b67 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/QuerySuggestionsIndex.kt @@ -0,0 +1,29 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.querysuggestions + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * QuerySuggestionsIndex + * + * @param indexName Index name to target. + * @param sourceIndices List of source indices used to generate a Query Suggestions index. + * @param languages De-duplicate singular and plural suggestions. For example, let's say your index contains English content, and that two suggestions “shoe” and “shoes” end up in your Query Suggestions index. If the English language is configured, only the most popular of those two suggestions would remain. + * @param exclude List of words and patterns to exclude from the Query Suggestions index. + */ +@Serializable +public data class QuerySuggestionsIndex( + + /** Index name to target. */ + @SerialName(value = "indexName") val indexName: String, + + /** List of source indices used to generate a Query Suggestions index. */ + @SerialName(value = "sourceIndices") val sourceIndices: List, + + /** De-duplicate singular and plural suggestions. For example, let's say your index contains English content, and that two suggestions “shoe” and “shoes” end up in your Query Suggestions index. If the English language is configured, only the most popular of those two suggestions would remain. */ + @SerialName(value = "languages") val languages: List, + + /** List of words and patterns to exclude from the Query Suggestions index. */ + @SerialName(value = "exclude") val exclude: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/QuerySuggestionsIndexParam.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/QuerySuggestionsIndexParam.kt new file mode 100644 index 0000000000..b25f0ae36b --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/QuerySuggestionsIndexParam.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.querysuggestions + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * QuerySuggestionsIndexParam + * + * @param sourceIndices List of source indices used to generate a Query Suggestions index. + * @param languages De-duplicate singular and plural suggestions. For example, let's say your index contains English content, and that two suggestions “shoe” and “shoes” end up in your Query Suggestions index. If the English language is configured, only the most popular of those two suggestions would remain. + * @param exclude List of words and patterns to exclude from the Query Suggestions index. + */ +@Serializable +public data class QuerySuggestionsIndexParam( + + /** List of source indices used to generate a Query Suggestions index. */ + @SerialName(value = "sourceIndices") val sourceIndices: List, + + /** De-duplicate singular and plural suggestions. For example, let's say your index contains English content, and that two suggestions “shoe” and “shoes” end up in your Query Suggestions index. If the English language is configured, only the most popular of those two suggestions would remain. */ + @SerialName(value = "languages") val languages: List? = null, + + /** List of words and patterns to exclude from the Query Suggestions index. */ + @SerialName(value = "exclude") val exclude: List? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/QuerySuggestionsIndexWithIndexParam.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/QuerySuggestionsIndexWithIndexParam.kt new file mode 100644 index 0000000000..4e9918e5b6 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/QuerySuggestionsIndexWithIndexParam.kt @@ -0,0 +1,29 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.querysuggestions + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * QuerySuggestionsIndexWithIndexParam + * + * @param sourceIndices List of source indices used to generate a Query Suggestions index. + * @param indexName Index name to target. + * @param languages De-duplicate singular and plural suggestions. For example, let's say your index contains English content, and that two suggestions “shoe” and “shoes” end up in your Query Suggestions index. If the English language is configured, only the most popular of those two suggestions would remain. + * @param exclude List of words and patterns to exclude from the Query Suggestions index. + */ +@Serializable +public data class QuerySuggestionsIndexWithIndexParam( + + /** List of source indices used to generate a Query Suggestions index. */ + @SerialName(value = "sourceIndices") val sourceIndices: List, + + /** Index name to target. */ + @SerialName(value = "indexName") val indexName: String, + + /** De-duplicate singular and plural suggestions. For example, let's say your index contains English content, and that two suggestions “shoe” and “shoes” end up in your Query Suggestions index. If the English language is configured, only the most popular of those two suggestions would remain. */ + @SerialName(value = "languages") val languages: List? = null, + + /** List of words and patterns to exclude from the Query Suggestions index. */ + @SerialName(value = "exclude") val exclude: List? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/SourceIndex.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/SourceIndex.kt new file mode 100644 index 0000000000..ff95313883 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/SourceIndex.kt @@ -0,0 +1,41 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.querysuggestions + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SourceIndex + * + * @param indexName Source index name. + * @param analyticsTags List of analytics tags to filter the popular searches per tag. + * @param facets List of facets to define as categories for the query suggestions. + * @param minHits Minimum number of hits (e.g., matching records in the source index) to generate a suggestions. + * @param minLetters Minimum number of required letters for a suggestion to remain. + * @param generate List of facet attributes used to generate Query Suggestions. The resulting suggestions are every combination of the facets in the nested list (e.g., (facetA and facetB) and facetC). + * @param `external` List of external indices to use to generate custom Query Suggestions. + */ +@Serializable +public data class SourceIndex( + + /** Source index name. */ + @SerialName(value = "indexName") val indexName: String, + + /** List of analytics tags to filter the popular searches per tag. */ + @SerialName(value = "analyticsTags") val analyticsTags: List? = null, + + /** List of facets to define as categories for the query suggestions. */ + @SerialName(value = "facets") val facets: List? = null, + + /** Minimum number of hits (e.g., matching records in the source index) to generate a suggestions. */ + @SerialName(value = "minHits") val minHits: Int? = null, + + /** Minimum number of required letters for a suggestion to remain. */ + @SerialName(value = "minLetters") val minLetters: Int? = null, + + /** List of facet attributes used to generate Query Suggestions. The resulting suggestions are every combination of the facets in the nested list (e.g., (facetA and facetB) and facetC). */ + @SerialName(value = "generate") val generate: List>? = null, + + /** List of external indices to use to generate custom Query Suggestions. */ + @SerialName(value = "external") val `external`: List? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/SourceIndexExternal.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/SourceIndexExternal.kt new file mode 100644 index 0000000000..1e557dc850 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/SourceIndexExternal.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.querysuggestions + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SourceIndexExternal + * + * @param query The suggestion you would like to add. + * @param count The measure of the suggestion relative popularity. + */ +@Serializable +public data class SourceIndexExternal( + + /** The suggestion you would like to add. */ + @SerialName(value = "query") val query: String, + + /** The measure of the suggestion relative popularity. */ + @SerialName(value = "count") val count: Int, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/SourceIndexWithReplicas.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/SourceIndexWithReplicas.kt new file mode 100644 index 0000000000..8533d8771d --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/SourceIndexWithReplicas.kt @@ -0,0 +1,45 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.querysuggestions + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Source index with replicas used to generate a Query Suggestions index. + * + * @param replicas true if the Query Suggestions index is a replicas. + * @param indexName Source index name. + * @param analyticsTags List of analytics tags to filter the popular searches per tag. + * @param facets List of facets to define as categories for the query suggestions. + * @param minHits Minimum number of hits (e.g., matching records in the source index) to generate a suggestions. + * @param minLetters Minimum number of required letters for a suggestion to remain. + * @param generate List of facet attributes used to generate Query Suggestions. The resulting suggestions are every combination of the facets in the nested list (e.g., (facetA and facetB) and facetC). + * @param `external` List of external indices to use to generate custom Query Suggestions. + */ +@Serializable +public data class SourceIndexWithReplicas( + + /** true if the Query Suggestions index is a replicas. */ + @SerialName(value = "replicas") val replicas: Boolean, + + /** Source index name. */ + @SerialName(value = "indexName") val indexName: String, + + /** List of analytics tags to filter the popular searches per tag. */ + @SerialName(value = "analyticsTags") val analyticsTags: List, + + /** List of facets to define as categories for the query suggestions. */ + @SerialName(value = "facets") val facets: List, + + /** Minimum number of hits (e.g., matching records in the source index) to generate a suggestions. */ + @SerialName(value = "minHits") val minHits: Int, + + /** Minimum number of required letters for a suggestion to remain. */ + @SerialName(value = "minLetters") val minLetters: Int, + + /** List of facet attributes used to generate Query Suggestions. The resulting suggestions are every combination of the facets in the nested list (e.g., (facetA and facetB) and facetC). */ + @SerialName(value = "generate") val generate: List>, + + /** List of external indices to use to generate custom Query Suggestions. */ + @SerialName(value = "external") val `external`: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/Status.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/Status.kt new file mode 100644 index 0000000000..1f60b34f66 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/Status.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.querysuggestions + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Status + * + * @param indexName The targeted index name. + * @param isRunning true if the Query Suggestions index is running. + * @param lastBuiltAt Date and time of the last build. + */ +@Serializable +public data class Status( + + /** The targeted index name. */ + @SerialName(value = "indexName") val indexName: String, + + /** true if the Query Suggestions index is running. */ + @SerialName(value = "isRunning") val isRunning: Boolean, + + /** Date and time of the last build. */ + @SerialName(value = "lastBuiltAt") val lastBuiltAt: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/SuccessResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/SuccessResponse.kt new file mode 100644 index 0000000000..ac72b560a8 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/SuccessResponse.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.querysuggestions + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SuccessResponse + * + * @param status The status code. + * @param message Message of the response. + */ +@Serializable +public data class SuccessResponse( + + /** The status code. */ + @SerialName(value = "status") val status: Int, + + /** Message of the response. */ + @SerialName(value = "message") val message: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/AdvancedSyntaxFeatures.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/AdvancedSyntaxFeatures.kt new file mode 100644 index 0000000000..c19ca38dd3 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/AdvancedSyntaxFeatures.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* + +@Serializable +public enum class AdvancedSyntaxFeatures(public val value: kotlin.String) { + + @SerialName(value = "exactPhrase") + ExactPhrase("exactPhrase"), + + @SerialName(value = "excludeWords") + ExcludeWords("excludeWords"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/AlternativesAsExact.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/AlternativesAsExact.kt new file mode 100644 index 0000000000..b5a27a49f7 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/AlternativesAsExact.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* + +@Serializable +public enum class AlternativesAsExact(public val value: kotlin.String) { + + @SerialName(value = "ignorePlurals") + IgnorePlurals("ignorePlurals"), + + @SerialName(value = "singleWordSynonym") + SingleWordSynonym("singleWordSynonym"), + + @SerialName(value = "multiWordsSynonym") + MultiWordsSynonym("multiWordsSynonym"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/AroundRadius.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/AroundRadius.kt new file mode 100644 index 0000000000..edbbba8850 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/AroundRadius.kt @@ -0,0 +1,76 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Define the maximum radius for a geo search (in meters). + */ +@Serializable(AroundRadiusSerializer::class) +public sealed interface AroundRadius { + + public data class IntWrapper(val value: Int) : AroundRadius + + public companion object { + + /** + * AroundRadiusAll + */ + public fun of(value: AroundRadiusAll): AroundRadiusAll = value + + /** + * AroundRadius as Int + * + */ + public fun Number( + value: Int, + ): IntWrapper = IntWrapper( + value = value, + ) + } +} + +internal class AroundRadiusSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("AroundRadius") + + override fun serialize(encoder: Encoder, value: AroundRadius) { + when (value) { + is AroundRadiusAll -> AroundRadiusAll.serializer().serialize(encoder, value) + is AroundRadius.IntWrapper -> Int.serializer().serialize(encoder, value.value) + } + } + + override fun deserialize(decoder: Decoder): AroundRadius { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize AroundRadiusAll + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize AroundRadiusAll (error: ${e.message})") + } + } + + // deserialize Int + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize Int (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/AroundRadiusAll.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/AroundRadiusAll.kt new file mode 100644 index 0000000000..2e28b218ac --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/AroundRadiusAll.kt @@ -0,0 +1,13 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* + +@Serializable +public enum class AroundRadiusAll(public val value: kotlin.String) : AroundRadius { + + @SerialName(value = "all") + All("all"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/BaseRecommendRequest.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/BaseRecommendRequest.kt new file mode 100644 index 0000000000..448c9171ab --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/BaseRecommendRequest.kt @@ -0,0 +1,31 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * BaseRecommendRequest + * + * @param indexName The Algolia index name. + * @param threshold The threshold to use when filtering recommendations by their score. + * @param maxRecommendations The max number of recommendations to retrieve. If it's set to 0, all the recommendations of the objectID may be returned. + * @param queryParameters + * @param fallbackParameters + */ +@Serializable +public data class BaseRecommendRequest( + + /** The Algolia index name. */ + @SerialName(value = "indexName") val indexName: String, + + /** The threshold to use when filtering recommendations by their score. */ + @SerialName(value = "threshold") val threshold: Int, + + /** The max number of recommendations to retrieve. If it's set to 0, all the recommendations of the objectID may be returned. */ + @SerialName(value = "maxRecommendations") val maxRecommendations: Int? = null, + + @SerialName(value = "queryParameters") val queryParameters: SearchParamsObject? = null, + + @SerialName(value = "fallbackParameters") val fallbackParameters: SearchParamsObject? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/BaseRecommendationRequest.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/BaseRecommendationRequest.kt new file mode 100644 index 0000000000..58b2cb2141 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/BaseRecommendationRequest.kt @@ -0,0 +1,20 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * BaseRecommendationRequest + * + * @param model + * @param objectID Unique identifier of the object. + */ +@Serializable +public data class BaseRecommendationRequest( + + @SerialName(value = "model") val model: RecommendationModels, + + /** Unique identifier of the object. */ + @SerialName(value = "objectID") val objectID: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/BaseSearchParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/BaseSearchParams.kt new file mode 100644 index 0000000000..a2d88e0a13 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/BaseSearchParams.kt @@ -0,0 +1,143 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * BaseSearchParams + * + * @param query The text to search in the index. + * @param similarQuery Overrides the query parameter and performs a more generic search that can be used to find \"similar\" results. + * @param filters Filter the query with numeric, facet and/or tag filters. + * @param facetFilters + * @param optionalFilters + * @param numericFilters + * @param tagFilters + * @param sumOrFiltersScores Determines how to calculate the total score for filtering. + * @param facets Retrieve facets and their facet values. + * @param maxValuesPerFacet Maximum number of facet values to return for each facet during a regular search. + * @param facetingAfterDistinct Force faceting to be applied after de-duplication (via the Distinct setting). + * @param sortFacetValuesBy Controls how facet values are fetched. + * @param page Specify the page to retrieve. + * @param offset Specify the offset of the first hit to return. + * @param length Set the number of hits to retrieve (used only with offset). + * @param aroundLatLng Search for entries around a central geolocation, enabling a geo search within a circular area. + * @param aroundLatLngViaIP Search for entries around a given location automatically computed from the requester's IP address. + * @param aroundRadius + * @param aroundPrecision Precision of geo search (in meters), to add grouping by geo location to the ranking formula. + * @param minimumAroundRadius Minimum radius (in meters) used for a geo search when aroundRadius is not set. + * @param insideBoundingBox Search inside a rectangular area (in geo coordinates). + * @param insidePolygon Search inside a polygon (in geo coordinates). + * @param naturalLanguages This parameter changes the default values of certain parameters and settings that work best for a natural language query, such as ignorePlurals, removeStopWords, removeWordsIfNoResults, analyticsTags and ruleContexts. These parameters and settings work well together when the query is formatted in natural language instead of keywords, for example when your user performs a voice search. + * @param ruleContexts Enables contextual rules. + * @param personalizationImpact Define the impact of the Personalization feature. + * @param userToken Associates a certain user token with the current search. + * @param getRankingInfo Retrieve detailed ranking information. + * @param clickAnalytics Enable the Click Analytics feature. + * @param analytics Whether the current query will be taken into account in the Analytics. + * @param analyticsTags List of tags to apply to the query for analytics purposes. + * @param percentileComputation Whether to include or exclude a query from the processing-time percentile computation. + * @param enableABTest Whether this search should participate in running AB tests. + * @param enableReRanking Whether this search should use AI Re-Ranking. + * @param reRankingApplyFilter + */ +@Serializable +public data class BaseSearchParams( + + /** The text to search in the index. */ + @SerialName(value = "query") val query: String? = null, + + /** Overrides the query parameter and performs a more generic search that can be used to find \"similar\" results. */ + @SerialName(value = "similarQuery") val similarQuery: String? = null, + + /** Filter the query with numeric, facet and/or tag filters. */ + @SerialName(value = "filters") val filters: String? = null, + + @SerialName(value = "facetFilters") val facetFilters: FacetFilters? = null, + + @SerialName(value = "optionalFilters") val optionalFilters: OptionalFilters? = null, + + @SerialName(value = "numericFilters") val numericFilters: NumericFilters? = null, + + @SerialName(value = "tagFilters") val tagFilters: TagFilters? = null, + + /** Determines how to calculate the total score for filtering. */ + @SerialName(value = "sumOrFiltersScores") val sumOrFiltersScores: Boolean? = null, + + /** Retrieve facets and their facet values. */ + @SerialName(value = "facets") val facets: List? = null, + + /** Maximum number of facet values to return for each facet during a regular search. */ + @SerialName(value = "maxValuesPerFacet") val maxValuesPerFacet: Int? = null, + + /** Force faceting to be applied after de-duplication (via the Distinct setting). */ + @SerialName(value = "facetingAfterDistinct") val facetingAfterDistinct: Boolean? = null, + + /** Controls how facet values are fetched. */ + @SerialName(value = "sortFacetValuesBy") val sortFacetValuesBy: String? = null, + + /** Specify the page to retrieve. */ + @SerialName(value = "page") val page: Int? = null, + + /** Specify the offset of the first hit to return. */ + @SerialName(value = "offset") val offset: Int? = null, + + /** Set the number of hits to retrieve (used only with offset). */ + @SerialName(value = "length") val length: Int? = null, + + /** Search for entries around a central geolocation, enabling a geo search within a circular area. */ + @SerialName(value = "aroundLatLng") val aroundLatLng: String? = null, + + /** Search for entries around a given location automatically computed from the requester's IP address. */ + @SerialName(value = "aroundLatLngViaIP") val aroundLatLngViaIP: Boolean? = null, + + @SerialName(value = "aroundRadius") val aroundRadius: AroundRadius? = null, + + /** Precision of geo search (in meters), to add grouping by geo location to the ranking formula. */ + @SerialName(value = "aroundPrecision") val aroundPrecision: Int? = null, + + /** Minimum radius (in meters) used for a geo search when aroundRadius is not set. */ + @SerialName(value = "minimumAroundRadius") val minimumAroundRadius: Int? = null, + + /** Search inside a rectangular area (in geo coordinates). */ + @SerialName(value = "insideBoundingBox") val insideBoundingBox: List? = null, + + /** Search inside a polygon (in geo coordinates). */ + @SerialName(value = "insidePolygon") val insidePolygon: List? = null, + + /** This parameter changes the default values of certain parameters and settings that work best for a natural language query, such as ignorePlurals, removeStopWords, removeWordsIfNoResults, analyticsTags and ruleContexts. These parameters and settings work well together when the query is formatted in natural language instead of keywords, for example when your user performs a voice search. */ + @SerialName(value = "naturalLanguages") val naturalLanguages: List? = null, + + /** Enables contextual rules. */ + @SerialName(value = "ruleContexts") val ruleContexts: List? = null, + + /** Define the impact of the Personalization feature. */ + @SerialName(value = "personalizationImpact") val personalizationImpact: Int? = null, + + /** Associates a certain user token with the current search. */ + @SerialName(value = "userToken") val userToken: String? = null, + + /** Retrieve detailed ranking information. */ + @SerialName(value = "getRankingInfo") val getRankingInfo: Boolean? = null, + + /** Enable the Click Analytics feature. */ + @SerialName(value = "clickAnalytics") val clickAnalytics: Boolean? = null, + + /** Whether the current query will be taken into account in the Analytics. */ + @SerialName(value = "analytics") val analytics: Boolean? = null, + + /** List of tags to apply to the query for analytics purposes. */ + @SerialName(value = "analyticsTags") val analyticsTags: List? = null, + + /** Whether to include or exclude a query from the processing-time percentile computation. */ + @SerialName(value = "percentileComputation") val percentileComputation: Boolean? = null, + + /** Whether this search should participate in running AB tests. */ + @SerialName(value = "enableABTest") val enableABTest: Boolean? = null, + + /** Whether this search should use AI Re-Ranking. */ + @SerialName(value = "enableReRanking") val enableReRanking: Boolean? = null, + + @SerialName(value = "reRankingApplyFilter") val reRankingApplyFilter: ReRankingApplyFilter? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/BaseSearchParamsWithoutQuery.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/BaseSearchParamsWithoutQuery.kt new file mode 100644 index 0000000000..6351553de5 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/BaseSearchParamsWithoutQuery.kt @@ -0,0 +1,139 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * BaseSearchParamsWithoutQuery + * + * @param similarQuery Overrides the query parameter and performs a more generic search that can be used to find \"similar\" results. + * @param filters Filter the query with numeric, facet and/or tag filters. + * @param facetFilters + * @param optionalFilters + * @param numericFilters + * @param tagFilters + * @param sumOrFiltersScores Determines how to calculate the total score for filtering. + * @param facets Retrieve facets and their facet values. + * @param maxValuesPerFacet Maximum number of facet values to return for each facet during a regular search. + * @param facetingAfterDistinct Force faceting to be applied after de-duplication (via the Distinct setting). + * @param sortFacetValuesBy Controls how facet values are fetched. + * @param page Specify the page to retrieve. + * @param offset Specify the offset of the first hit to return. + * @param length Set the number of hits to retrieve (used only with offset). + * @param aroundLatLng Search for entries around a central geolocation, enabling a geo search within a circular area. + * @param aroundLatLngViaIP Search for entries around a given location automatically computed from the requester's IP address. + * @param aroundRadius + * @param aroundPrecision Precision of geo search (in meters), to add grouping by geo location to the ranking formula. + * @param minimumAroundRadius Minimum radius (in meters) used for a geo search when aroundRadius is not set. + * @param insideBoundingBox Search inside a rectangular area (in geo coordinates). + * @param insidePolygon Search inside a polygon (in geo coordinates). + * @param naturalLanguages This parameter changes the default values of certain parameters and settings that work best for a natural language query, such as ignorePlurals, removeStopWords, removeWordsIfNoResults, analyticsTags and ruleContexts. These parameters and settings work well together when the query is formatted in natural language instead of keywords, for example when your user performs a voice search. + * @param ruleContexts Enables contextual rules. + * @param personalizationImpact Define the impact of the Personalization feature. + * @param userToken Associates a certain user token with the current search. + * @param getRankingInfo Retrieve detailed ranking information. + * @param clickAnalytics Enable the Click Analytics feature. + * @param analytics Whether the current query will be taken into account in the Analytics. + * @param analyticsTags List of tags to apply to the query for analytics purposes. + * @param percentileComputation Whether to include or exclude a query from the processing-time percentile computation. + * @param enableABTest Whether this search should participate in running AB tests. + * @param enableReRanking Whether this search should use AI Re-Ranking. + * @param reRankingApplyFilter + */ +@Serializable +public data class BaseSearchParamsWithoutQuery( + + /** Overrides the query parameter and performs a more generic search that can be used to find \"similar\" results. */ + @SerialName(value = "similarQuery") val similarQuery: String? = null, + + /** Filter the query with numeric, facet and/or tag filters. */ + @SerialName(value = "filters") val filters: String? = null, + + @SerialName(value = "facetFilters") val facetFilters: FacetFilters? = null, + + @SerialName(value = "optionalFilters") val optionalFilters: OptionalFilters? = null, + + @SerialName(value = "numericFilters") val numericFilters: NumericFilters? = null, + + @SerialName(value = "tagFilters") val tagFilters: TagFilters? = null, + + /** Determines how to calculate the total score for filtering. */ + @SerialName(value = "sumOrFiltersScores") val sumOrFiltersScores: Boolean? = null, + + /** Retrieve facets and their facet values. */ + @SerialName(value = "facets") val facets: List? = null, + + /** Maximum number of facet values to return for each facet during a regular search. */ + @SerialName(value = "maxValuesPerFacet") val maxValuesPerFacet: Int? = null, + + /** Force faceting to be applied after de-duplication (via the Distinct setting). */ + @SerialName(value = "facetingAfterDistinct") val facetingAfterDistinct: Boolean? = null, + + /** Controls how facet values are fetched. */ + @SerialName(value = "sortFacetValuesBy") val sortFacetValuesBy: String? = null, + + /** Specify the page to retrieve. */ + @SerialName(value = "page") val page: Int? = null, + + /** Specify the offset of the first hit to return. */ + @SerialName(value = "offset") val offset: Int? = null, + + /** Set the number of hits to retrieve (used only with offset). */ + @SerialName(value = "length") val length: Int? = null, + + /** Search for entries around a central geolocation, enabling a geo search within a circular area. */ + @SerialName(value = "aroundLatLng") val aroundLatLng: String? = null, + + /** Search for entries around a given location automatically computed from the requester's IP address. */ + @SerialName(value = "aroundLatLngViaIP") val aroundLatLngViaIP: Boolean? = null, + + @SerialName(value = "aroundRadius") val aroundRadius: AroundRadius? = null, + + /** Precision of geo search (in meters), to add grouping by geo location to the ranking formula. */ + @SerialName(value = "aroundPrecision") val aroundPrecision: Int? = null, + + /** Minimum radius (in meters) used for a geo search when aroundRadius is not set. */ + @SerialName(value = "minimumAroundRadius") val minimumAroundRadius: Int? = null, + + /** Search inside a rectangular area (in geo coordinates). */ + @SerialName(value = "insideBoundingBox") val insideBoundingBox: List? = null, + + /** Search inside a polygon (in geo coordinates). */ + @SerialName(value = "insidePolygon") val insidePolygon: List? = null, + + /** This parameter changes the default values of certain parameters and settings that work best for a natural language query, such as ignorePlurals, removeStopWords, removeWordsIfNoResults, analyticsTags and ruleContexts. These parameters and settings work well together when the query is formatted in natural language instead of keywords, for example when your user performs a voice search. */ + @SerialName(value = "naturalLanguages") val naturalLanguages: List? = null, + + /** Enables contextual rules. */ + @SerialName(value = "ruleContexts") val ruleContexts: List? = null, + + /** Define the impact of the Personalization feature. */ + @SerialName(value = "personalizationImpact") val personalizationImpact: Int? = null, + + /** Associates a certain user token with the current search. */ + @SerialName(value = "userToken") val userToken: String? = null, + + /** Retrieve detailed ranking information. */ + @SerialName(value = "getRankingInfo") val getRankingInfo: Boolean? = null, + + /** Enable the Click Analytics feature. */ + @SerialName(value = "clickAnalytics") val clickAnalytics: Boolean? = null, + + /** Whether the current query will be taken into account in the Analytics. */ + @SerialName(value = "analytics") val analytics: Boolean? = null, + + /** List of tags to apply to the query for analytics purposes. */ + @SerialName(value = "analyticsTags") val analyticsTags: List? = null, + + /** Whether to include or exclude a query from the processing-time percentile computation. */ + @SerialName(value = "percentileComputation") val percentileComputation: Boolean? = null, + + /** Whether this search should participate in running AB tests. */ + @SerialName(value = "enableABTest") val enableABTest: Boolean? = null, + + /** Whether this search should use AI Re-Ranking. */ + @SerialName(value = "enableReRanking") val enableReRanking: Boolean? = null, + + @SerialName(value = "reRankingApplyFilter") val reRankingApplyFilter: ReRankingApplyFilter? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/BaseSearchResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/BaseSearchResponse.kt new file mode 100644 index 0000000000..1d36b936c2 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/BaseSearchResponse.kt @@ -0,0 +1,115 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * BaseSearchResponse + * + * @param exhaustiveNbHits Indicate if the nbHits count was exhaustive or approximate. + * @param hitsPerPage Set the number of hits per page. + * @param nbHits Number of hits that the search query matched. + * @param nbPages Number of pages available for the current query. + * @param page Specify the page to retrieve. + * @param params A url-encoded string of all search parameters. + * @param processingTimeMS Time the server took to process the request, in milliseconds. + * @param query The text to search in the index. + * @param abTestID If a search encounters an index that is being A/B tested, abTestID reports the ongoing A/B test ID. + * @param abTestVariantID If a search encounters an index that is being A/B tested, abTestVariantID reports the variant ID of the index used (starting at 1). + * @param aroundLatLng The computed geo location. + * @param automaticRadius The automatically computed radius. For legacy reasons, this parameter is a string and not an integer. + * @param exhaustiveFacetsCount Whether the facet count is exhaustive or approximate. + * @param exhaustiveTypo Indicate if the typo-tolerance search was exhaustive or approximate (only included when typo-tolerance is enabled). + * @param facets A mapping of each facet name to the corresponding facet counts. + * @param facetsStats Statistics for numerical facets. + * @param index Index name used for the query. + * @param indexUsed Index name used for the query. In the case of an A/B test, the targeted index isn't always the index used by the query. + * @param message Used to return warnings about the query. + * @param nbSortedHits The number of hits selected and sorted by the relevant sort algorithm. + * @param redirect + * @param parsedQuery The query string that will be searched, after normalization. + * @param queryAfterRemoval A markup text indicating which parts of the original query have been removed in order to retrieve a non-empty result set. + * @param serverUsed Actual host name of the server that processed the request. + * @param userData Lets you store custom data in your indices. + * @param renderingContent + */ +@Serializable +public data class BaseSearchResponse( + + /** Indicate if the nbHits count was exhaustive or approximate. */ + @SerialName(value = "exhaustiveNbHits") val exhaustiveNbHits: Boolean, + + /** Set the number of hits per page. */ + @SerialName(value = "hitsPerPage") val hitsPerPage: Int, + + /** Number of hits that the search query matched. */ + @SerialName(value = "nbHits") val nbHits: Int, + + /** Number of pages available for the current query. */ + @SerialName(value = "nbPages") val nbPages: Int, + + /** Specify the page to retrieve. */ + @SerialName(value = "page") val page: Int, + + /** A url-encoded string of all search parameters. */ + @SerialName(value = "params") val params: String, + + /** Time the server took to process the request, in milliseconds. */ + @SerialName(value = "processingTimeMS") val processingTimeMS: Int, + + /** The text to search in the index. */ + @SerialName(value = "query") val query: String, + + /** If a search encounters an index that is being A/B tested, abTestID reports the ongoing A/B test ID. */ + @SerialName(value = "abTestID") val abTestID: Int? = null, + + /** If a search encounters an index that is being A/B tested, abTestVariantID reports the variant ID of the index used (starting at 1). */ + @SerialName(value = "abTestVariantID") val abTestVariantID: Int? = null, + + /** The computed geo location. */ + @SerialName(value = "aroundLatLng") val aroundLatLng: String? = null, + + /** The automatically computed radius. For legacy reasons, this parameter is a string and not an integer. */ + @SerialName(value = "automaticRadius") val automaticRadius: String? = null, + + /** Whether the facet count is exhaustive or approximate. */ + @SerialName(value = "exhaustiveFacetsCount") val exhaustiveFacetsCount: Boolean? = null, + + /** Indicate if the typo-tolerance search was exhaustive or approximate (only included when typo-tolerance is enabled). */ + @SerialName(value = "exhaustiveTypo") val exhaustiveTypo: Boolean? = null, + + /** A mapping of each facet name to the corresponding facet counts. */ + @SerialName(value = "facets") val facets: Map>? = null, + + /** Statistics for numerical facets. */ + @SerialName(value = "facets_stats") val facetsStats: Map? = null, + + /** Index name used for the query. */ + @SerialName(value = "index") val index: String? = null, + + /** Index name used for the query. In the case of an A/B test, the targeted index isn't always the index used by the query. */ + @SerialName(value = "indexUsed") val indexUsed: String? = null, + + /** Used to return warnings about the query. */ + @SerialName(value = "message") val message: String? = null, + + /** The number of hits selected and sorted by the relevant sort algorithm. */ + @SerialName(value = "nbSortedHits") val nbSortedHits: Int? = null, + + @SerialName(value = "redirect") val redirect: BaseSearchResponseRedirect? = null, + + /** The query string that will be searched, after normalization. */ + @SerialName(value = "parsedQuery") val parsedQuery: String? = null, + + /** A markup text indicating which parts of the original query have been removed in order to retrieve a non-empty result set. */ + @SerialName(value = "queryAfterRemoval") val queryAfterRemoval: String? = null, + + /** Actual host name of the server that processed the request. */ + @SerialName(value = "serverUsed") val serverUsed: String? = null, + + /** Lets you store custom data in your indices. */ + @SerialName(value = "userData") val userData: JsonObject? = null, + + @SerialName(value = "renderingContent") val renderingContent: RenderingContent? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/BaseSearchResponseRedirect.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/BaseSearchResponseRedirect.kt new file mode 100644 index 0000000000..68c917c9d9 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/BaseSearchResponseRedirect.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * This parameter is for internal use only. + * + * @param index + */ +@Serializable +public data class BaseSearchResponseRedirect( + + @SerialName(value = "index") val index: List? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/BaseTrendingRequest.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/BaseTrendingRequest.kt new file mode 100644 index 0000000000..372e9d017f --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/BaseTrendingRequest.kt @@ -0,0 +1,24 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * BaseTrendingRequest + * + * @param model + * @param facetName The facet name to use for trending models. + * @param facetValue The facet value to use for trending models. + */ +@Serializable +public data class BaseTrendingRequest( + + @SerialName(value = "model") val model: TrendingModels, + + /** The facet name to use for trending models. */ + @SerialName(value = "facetName") val facetName: String? = null, + + /** The facet value to use for trending models. */ + @SerialName(value = "facetValue") val facetValue: String? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/Distinct.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/Distinct.kt new file mode 100644 index 0000000000..872e82f388 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/Distinct.kt @@ -0,0 +1,83 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Enables de-duplication or grouping of results. + */ +@Serializable(DistinctSerializer::class) +public sealed interface Distinct { + + public data class BooleanWrapper(val value: Boolean) : Distinct + + public data class IntWrapper(val value: Int) : Distinct + + public companion object { + + /** + * Distinct as Boolean + * + */ + public fun Boolean( + value: Boolean, + ): BooleanWrapper = BooleanWrapper( + value = value, + ) + + /** + * Distinct as Int + * + */ + public fun Number( + value: Int, + ): IntWrapper = IntWrapper( + value = value, + ) + } +} + +internal class DistinctSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("Distinct") + + override fun serialize(encoder: Encoder, value: Distinct) { + when (value) { + is Distinct.BooleanWrapper -> Boolean.serializer().serialize(encoder, value.value) + is Distinct.IntWrapper -> Int.serializer().serialize(encoder, value.value) + } + } + + override fun deserialize(decoder: Decoder): Distinct { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize Boolean + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize Boolean (error: ${e.message})") + } + } + + // deserialize Int + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize Int (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/ErrorBase.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/ErrorBase.kt new file mode 100644 index 0000000000..4279f28785 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/ErrorBase.kt @@ -0,0 +1,46 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Error. + * + * @param message + */ +@Serializable(ErrorBaseSerializer::class) +public data class ErrorBase( + + val message: String? = null, + + val additionalProperties: Map? = null, +) + +internal object ErrorBaseSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("ErrorBase") { + element("message") + } + + override fun deserialize(decoder: Decoder): ErrorBase { + val input = decoder.asJsonDecoder() + val tree = input.decodeJsonObject() + return ErrorBase( + message = tree["message"]?.let { input.json.decodeFromJsonElement(it) }, + additionalProperties = tree.filterKeys { it !in descriptor.elementNames }, + ) + } + + override fun serialize(encoder: Encoder, value: ErrorBase) { + val output = encoder.asJsonEncoder() + val json = buildJsonObject { + value.message?.let { put("message", output.json.encodeToJsonElement(it)) } + value.additionalProperties?.onEach { (key, element) -> put(key, element) } + } + (encoder as JsonEncoder).encodeJsonElement(json) + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/ExactOnSingleWordQuery.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/ExactOnSingleWordQuery.kt new file mode 100644 index 0000000000..90ca7186a1 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/ExactOnSingleWordQuery.kt @@ -0,0 +1,22 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* + +/** + * Controls how the exact ranking criterion is computed when the query contains only one word. + */ +@Serializable +public enum class ExactOnSingleWordQuery(public val value: kotlin.String) { + + @SerialName(value = "attribute") + Attribute("attribute"), + + @SerialName(value = "none") + None("none"), + + @SerialName(value = "word") + Word("word"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/FacetFilters.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/FacetFilters.kt new file mode 100644 index 0000000000..cbec6a950f --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/FacetFilters.kt @@ -0,0 +1,83 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Filter hits by facet value. + */ +@Serializable(FacetFiltersSerializer::class) +public sealed interface FacetFilters { + + public data class ListOfMixedSearchFiltersWrapper(val value: List) : FacetFilters + + public data class StringWrapper(val value: String) : FacetFilters + + public companion object { + + /** + * FacetFilters as List + * + */ + public fun ListOfMixedSearchFilters( + value: List, + ): ListOfMixedSearchFiltersWrapper = ListOfMixedSearchFiltersWrapper( + value = value, + ) + + /** + * FacetFilters as String + * + */ + public fun String( + value: String, + ): StringWrapper = StringWrapper( + value = value, + ) + } +} + +internal class FacetFiltersSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("FacetFilters") + + override fun serialize(encoder: Encoder, value: FacetFilters) { + when (value) { + is FacetFilters.ListOfMixedSearchFiltersWrapper -> ListSerializer(MixedSearchFilters.serializer()).serialize(encoder, value.value) + is FacetFilters.StringWrapper -> String.serializer().serialize(encoder, value.value) + } + } + + override fun deserialize(decoder: Decoder): FacetFilters { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize List + if (tree is JsonArray) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize List (error: ${e.message})") + } + } + + // deserialize String + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize String (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/FacetOrdering.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/FacetOrdering.kt new file mode 100644 index 0000000000..847c740ec0 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/FacetOrdering.kt @@ -0,0 +1,20 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Defining how facets should be ordered. + * + * @param facets + * @param values The ordering of facet values, within an individual list. + */ +@Serializable +public data class FacetOrdering( + + @SerialName(value = "facets") val facets: Facets? = null, + + /** The ordering of facet values, within an individual list. */ + @SerialName(value = "values") val values: Map? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/Facets.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/Facets.kt new file mode 100644 index 0000000000..f071aece66 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/Facets.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The ordering of facets (widgets). + * + * @param order Pinned order of facet lists. + */ +@Serializable +public data class Facets( + + /** Pinned order of facet lists. */ + @SerialName(value = "order") val order: List? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/FacetsStats.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/FacetsStats.kt new file mode 100644 index 0000000000..e162f07fe3 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/FacetsStats.kt @@ -0,0 +1,29 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * FacetsStats + * + * @param min The minimum value in the result set. + * @param max The maximum value in the result set. + * @param avg The average facet value in the result set. + * @param sum The sum of all values in the result set. + */ +@Serializable +public data class FacetsStats( + + /** The minimum value in the result set. */ + @SerialName(value = "min") val min: Int? = null, + + /** The maximum value in the result set. */ + @SerialName(value = "max") val max: Int? = null, + + /** The average facet value in the result set. */ + @SerialName(value = "avg") val avg: Int? = null, + + /** The sum of all values in the result set. */ + @SerialName(value = "sum") val sum: Int? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/GetRecommendationsParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/GetRecommendationsParams.kt new file mode 100644 index 0000000000..2745fef5c0 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/GetRecommendationsParams.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The `getRecommendations` parameters. + * + * @param requests The `getRecommendations` requests. + */ +@Serializable +public data class GetRecommendationsParams( + + /** The `getRecommendations` requests. */ + @SerialName(value = "requests") val requests: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/GetRecommendationsResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/GetRecommendationsResponse.kt new file mode 100644 index 0000000000..4c36fc4c46 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/GetRecommendationsResponse.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * GetRecommendationsResponse + * + * @param results + */ +@Serializable +public data class GetRecommendationsResponse( + + @SerialName(value = "results") val results: List? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/HighlightResult.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/HighlightResult.kt new file mode 100644 index 0000000000..db84d7f52b --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/HighlightResult.kt @@ -0,0 +1,91 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * HighlightResult + */ +@Serializable(HighlightResultSerializer::class) +public sealed interface HighlightResult { + + public data class ListOfHighlightResultOptionWrapper(val value: List) : HighlightResult + + public companion object { + + /** + * Show highlighted section and words matched on a query. + * + * @param `value` Markup text with occurrences highlighted. + * @param matchLevel + * @param matchedWords List of words from the query that matched the object. + * @param fullyHighlighted Whether the entire attribute value is highlighted. + */ + public fun HighlightResultOption( + `value`: String, + matchLevel: MatchLevel, + matchedWords: List, + fullyHighlighted: Boolean? = null, + ): HighlightResultOption = com.algolia.client.model.recommend.HighlightResultOption( + `value` = `value`, + matchLevel = matchLevel, + matchedWords = matchedWords, + fullyHighlighted = fullyHighlighted, + ) + + /** + * HighlightResult as List + * + */ + public fun ListOfHighlightResultOption( + value: List, + ): ListOfHighlightResultOptionWrapper = ListOfHighlightResultOptionWrapper( + value = value, + ) + } +} + +internal class HighlightResultSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("HighlightResult") + + override fun serialize(encoder: Encoder, value: HighlightResult) { + when (value) { + is HighlightResultOption -> HighlightResultOption.serializer().serialize(encoder, value) + is HighlightResult.ListOfHighlightResultOptionWrapper -> ListSerializer(HighlightResultOption.serializer()).serialize(encoder, value.value) + } + } + + override fun deserialize(decoder: Decoder): HighlightResult { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize HighlightResultOption + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize HighlightResultOption (error: ${e.message})") + } + } + + // deserialize List + if (tree is JsonArray) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize List (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/HighlightResultOption.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/HighlightResultOption.kt new file mode 100644 index 0000000000..6ac389a6df --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/HighlightResultOption.kt @@ -0,0 +1,28 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Show highlighted section and words matched on a query. + * + * @param `value` Markup text with occurrences highlighted. + * @param matchLevel + * @param matchedWords List of words from the query that matched the object. + * @param fullyHighlighted Whether the entire attribute value is highlighted. + */ +@Serializable +public data class HighlightResultOption( + + /** Markup text with occurrences highlighted. */ + @SerialName(value = "value") val `value`: String, + + @SerialName(value = "matchLevel") val matchLevel: MatchLevel, + + /** List of words from the query that matched the object. */ + @SerialName(value = "matchedWords") val matchedWords: List, + + /** Whether the entire attribute value is highlighted. */ + @SerialName(value = "fullyHighlighted") val fullyHighlighted: Boolean? = null, +) : HighlightResult diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/IgnorePlurals.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/IgnorePlurals.kt new file mode 100644 index 0000000000..9f9c15290e --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/IgnorePlurals.kt @@ -0,0 +1,83 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Treats singular, plurals, and other forms of declensions as matching terms. ignorePlurals is used in conjunction with the queryLanguages setting. list: language ISO codes for which ignoring plurals should be enabled. This list will override any values that you may have set in queryLanguages. true: enables the ignore plurals functionality, where singulars and plurals are considered equivalent (foot = feet). The languages supported here are either every language (this is the default, see list of languages below), or those set by queryLanguages. false: disables ignore plurals, where singulars and plurals are not considered the same for matching purposes (foot will not find feet). + */ +@Serializable(IgnorePluralsSerializer::class) +public sealed interface IgnorePlurals { + + public data class BooleanWrapper(val value: Boolean) : IgnorePlurals + + public data class ListOfStringWrapper(val value: List) : IgnorePlurals + + public companion object { + + /** + * IgnorePlurals as Boolean + * + */ + public fun Boolean( + value: Boolean, + ): BooleanWrapper = BooleanWrapper( + value = value, + ) + + /** + * IgnorePlurals as List + * + */ + public fun ListOfString( + value: List, + ): ListOfStringWrapper = ListOfStringWrapper( + value = value, + ) + } +} + +internal class IgnorePluralsSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("IgnorePlurals") + + override fun serialize(encoder: Encoder, value: IgnorePlurals) { + when (value) { + is IgnorePlurals.BooleanWrapper -> Boolean.serializer().serialize(encoder, value.value) + is IgnorePlurals.ListOfStringWrapper -> ListSerializer(String.serializer()).serialize(encoder, value.value) + } + } + + override fun deserialize(decoder: Decoder): IgnorePlurals { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize Boolean + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize Boolean (error: ${e.message})") + } + } + + // deserialize List + if (tree is JsonArray) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize List (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/IndexSettingsAsSearchParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/IndexSettingsAsSearchParams.kt new file mode 100644 index 0000000000..8516bddae7 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/IndexSettingsAsSearchParams.kt @@ -0,0 +1,183 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * IndexSettingsAsSearchParams + * + * @param attributesForFaceting The complete list of attributes that will be used for faceting. + * @param attributesToRetrieve This parameter controls which attributes to retrieve and which not to retrieve. + * @param restrictSearchableAttributes Restricts a given query to look in only a subset of your searchable attributes. + * @param ranking Controls how Algolia should sort your results. + * @param customRanking Specifies the custom ranking criterion. + * @param relevancyStrictness Controls the relevancy threshold below which less relevant results aren't included in the results. + * @param attributesToHighlight List of attributes to highlight. + * @param attributesToSnippet List of attributes to snippet, with an optional maximum number of words to snippet. + * @param highlightPreTag The HTML string to insert before the highlighted parts in all highlight and snippet results. + * @param highlightPostTag The HTML string to insert after the highlighted parts in all highlight and snippet results. + * @param snippetEllipsisText String used as an ellipsis indicator when a snippet is truncated. + * @param restrictHighlightAndSnippetArrays Restrict highlighting and snippeting to items that matched the query. + * @param hitsPerPage Set the number of hits per page. + * @param minWordSizefor1Typo Minimum number of characters a word in the query string must contain to accept matches with 1 typo. + * @param minWordSizefor2Typos Minimum number of characters a word in the query string must contain to accept matches with 2 typos. + * @param typoTolerance + * @param allowTyposOnNumericTokens Whether to allow typos on numbers (\"numeric tokens\") in the query string. + * @param disableTypoToleranceOnAttributes List of attributes on which you want to disable typo tolerance. + * @param ignorePlurals + * @param removeStopWords + * @param keepDiacriticsOnCharacters List of characters that the engine shouldn't automatically normalize. + * @param queryLanguages Sets the languages to be used by language-specific settings and functionalities such as ignorePlurals, removeStopWords, and CJK word-detection. + * @param decompoundQuery Splits compound words into their composing atoms in the query. + * @param enableRules Whether Rules should be globally enabled. + * @param enablePersonalization Enable the Personalization feature. + * @param queryType + * @param removeWordsIfNoResults + * @param mode + * @param semanticSearch + * @param advancedSyntax Enables the advanced query syntax. + * @param optionalWords A list of words that should be considered as optional when found in the query. + * @param disableExactOnAttributes List of attributes on which you want to disable the exact ranking criterion. + * @param exactOnSingleWordQuery + * @param alternativesAsExact List of alternatives that should be considered an exact match by the exact ranking criterion. + * @param advancedSyntaxFeatures Allows you to specify which advanced syntax features are active when ‘advancedSyntax' is enabled. + * @param explain Enriches the API’s response with meta-information as to how the query was processed. + * @param distinct + * @param attributeForDistinct Name of the de-duplication attribute to be used with the distinct feature. + * @param synonyms Whether to take into account an index's synonyms for a particular search. + * @param replaceSynonymsInHighlight Whether to highlight and snippet the original word that matches the synonym or the synonym itself. + * @param minProximity Precision of the proximity ranking criterion. + * @param responseFields Choose which fields to return in the API response. This parameters applies to search and browse queries. + * @param maxFacetHits Maximum number of facet hits to return during a search for facet values. For performance reasons, the maximum allowed number of returned values is 100. + * @param attributeCriteriaComputedByMinProximity When attribute is ranked above proximity in your ranking formula, proximity is used to select which searchable attribute is matched in the attribute ranking stage. + * @param renderingContent + */ +@Serializable +public data class IndexSettingsAsSearchParams( + + /** The complete list of attributes that will be used for faceting. */ + @SerialName(value = "attributesForFaceting") val attributesForFaceting: List? = null, + + /** This parameter controls which attributes to retrieve and which not to retrieve. */ + @SerialName(value = "attributesToRetrieve") val attributesToRetrieve: List? = null, + + /** Restricts a given query to look in only a subset of your searchable attributes. */ + @SerialName(value = "restrictSearchableAttributes") val restrictSearchableAttributes: List? = null, + + /** Controls how Algolia should sort your results. */ + @SerialName(value = "ranking") val ranking: List? = null, + + /** Specifies the custom ranking criterion. */ + @SerialName(value = "customRanking") val customRanking: List? = null, + + /** Controls the relevancy threshold below which less relevant results aren't included in the results. */ + @SerialName(value = "relevancyStrictness") val relevancyStrictness: Int? = null, + + /** List of attributes to highlight. */ + @SerialName(value = "attributesToHighlight") val attributesToHighlight: List? = null, + + /** List of attributes to snippet, with an optional maximum number of words to snippet. */ + @SerialName(value = "attributesToSnippet") val attributesToSnippet: List? = null, + + /** The HTML string to insert before the highlighted parts in all highlight and snippet results. */ + @SerialName(value = "highlightPreTag") val highlightPreTag: String? = null, + + /** The HTML string to insert after the highlighted parts in all highlight and snippet results. */ + @SerialName(value = "highlightPostTag") val highlightPostTag: String? = null, + + /** String used as an ellipsis indicator when a snippet is truncated. */ + @SerialName(value = "snippetEllipsisText") val snippetEllipsisText: String? = null, + + /** Restrict highlighting and snippeting to items that matched the query. */ + @SerialName(value = "restrictHighlightAndSnippetArrays") val restrictHighlightAndSnippetArrays: Boolean? = null, + + /** Set the number of hits per page. */ + @SerialName(value = "hitsPerPage") val hitsPerPage: Int? = null, + + /** Minimum number of characters a word in the query string must contain to accept matches with 1 typo. */ + @SerialName(value = "minWordSizefor1Typo") val minWordSizefor1Typo: Int? = null, + + /** Minimum number of characters a word in the query string must contain to accept matches with 2 typos. */ + @SerialName(value = "minWordSizefor2Typos") val minWordSizefor2Typos: Int? = null, + + @SerialName(value = "typoTolerance") val typoTolerance: TypoTolerance? = null, + + /** Whether to allow typos on numbers (\"numeric tokens\") in the query string. */ + @SerialName(value = "allowTyposOnNumericTokens") val allowTyposOnNumericTokens: Boolean? = null, + + /** List of attributes on which you want to disable typo tolerance. */ + @SerialName(value = "disableTypoToleranceOnAttributes") val disableTypoToleranceOnAttributes: List? = null, + + @SerialName(value = "ignorePlurals") val ignorePlurals: IgnorePlurals? = null, + + @SerialName(value = "removeStopWords") val removeStopWords: RemoveStopWords? = null, + + /** List of characters that the engine shouldn't automatically normalize. */ + @SerialName(value = "keepDiacriticsOnCharacters") val keepDiacriticsOnCharacters: String? = null, + + /** Sets the languages to be used by language-specific settings and functionalities such as ignorePlurals, removeStopWords, and CJK word-detection. */ + @SerialName(value = "queryLanguages") val queryLanguages: List? = null, + + /** Splits compound words into their composing atoms in the query. */ + @SerialName(value = "decompoundQuery") val decompoundQuery: Boolean? = null, + + /** Whether Rules should be globally enabled. */ + @SerialName(value = "enableRules") val enableRules: Boolean? = null, + + /** Enable the Personalization feature. */ + @SerialName(value = "enablePersonalization") val enablePersonalization: Boolean? = null, + + @SerialName(value = "queryType") val queryType: QueryType? = null, + + @SerialName(value = "removeWordsIfNoResults") val removeWordsIfNoResults: RemoveWordsIfNoResults? = null, + + @SerialName(value = "mode") val mode: Mode? = null, + + @SerialName(value = "semanticSearch") val semanticSearch: IndexSettingsAsSearchParamsSemanticSearch? = null, + + /** Enables the advanced query syntax. */ + @SerialName(value = "advancedSyntax") val advancedSyntax: Boolean? = null, + + /** A list of words that should be considered as optional when found in the query. */ + @SerialName(value = "optionalWords") val optionalWords: List? = null, + + /** List of attributes on which you want to disable the exact ranking criterion. */ + @SerialName(value = "disableExactOnAttributes") val disableExactOnAttributes: List? = null, + + @SerialName(value = "exactOnSingleWordQuery") val exactOnSingleWordQuery: ExactOnSingleWordQuery? = null, + + /** List of alternatives that should be considered an exact match by the exact ranking criterion. */ + @SerialName(value = "alternativesAsExact") val alternativesAsExact: List? = null, + + /** Allows you to specify which advanced syntax features are active when ‘advancedSyntax' is enabled. */ + @SerialName(value = "advancedSyntaxFeatures") val advancedSyntaxFeatures: List? = null, + + /** Enriches the API’s response with meta-information as to how the query was processed. */ + @SerialName(value = "explain") val explain: List? = null, + + @SerialName(value = "distinct") val distinct: Distinct? = null, + + /** Name of the de-duplication attribute to be used with the distinct feature. */ + @SerialName(value = "attributeForDistinct") val attributeForDistinct: String? = null, + + /** Whether to take into account an index's synonyms for a particular search. */ + @SerialName(value = "synonyms") val synonyms: Boolean? = null, + + /** Whether to highlight and snippet the original word that matches the synonym or the synonym itself. */ + @SerialName(value = "replaceSynonymsInHighlight") val replaceSynonymsInHighlight: Boolean? = null, + + /** Precision of the proximity ranking criterion. */ + @SerialName(value = "minProximity") val minProximity: Int? = null, + + /** Choose which fields to return in the API response. This parameters applies to search and browse queries. */ + @SerialName(value = "responseFields") val responseFields: List? = null, + + /** Maximum number of facet hits to return during a search for facet values. For performance reasons, the maximum allowed number of returned values is 100. */ + @SerialName(value = "maxFacetHits") val maxFacetHits: Int? = null, + + /** When attribute is ranked above proximity in your ranking formula, proximity is used to select which searchable attribute is matched in the attribute ranking stage. */ + @SerialName(value = "attributeCriteriaComputedByMinProximity") val attributeCriteriaComputedByMinProximity: Boolean? = null, + + @SerialName(value = "renderingContent") val renderingContent: RenderingContent? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/IndexSettingsAsSearchParamsSemanticSearch.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/IndexSettingsAsSearchParamsSemanticSearch.kt new file mode 100644 index 0000000000..3b8b05055b --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/IndexSettingsAsSearchParamsSemanticSearch.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The settings relevant for configuration of the semantic search engine. These settings are only used when the mode is set to 'neuralSearch'. + * + * @param eventSources When null, the current index / replica group will be used as the event source. + */ +@Serializable +public data class IndexSettingsAsSearchParamsSemanticSearch( + + /** When null, the current index / replica group will be used as the event source. */ + @SerialName(value = "eventSources") val eventSources: List? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/MatchLevel.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/MatchLevel.kt new file mode 100644 index 0000000000..e4f79c1cd0 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/MatchLevel.kt @@ -0,0 +1,22 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* + +/** + * Indicates how well the attribute matched the search query. + */ +@Serializable +public enum class MatchLevel(public val value: kotlin.String) { + + @SerialName(value = "none") + None("none"), + + @SerialName(value = "partial") + Partial("partial"), + + @SerialName(value = "full") + Full("full"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/MatchedGeoLocation.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/MatchedGeoLocation.kt new file mode 100644 index 0000000000..bd86b554ff --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/MatchedGeoLocation.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * MatchedGeoLocation + * + * @param lat Latitude of the matched location. + * @param lng Longitude of the matched location. + * @param distance Distance between the matched location and the search location (in meters). + */ +@Serializable +public data class MatchedGeoLocation( + + /** Latitude of the matched location. */ + @SerialName(value = "lat") val lat: Double? = null, + + /** Longitude of the matched location. */ + @SerialName(value = "lng") val lng: Double? = null, + + /** Distance between the matched location and the search location (in meters). */ + @SerialName(value = "distance") val distance: Int? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/MixedSearchFilters.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/MixedSearchFilters.kt new file mode 100644 index 0000000000..831a9c3187 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/MixedSearchFilters.kt @@ -0,0 +1,83 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * MixedSearchFilters + */ +@Serializable(MixedSearchFiltersSerializer::class) +public sealed interface MixedSearchFilters { + + public data class ListOfStringWrapper(val value: List) : MixedSearchFilters + + public data class StringWrapper(val value: String) : MixedSearchFilters + + public companion object { + + /** + * MixedSearchFilters as List + * + */ + public fun ListOfString( + value: List, + ): ListOfStringWrapper = ListOfStringWrapper( + value = value, + ) + + /** + * MixedSearchFilters as String + * + */ + public fun String( + value: String, + ): StringWrapper = StringWrapper( + value = value, + ) + } +} + +internal class MixedSearchFiltersSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("MixedSearchFilters") + + override fun serialize(encoder: Encoder, value: MixedSearchFilters) { + when (value) { + is MixedSearchFilters.ListOfStringWrapper -> ListSerializer(String.serializer()).serialize(encoder, value.value) + is MixedSearchFilters.StringWrapper -> String.serializer().serialize(encoder, value.value) + } + } + + override fun deserialize(decoder: Decoder): MixedSearchFilters { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize List + if (tree is JsonArray) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize List (error: ${e.message})") + } + } + + // deserialize String + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize String (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/Mode.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/Mode.kt new file mode 100644 index 0000000000..3ef2efd83d --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/Mode.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* + +/** + * The search mode that the index will use to query for results. + */ +@Serializable +public enum class Mode(public val value: kotlin.String) { + + @SerialName(value = "neuralSearch") + NeuralSearch("neuralSearch"), + + @SerialName(value = "keywordSearch") + KeywordSearch("keywordSearch"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/NumericFilters.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/NumericFilters.kt new file mode 100644 index 0000000000..fcaefe651c --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/NumericFilters.kt @@ -0,0 +1,83 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Filter on numeric attributes. + */ +@Serializable(NumericFiltersSerializer::class) +public sealed interface NumericFilters { + + public data class ListOfMixedSearchFiltersWrapper(val value: List) : NumericFilters + + public data class StringWrapper(val value: String) : NumericFilters + + public companion object { + + /** + * NumericFilters as List + * + */ + public fun ListOfMixedSearchFilters( + value: List, + ): ListOfMixedSearchFiltersWrapper = ListOfMixedSearchFiltersWrapper( + value = value, + ) + + /** + * NumericFilters as String + * + */ + public fun String( + value: String, + ): StringWrapper = StringWrapper( + value = value, + ) + } +} + +internal class NumericFiltersSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("NumericFilters") + + override fun serialize(encoder: Encoder, value: NumericFilters) { + when (value) { + is NumericFilters.ListOfMixedSearchFiltersWrapper -> ListSerializer(MixedSearchFilters.serializer()).serialize(encoder, value.value) + is NumericFilters.StringWrapper -> String.serializer().serialize(encoder, value.value) + } + } + + override fun deserialize(decoder: Decoder): NumericFilters { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize List + if (tree is JsonArray) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize List (error: ${e.message})") + } + } + + // deserialize String + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize String (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/OptionalFilters.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/OptionalFilters.kt new file mode 100644 index 0000000000..1298732340 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/OptionalFilters.kt @@ -0,0 +1,83 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Create filters for ranking purposes, where records that match the filter are ranked higher, or lower in the case of a negative optional filter. + */ +@Serializable(OptionalFiltersSerializer::class) +public sealed interface OptionalFilters { + + public data class ListOfMixedSearchFiltersWrapper(val value: List) : OptionalFilters + + public data class StringWrapper(val value: String) : OptionalFilters + + public companion object { + + /** + * OptionalFilters as List + * + */ + public fun ListOfMixedSearchFilters( + value: List, + ): ListOfMixedSearchFiltersWrapper = ListOfMixedSearchFiltersWrapper( + value = value, + ) + + /** + * OptionalFilters as String + * + */ + public fun String( + value: String, + ): StringWrapper = StringWrapper( + value = value, + ) + } +} + +internal class OptionalFiltersSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("OptionalFilters") + + override fun serialize(encoder: Encoder, value: OptionalFilters) { + when (value) { + is OptionalFilters.ListOfMixedSearchFiltersWrapper -> ListSerializer(MixedSearchFilters.serializer()).serialize(encoder, value.value) + is OptionalFilters.StringWrapper -> String.serializer().serialize(encoder, value.value) + } + } + + override fun deserialize(decoder: Decoder): OptionalFilters { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize List + if (tree is JsonArray) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize List (error: ${e.message})") + } + } + + // deserialize String + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize String (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/Personalization.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/Personalization.kt new file mode 100644 index 0000000000..bfc15488ad --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/Personalization.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Personalization + * + * @param filtersScore The score of the filters. + * @param rankingScore The score of the ranking. + * @param score The score of the event. + */ +@Serializable +public data class Personalization( + + /** The score of the filters. */ + @SerialName(value = "filtersScore") val filtersScore: Int? = null, + + /** The score of the ranking. */ + @SerialName(value = "rankingScore") val rankingScore: Int? = null, + + /** The score of the event. */ + @SerialName(value = "score") val score: Int? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/QueryType.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/QueryType.kt new file mode 100644 index 0000000000..98adefd49e --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/QueryType.kt @@ -0,0 +1,22 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* + +/** + * Controls if and how query words are interpreted as prefixes. + */ +@Serializable +public enum class QueryType(public val value: kotlin.String) { + + @SerialName(value = "prefixLast") + PrefixLast("prefixLast"), + + @SerialName(value = "prefixAll") + PrefixAll("prefixAll"), + + @SerialName(value = "prefixNone") + PrefixNone("prefixNone"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RankingInfo.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RankingInfo.kt new file mode 100644 index 0000000000..694ff5724e --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RankingInfo.kt @@ -0,0 +1,63 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * RankingInfo + * + * @param filters This field is reserved for advanced usage. + * @param firstMatchedWord Position of the most important matched attribute in the attributes to index list. + * @param geoDistance Distance between the geo location in the search query and the best matching geo location in the record, divided by the geo precision (in meters). + * @param nbExactWords Number of exactly matched words. + * @param nbTypos Number of typos encountered when matching the record. + * @param promoted Present and set to true if a Rule promoted the hit. + * @param userScore Custom ranking for the object, expressed as a single integer value. + * @param words Number of matched words, including prefixes and typos. + * @param geoPrecision Precision used when computing the geo distance, in meters. + * @param matchedGeoLocation + * @param personalization + * @param proximityDistance When the query contains more than one word, the sum of the distances between matched words (in meters). + * @param promotedByReRanking Wether the record are promoted by the re-ranking strategy. + */ +@Serializable +public data class RankingInfo( + + /** This field is reserved for advanced usage. */ + @SerialName(value = "filters") val filters: Int, + + /** Position of the most important matched attribute in the attributes to index list. */ + @SerialName(value = "firstMatchedWord") val firstMatchedWord: Int, + + /** Distance between the geo location in the search query and the best matching geo location in the record, divided by the geo precision (in meters). */ + @SerialName(value = "geoDistance") val geoDistance: Int, + + /** Number of exactly matched words. */ + @SerialName(value = "nbExactWords") val nbExactWords: Int, + + /** Number of typos encountered when matching the record. */ + @SerialName(value = "nbTypos") val nbTypos: Int, + + /** Present and set to true if a Rule promoted the hit. */ + @SerialName(value = "promoted") val promoted: Boolean, + + /** Custom ranking for the object, expressed as a single integer value. */ + @SerialName(value = "userScore") val userScore: Int, + + /** Number of matched words, including prefixes and typos. */ + @SerialName(value = "words") val words: Int, + + /** Precision used when computing the geo distance, in meters. */ + @SerialName(value = "geoPrecision") val geoPrecision: Int? = null, + + @SerialName(value = "matchedGeoLocation") val matchedGeoLocation: MatchedGeoLocation? = null, + + @SerialName(value = "personalization") val personalization: Personalization? = null, + + /** When the query contains more than one word, the sum of the distances between matched words (in meters). */ + @SerialName(value = "proximityDistance") val proximityDistance: Int? = null, + + /** Wether the record are promoted by the re-ranking strategy. */ + @SerialName(value = "promotedByReRanking") val promotedByReRanking: Boolean? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/ReRankingApplyFilter.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/ReRankingApplyFilter.kt new file mode 100644 index 0000000000..a4197e882a --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/ReRankingApplyFilter.kt @@ -0,0 +1,83 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * When Dynamic Re-Ranking is enabled, only records that match these filters will be impacted by Dynamic Re-Ranking. + */ +@Serializable(ReRankingApplyFilterSerializer::class) +public sealed interface ReRankingApplyFilter { + + public data class ListOfMixedSearchFiltersWrapper(val value: List) : ReRankingApplyFilter + + public data class StringWrapper(val value: String) : ReRankingApplyFilter + + public companion object { + + /** + * ReRankingApplyFilter as List + * + */ + public fun ListOfMixedSearchFilters( + value: List, + ): ListOfMixedSearchFiltersWrapper = ListOfMixedSearchFiltersWrapper( + value = value, + ) + + /** + * ReRankingApplyFilter as String + * + */ + public fun String( + value: String, + ): StringWrapper = StringWrapper( + value = value, + ) + } +} + +internal class ReRankingApplyFilterSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("ReRankingApplyFilter") + + override fun serialize(encoder: Encoder, value: ReRankingApplyFilter) { + when (value) { + is ReRankingApplyFilter.ListOfMixedSearchFiltersWrapper -> ListSerializer(MixedSearchFilters.serializer()).serialize(encoder, value.value) + is ReRankingApplyFilter.StringWrapper -> String.serializer().serialize(encoder, value.value) + } + } + + override fun deserialize(decoder: Decoder): ReRankingApplyFilter { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize List + if (tree is JsonArray) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize List (error: ${e.message})") + } + } + + // deserialize String + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize String (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RecommendHit.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RecommendHit.kt new file mode 100644 index 0000000000..dcaeb4a720 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RecommendHit.kt @@ -0,0 +1,80 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * A Recommend hit. + * + * @param objectID Unique identifier of the object. + * @param score The recommendation score. + * @param highlightResult Show highlighted section and words matched on a query. + * @param snippetResult Snippeted attributes show parts of the matched attributes. Only returned when attributesToSnippet is non-empty. + * @param rankingInfo + * @param distinctSeqID + */ +@Serializable(RecommendHitSerializer::class) +public data class RecommendHit( + + /** Unique identifier of the object. */ + val objectID: String, + + /** The recommendation score. */ + val score: Double, + + /** Show highlighted section and words matched on a query. */ + val highlightResult: Map? = null, + + /** Snippeted attributes show parts of the matched attributes. Only returned when attributesToSnippet is non-empty. */ + val snippetResult: Map? = null, + + val rankingInfo: RankingInfo? = null, + + val distinctSeqID: Int? = null, + + val additionalProperties: Map? = null, +) + +internal object RecommendHitSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("RecommendHit") { + element("objectID") + element("_score") + element>("_highlightResult") + element>("_snippetResult") + element("_rankingInfo") + element("_distinctSeqID") + } + + override fun deserialize(decoder: Decoder): RecommendHit { + val input = decoder.asJsonDecoder() + val tree = input.decodeJsonObject() + return RecommendHit( + objectID = tree.getValue("objectID").let { input.json.decodeFromJsonElement(it) }, + score = tree.getValue("_score").let { input.json.decodeFromJsonElement(it) }, + highlightResult = tree["_highlightResult"]?.let { input.json.decodeFromJsonElement(it) }, + snippetResult = tree["_snippetResult"]?.let { input.json.decodeFromJsonElement(it) }, + rankingInfo = tree["_rankingInfo"]?.let { input.json.decodeFromJsonElement(it) }, + distinctSeqID = tree["_distinctSeqID"]?.let { input.json.decodeFromJsonElement(it) }, + additionalProperties = tree.filterKeys { it !in descriptor.elementNames }, + ) + } + + override fun serialize(encoder: Encoder, value: RecommendHit) { + val output = encoder.asJsonEncoder() + val json = buildJsonObject { + put("objectID", output.json.encodeToJsonElement(value.objectID)) + put("_score", output.json.encodeToJsonElement(value.score)) + value.highlightResult?.let { put("_highlightResult", output.json.encodeToJsonElement(it)) } + value.snippetResult?.let { put("_snippetResult", output.json.encodeToJsonElement(it)) } + value.rankingInfo?.let { put("_rankingInfo", output.json.encodeToJsonElement(it)) } + value.distinctSeqID?.let { put("_distinctSeqID", output.json.encodeToJsonElement(it)) } + value.additionalProperties?.onEach { (key, element) -> put(key, element) } + } + (encoder as JsonEncoder).encodeJsonElement(json) + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RecommendHits.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RecommendHits.kt new file mode 100644 index 0000000000..a36e4da150 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RecommendHits.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * RecommendHits + * + * @param hits + */ +@Serializable +public data class RecommendHits( + + @SerialName(value = "hits") val hits: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RecommendationModels.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RecommendationModels.kt new file mode 100644 index 0000000000..3d58c4bab5 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RecommendationModels.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* + +/** + * The recommendation model to use. + */ +@Serializable +public enum class RecommendationModels(public val value: kotlin.String) { + + @SerialName(value = "related-products") + RelatedProducts("related-products"), + + @SerialName(value = "bought-together") + BoughtTogether("bought-together"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RecommendationRequest.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RecommendationRequest.kt new file mode 100644 index 0000000000..15869c64c5 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RecommendationRequest.kt @@ -0,0 +1,38 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * RecommendationRequest + * + * @param model + * @param objectID Unique identifier of the object. + * @param indexName The Algolia index name. + * @param threshold The threshold to use when filtering recommendations by their score. + * @param maxRecommendations The max number of recommendations to retrieve. If it's set to 0, all the recommendations of the objectID may be returned. + * @param queryParameters + * @param fallbackParameters + */ +@Serializable +public data class RecommendationRequest( + + @SerialName(value = "model") val model: RecommendationModels, + + /** Unique identifier of the object. */ + @SerialName(value = "objectID") val objectID: String, + + /** The Algolia index name. */ + @SerialName(value = "indexName") val indexName: String, + + /** The threshold to use when filtering recommendations by their score. */ + @SerialName(value = "threshold") val threshold: Int, + + /** The max number of recommendations to retrieve. If it's set to 0, all the recommendations of the objectID may be returned. */ + @SerialName(value = "maxRecommendations") val maxRecommendations: Int? = null, + + @SerialName(value = "queryParameters") val queryParameters: SearchParamsObject? = null, + + @SerialName(value = "fallbackParameters") val fallbackParameters: SearchParamsObject? = null, +) : RecommendationsRequest diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RecommendationsRequest.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RecommendationsRequest.kt new file mode 100644 index 0000000000..27ca011b00 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RecommendationsRequest.kt @@ -0,0 +1,120 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * RecommendationsRequest + */ +@Serializable(RecommendationsRequestSerializer::class) +public sealed interface RecommendationsRequest { + + public companion object { + + /** + * RecommendationRequest + * + * @param model + * @param objectID Unique identifier of the object. + * @param indexName The Algolia index name. + * @param threshold The threshold to use when filtering recommendations by their score. + * @param maxRecommendations The max number of recommendations to retrieve. If it's set to 0, all the recommendations of the objectID may be returned. + * @param queryParameters + * @param fallbackParameters + */ + public fun RecommendationRequest( + model: RecommendationModels, + objectID: String, + indexName: String, + threshold: Int, + maxRecommendations: Int? = null, + queryParameters: SearchParamsObject? = null, + fallbackParameters: SearchParamsObject? = null, + ): RecommendationRequest = com.algolia.client.model.recommend.RecommendationRequest( + model = model, + objectID = objectID, + indexName = indexName, + threshold = threshold, + maxRecommendations = maxRecommendations, + queryParameters = queryParameters, + fallbackParameters = fallbackParameters, + ) + + /** + * TrendingRequest + * + * @param model + * @param indexName The Algolia index name. + * @param threshold The threshold to use when filtering recommendations by their score. + * @param facetName The facet name to use for trending models. + * @param facetValue The facet value to use for trending models. + * @param maxRecommendations The max number of recommendations to retrieve. If it's set to 0, all the recommendations of the objectID may be returned. + * @param queryParameters + * @param fallbackParameters + */ + public fun TrendingRequest( + model: TrendingModels, + indexName: String, + threshold: Int, + facetName: String? = null, + facetValue: String? = null, + maxRecommendations: Int? = null, + queryParameters: SearchParamsObject? = null, + fallbackParameters: SearchParamsObject? = null, + ): TrendingRequest = com.algolia.client.model.recommend.TrendingRequest( + model = model, + indexName = indexName, + threshold = threshold, + facetName = facetName, + facetValue = facetValue, + maxRecommendations = maxRecommendations, + queryParameters = queryParameters, + fallbackParameters = fallbackParameters, + ) + } +} + +internal class RecommendationsRequestSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("RecommendationsRequest") + + override fun serialize(encoder: Encoder, value: RecommendationsRequest) { + when (value) { + is RecommendationRequest -> RecommendationRequest.serializer().serialize(encoder, value) + is TrendingRequest -> TrendingRequest.serializer().serialize(encoder, value) + } + } + + override fun deserialize(decoder: Decoder): RecommendationsRequest { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize RecommendationRequest + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize RecommendationRequest (error: ${e.message})") + } + } + + // deserialize TrendingRequest + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize TrendingRequest (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RecommendationsResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RecommendationsResponse.kt new file mode 100644 index 0000000000..650c45e4dc --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RecommendationsResponse.kt @@ -0,0 +1,118 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * RecommendationsResponse + * + * @param exhaustiveNbHits Indicate if the nbHits count was exhaustive or approximate. + * @param hitsPerPage Set the number of hits per page. + * @param nbHits Number of hits that the search query matched. + * @param nbPages Number of pages available for the current query. + * @param page Specify the page to retrieve. + * @param params A url-encoded string of all search parameters. + * @param processingTimeMS Time the server took to process the request, in milliseconds. + * @param query The text to search in the index. + * @param hits + * @param abTestID If a search encounters an index that is being A/B tested, abTestID reports the ongoing A/B test ID. + * @param abTestVariantID If a search encounters an index that is being A/B tested, abTestVariantID reports the variant ID of the index used (starting at 1). + * @param aroundLatLng The computed geo location. + * @param automaticRadius The automatically computed radius. For legacy reasons, this parameter is a string and not an integer. + * @param exhaustiveFacetsCount Whether the facet count is exhaustive or approximate. + * @param exhaustiveTypo Indicate if the typo-tolerance search was exhaustive or approximate (only included when typo-tolerance is enabled). + * @param facets A mapping of each facet name to the corresponding facet counts. + * @param facetsStats Statistics for numerical facets. + * @param index Index name used for the query. + * @param indexUsed Index name used for the query. In the case of an A/B test, the targeted index isn't always the index used by the query. + * @param message Used to return warnings about the query. + * @param nbSortedHits The number of hits selected and sorted by the relevant sort algorithm. + * @param redirect + * @param parsedQuery The query string that will be searched, after normalization. + * @param queryAfterRemoval A markup text indicating which parts of the original query have been removed in order to retrieve a non-empty result set. + * @param serverUsed Actual host name of the server that processed the request. + * @param userData Lets you store custom data in your indices. + * @param renderingContent + */ +@Serializable +public data class RecommendationsResponse( + + /** Indicate if the nbHits count was exhaustive or approximate. */ + @SerialName(value = "exhaustiveNbHits") val exhaustiveNbHits: Boolean, + + /** Set the number of hits per page. */ + @SerialName(value = "hitsPerPage") val hitsPerPage: Int, + + /** Number of hits that the search query matched. */ + @SerialName(value = "nbHits") val nbHits: Int, + + /** Number of pages available for the current query. */ + @SerialName(value = "nbPages") val nbPages: Int, + + /** Specify the page to retrieve. */ + @SerialName(value = "page") val page: Int, + + /** A url-encoded string of all search parameters. */ + @SerialName(value = "params") val params: String, + + /** Time the server took to process the request, in milliseconds. */ + @SerialName(value = "processingTimeMS") val processingTimeMS: Int, + + /** The text to search in the index. */ + @SerialName(value = "query") val query: String, + + @SerialName(value = "hits") val hits: List, + + /** If a search encounters an index that is being A/B tested, abTestID reports the ongoing A/B test ID. */ + @SerialName(value = "abTestID") val abTestID: Int? = null, + + /** If a search encounters an index that is being A/B tested, abTestVariantID reports the variant ID of the index used (starting at 1). */ + @SerialName(value = "abTestVariantID") val abTestVariantID: Int? = null, + + /** The computed geo location. */ + @SerialName(value = "aroundLatLng") val aroundLatLng: String? = null, + + /** The automatically computed radius. For legacy reasons, this parameter is a string and not an integer. */ + @SerialName(value = "automaticRadius") val automaticRadius: String? = null, + + /** Whether the facet count is exhaustive or approximate. */ + @SerialName(value = "exhaustiveFacetsCount") val exhaustiveFacetsCount: Boolean? = null, + + /** Indicate if the typo-tolerance search was exhaustive or approximate (only included when typo-tolerance is enabled). */ + @SerialName(value = "exhaustiveTypo") val exhaustiveTypo: Boolean? = null, + + /** A mapping of each facet name to the corresponding facet counts. */ + @SerialName(value = "facets") val facets: Map>? = null, + + /** Statistics for numerical facets. */ + @SerialName(value = "facets_stats") val facetsStats: Map? = null, + + /** Index name used for the query. */ + @SerialName(value = "index") val index: String? = null, + + /** Index name used for the query. In the case of an A/B test, the targeted index isn't always the index used by the query. */ + @SerialName(value = "indexUsed") val indexUsed: String? = null, + + /** Used to return warnings about the query. */ + @SerialName(value = "message") val message: String? = null, + + /** The number of hits selected and sorted by the relevant sort algorithm. */ + @SerialName(value = "nbSortedHits") val nbSortedHits: Int? = null, + + @SerialName(value = "redirect") val redirect: BaseSearchResponseRedirect? = null, + + /** The query string that will be searched, after normalization. */ + @SerialName(value = "parsedQuery") val parsedQuery: String? = null, + + /** A markup text indicating which parts of the original query have been removed in order to retrieve a non-empty result set. */ + @SerialName(value = "queryAfterRemoval") val queryAfterRemoval: String? = null, + + /** Actual host name of the server that processed the request. */ + @SerialName(value = "serverUsed") val serverUsed: String? = null, + + /** Lets you store custom data in your indices. */ + @SerialName(value = "userData") val userData: JsonObject? = null, + + @SerialName(value = "renderingContent") val renderingContent: RenderingContent? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RedirectRuleIndexMetadata.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RedirectRuleIndexMetadata.kt new file mode 100644 index 0000000000..fa233b2d05 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RedirectRuleIndexMetadata.kt @@ -0,0 +1,32 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * RedirectRuleIndexMetadata + * + * @param source Source index for the redirect rule. + * @param dest Destination index for the redirect rule. + * @param reason Reason for the redirect rule. + * @param succeed Status for the redirect rule. + * @param `data` + */ +@Serializable +public data class RedirectRuleIndexMetadata( + + /** Source index for the redirect rule. */ + @SerialName(value = "source") val source: String, + + /** Destination index for the redirect rule. */ + @SerialName(value = "dest") val dest: String, + + /** Reason for the redirect rule. */ + @SerialName(value = "reason") val reason: String, + + /** Status for the redirect rule. */ + @SerialName(value = "succeed") val succeed: Boolean, + + @SerialName(value = "data") val `data`: RedirectRuleIndexMetadataData, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RedirectRuleIndexMetadataData.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RedirectRuleIndexMetadataData.kt new file mode 100644 index 0000000000..52e04dca56 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RedirectRuleIndexMetadataData.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Data for the redirect rule. + * + * @param ruleObjectID + */ +@Serializable +public data class RedirectRuleIndexMetadataData( + + @SerialName(value = "ruleObjectID") val ruleObjectID: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RemoveStopWords.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RemoveStopWords.kt new file mode 100644 index 0000000000..99eb25ff50 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RemoveStopWords.kt @@ -0,0 +1,83 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Removes stop (common) words from the query before executing it. removeStopWords is used in conjunction with the queryLanguages setting. list: language ISO codes for which ignoring plurals should be enabled. This list will override any values that you may have set in queryLanguages. true: enables the stop word functionality, ensuring that stop words are removed from consideration in a search. The languages supported here are either every language, or those set by queryLanguages. false: disables stop word functionality, allowing stop words to be taken into account in a search. + */ +@Serializable(RemoveStopWordsSerializer::class) +public sealed interface RemoveStopWords { + + public data class BooleanWrapper(val value: Boolean) : RemoveStopWords + + public data class ListOfStringWrapper(val value: List) : RemoveStopWords + + public companion object { + + /** + * RemoveStopWords as Boolean + * + */ + public fun Boolean( + value: Boolean, + ): BooleanWrapper = BooleanWrapper( + value = value, + ) + + /** + * RemoveStopWords as List + * + */ + public fun ListOfString( + value: List, + ): ListOfStringWrapper = ListOfStringWrapper( + value = value, + ) + } +} + +internal class RemoveStopWordsSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("RemoveStopWords") + + override fun serialize(encoder: Encoder, value: RemoveStopWords) { + when (value) { + is RemoveStopWords.BooleanWrapper -> Boolean.serializer().serialize(encoder, value.value) + is RemoveStopWords.ListOfStringWrapper -> ListSerializer(String.serializer()).serialize(encoder, value.value) + } + } + + override fun deserialize(decoder: Decoder): RemoveStopWords { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize Boolean + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize Boolean (error: ${e.message})") + } + } + + // deserialize List + if (tree is JsonArray) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize List (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RemoveWordsIfNoResults.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RemoveWordsIfNoResults.kt new file mode 100644 index 0000000000..9c9bfeaf4a --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RemoveWordsIfNoResults.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* + +/** + * Selects a strategy to remove words from the query when it doesn't match any hits. + */ +@Serializable +public enum class RemoveWordsIfNoResults(public val value: kotlin.String) { + + @SerialName(value = "none") + None("none"), + + @SerialName(value = "lastWords") + LastWords("lastWords"), + + @SerialName(value = "firstWords") + FirstWords("firstWords"), + + @SerialName(value = "allOptional") + AllOptional("allOptional"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RenderingContent.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RenderingContent.kt new file mode 100644 index 0000000000..5507509ae2 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/RenderingContent.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Content defining how the search interface should be rendered. Can be set via the settings for a default value and can be overridden via rules. + * + * @param facetOrdering + */ +@Serializable +public data class RenderingContent( + + @SerialName(value = "facetOrdering") val facetOrdering: FacetOrdering? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/SearchParamsObject.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/SearchParamsObject.kt new file mode 100644 index 0000000000..061e336ea0 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/SearchParamsObject.kt @@ -0,0 +1,313 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SearchParamsObject + * + * @param query The text to search in the index. + * @param similarQuery Overrides the query parameter and performs a more generic search that can be used to find \"similar\" results. + * @param filters Filter the query with numeric, facet and/or tag filters. + * @param facetFilters + * @param optionalFilters + * @param numericFilters + * @param tagFilters + * @param sumOrFiltersScores Determines how to calculate the total score for filtering. + * @param facets Retrieve facets and their facet values. + * @param maxValuesPerFacet Maximum number of facet values to return for each facet during a regular search. + * @param facetingAfterDistinct Force faceting to be applied after de-duplication (via the Distinct setting). + * @param sortFacetValuesBy Controls how facet values are fetched. + * @param page Specify the page to retrieve. + * @param offset Specify the offset of the first hit to return. + * @param length Set the number of hits to retrieve (used only with offset). + * @param aroundLatLng Search for entries around a central geolocation, enabling a geo search within a circular area. + * @param aroundLatLngViaIP Search for entries around a given location automatically computed from the requester's IP address. + * @param aroundRadius + * @param aroundPrecision Precision of geo search (in meters), to add grouping by geo location to the ranking formula. + * @param minimumAroundRadius Minimum radius (in meters) used for a geo search when aroundRadius is not set. + * @param insideBoundingBox Search inside a rectangular area (in geo coordinates). + * @param insidePolygon Search inside a polygon (in geo coordinates). + * @param naturalLanguages This parameter changes the default values of certain parameters and settings that work best for a natural language query, such as ignorePlurals, removeStopWords, removeWordsIfNoResults, analyticsTags and ruleContexts. These parameters and settings work well together when the query is formatted in natural language instead of keywords, for example when your user performs a voice search. + * @param ruleContexts Enables contextual rules. + * @param personalizationImpact Define the impact of the Personalization feature. + * @param userToken Associates a certain user token with the current search. + * @param getRankingInfo Retrieve detailed ranking information. + * @param clickAnalytics Enable the Click Analytics feature. + * @param analytics Whether the current query will be taken into account in the Analytics. + * @param analyticsTags List of tags to apply to the query for analytics purposes. + * @param percentileComputation Whether to include or exclude a query from the processing-time percentile computation. + * @param enableABTest Whether this search should participate in running AB tests. + * @param enableReRanking Whether this search should use AI Re-Ranking. + * @param reRankingApplyFilter + * @param attributesForFaceting The complete list of attributes that will be used for faceting. + * @param attributesToRetrieve This parameter controls which attributes to retrieve and which not to retrieve. + * @param restrictSearchableAttributes Restricts a given query to look in only a subset of your searchable attributes. + * @param ranking Controls how Algolia should sort your results. + * @param customRanking Specifies the custom ranking criterion. + * @param relevancyStrictness Controls the relevancy threshold below which less relevant results aren't included in the results. + * @param attributesToHighlight List of attributes to highlight. + * @param attributesToSnippet List of attributes to snippet, with an optional maximum number of words to snippet. + * @param highlightPreTag The HTML string to insert before the highlighted parts in all highlight and snippet results. + * @param highlightPostTag The HTML string to insert after the highlighted parts in all highlight and snippet results. + * @param snippetEllipsisText String used as an ellipsis indicator when a snippet is truncated. + * @param restrictHighlightAndSnippetArrays Restrict highlighting and snippeting to items that matched the query. + * @param hitsPerPage Set the number of hits per page. + * @param minWordSizefor1Typo Minimum number of characters a word in the query string must contain to accept matches with 1 typo. + * @param minWordSizefor2Typos Minimum number of characters a word in the query string must contain to accept matches with 2 typos. + * @param typoTolerance + * @param allowTyposOnNumericTokens Whether to allow typos on numbers (\"numeric tokens\") in the query string. + * @param disableTypoToleranceOnAttributes List of attributes on which you want to disable typo tolerance. + * @param ignorePlurals + * @param removeStopWords + * @param keepDiacriticsOnCharacters List of characters that the engine shouldn't automatically normalize. + * @param queryLanguages Sets the languages to be used by language-specific settings and functionalities such as ignorePlurals, removeStopWords, and CJK word-detection. + * @param decompoundQuery Splits compound words into their composing atoms in the query. + * @param enableRules Whether Rules should be globally enabled. + * @param enablePersonalization Enable the Personalization feature. + * @param queryType + * @param removeWordsIfNoResults + * @param mode + * @param semanticSearch + * @param advancedSyntax Enables the advanced query syntax. + * @param optionalWords A list of words that should be considered as optional when found in the query. + * @param disableExactOnAttributes List of attributes on which you want to disable the exact ranking criterion. + * @param exactOnSingleWordQuery + * @param alternativesAsExact List of alternatives that should be considered an exact match by the exact ranking criterion. + * @param advancedSyntaxFeatures Allows you to specify which advanced syntax features are active when ‘advancedSyntax' is enabled. + * @param explain Enriches the API’s response with meta-information as to how the query was processed. + * @param distinct + * @param attributeForDistinct Name of the de-duplication attribute to be used with the distinct feature. + * @param synonyms Whether to take into account an index's synonyms for a particular search. + * @param replaceSynonymsInHighlight Whether to highlight and snippet the original word that matches the synonym or the synonym itself. + * @param minProximity Precision of the proximity ranking criterion. + * @param responseFields Choose which fields to return in the API response. This parameters applies to search and browse queries. + * @param maxFacetHits Maximum number of facet hits to return during a search for facet values. For performance reasons, the maximum allowed number of returned values is 100. + * @param attributeCriteriaComputedByMinProximity When attribute is ranked above proximity in your ranking formula, proximity is used to select which searchable attribute is matched in the attribute ranking stage. + * @param renderingContent + */ +@Serializable +public data class SearchParamsObject( + + /** The text to search in the index. */ + @SerialName(value = "query") val query: String? = null, + + /** Overrides the query parameter and performs a more generic search that can be used to find \"similar\" results. */ + @SerialName(value = "similarQuery") val similarQuery: String? = null, + + /** Filter the query with numeric, facet and/or tag filters. */ + @SerialName(value = "filters") val filters: String? = null, + + @SerialName(value = "facetFilters") val facetFilters: FacetFilters? = null, + + @SerialName(value = "optionalFilters") val optionalFilters: OptionalFilters? = null, + + @SerialName(value = "numericFilters") val numericFilters: NumericFilters? = null, + + @SerialName(value = "tagFilters") val tagFilters: TagFilters? = null, + + /** Determines how to calculate the total score for filtering. */ + @SerialName(value = "sumOrFiltersScores") val sumOrFiltersScores: Boolean? = null, + + /** Retrieve facets and their facet values. */ + @SerialName(value = "facets") val facets: List? = null, + + /** Maximum number of facet values to return for each facet during a regular search. */ + @SerialName(value = "maxValuesPerFacet") val maxValuesPerFacet: Int? = null, + + /** Force faceting to be applied after de-duplication (via the Distinct setting). */ + @SerialName(value = "facetingAfterDistinct") val facetingAfterDistinct: Boolean? = null, + + /** Controls how facet values are fetched. */ + @SerialName(value = "sortFacetValuesBy") val sortFacetValuesBy: String? = null, + + /** Specify the page to retrieve. */ + @SerialName(value = "page") val page: Int? = null, + + /** Specify the offset of the first hit to return. */ + @SerialName(value = "offset") val offset: Int? = null, + + /** Set the number of hits to retrieve (used only with offset). */ + @SerialName(value = "length") val length: Int? = null, + + /** Search for entries around a central geolocation, enabling a geo search within a circular area. */ + @SerialName(value = "aroundLatLng") val aroundLatLng: String? = null, + + /** Search for entries around a given location automatically computed from the requester's IP address. */ + @SerialName(value = "aroundLatLngViaIP") val aroundLatLngViaIP: Boolean? = null, + + @SerialName(value = "aroundRadius") val aroundRadius: AroundRadius? = null, + + /** Precision of geo search (in meters), to add grouping by geo location to the ranking formula. */ + @SerialName(value = "aroundPrecision") val aroundPrecision: Int? = null, + + /** Minimum radius (in meters) used for a geo search when aroundRadius is not set. */ + @SerialName(value = "minimumAroundRadius") val minimumAroundRadius: Int? = null, + + /** Search inside a rectangular area (in geo coordinates). */ + @SerialName(value = "insideBoundingBox") val insideBoundingBox: List? = null, + + /** Search inside a polygon (in geo coordinates). */ + @SerialName(value = "insidePolygon") val insidePolygon: List? = null, + + /** This parameter changes the default values of certain parameters and settings that work best for a natural language query, such as ignorePlurals, removeStopWords, removeWordsIfNoResults, analyticsTags and ruleContexts. These parameters and settings work well together when the query is formatted in natural language instead of keywords, for example when your user performs a voice search. */ + @SerialName(value = "naturalLanguages") val naturalLanguages: List? = null, + + /** Enables contextual rules. */ + @SerialName(value = "ruleContexts") val ruleContexts: List? = null, + + /** Define the impact of the Personalization feature. */ + @SerialName(value = "personalizationImpact") val personalizationImpact: Int? = null, + + /** Associates a certain user token with the current search. */ + @SerialName(value = "userToken") val userToken: String? = null, + + /** Retrieve detailed ranking information. */ + @SerialName(value = "getRankingInfo") val getRankingInfo: Boolean? = null, + + /** Enable the Click Analytics feature. */ + @SerialName(value = "clickAnalytics") val clickAnalytics: Boolean? = null, + + /** Whether the current query will be taken into account in the Analytics. */ + @SerialName(value = "analytics") val analytics: Boolean? = null, + + /** List of tags to apply to the query for analytics purposes. */ + @SerialName(value = "analyticsTags") val analyticsTags: List? = null, + + /** Whether to include or exclude a query from the processing-time percentile computation. */ + @SerialName(value = "percentileComputation") val percentileComputation: Boolean? = null, + + /** Whether this search should participate in running AB tests. */ + @SerialName(value = "enableABTest") val enableABTest: Boolean? = null, + + /** Whether this search should use AI Re-Ranking. */ + @SerialName(value = "enableReRanking") val enableReRanking: Boolean? = null, + + @SerialName(value = "reRankingApplyFilter") val reRankingApplyFilter: ReRankingApplyFilter? = null, + + /** The complete list of attributes that will be used for faceting. */ + @SerialName(value = "attributesForFaceting") val attributesForFaceting: List? = null, + + /** This parameter controls which attributes to retrieve and which not to retrieve. */ + @SerialName(value = "attributesToRetrieve") val attributesToRetrieve: List? = null, + + /** Restricts a given query to look in only a subset of your searchable attributes. */ + @SerialName(value = "restrictSearchableAttributes") val restrictSearchableAttributes: List? = null, + + /** Controls how Algolia should sort your results. */ + @SerialName(value = "ranking") val ranking: List? = null, + + /** Specifies the custom ranking criterion. */ + @SerialName(value = "customRanking") val customRanking: List? = null, + + /** Controls the relevancy threshold below which less relevant results aren't included in the results. */ + @SerialName(value = "relevancyStrictness") val relevancyStrictness: Int? = null, + + /** List of attributes to highlight. */ + @SerialName(value = "attributesToHighlight") val attributesToHighlight: List? = null, + + /** List of attributes to snippet, with an optional maximum number of words to snippet. */ + @SerialName(value = "attributesToSnippet") val attributesToSnippet: List? = null, + + /** The HTML string to insert before the highlighted parts in all highlight and snippet results. */ + @SerialName(value = "highlightPreTag") val highlightPreTag: String? = null, + + /** The HTML string to insert after the highlighted parts in all highlight and snippet results. */ + @SerialName(value = "highlightPostTag") val highlightPostTag: String? = null, + + /** String used as an ellipsis indicator when a snippet is truncated. */ + @SerialName(value = "snippetEllipsisText") val snippetEllipsisText: String? = null, + + /** Restrict highlighting and snippeting to items that matched the query. */ + @SerialName(value = "restrictHighlightAndSnippetArrays") val restrictHighlightAndSnippetArrays: Boolean? = null, + + /** Set the number of hits per page. */ + @SerialName(value = "hitsPerPage") val hitsPerPage: Int? = null, + + /** Minimum number of characters a word in the query string must contain to accept matches with 1 typo. */ + @SerialName(value = "minWordSizefor1Typo") val minWordSizefor1Typo: Int? = null, + + /** Minimum number of characters a word in the query string must contain to accept matches with 2 typos. */ + @SerialName(value = "minWordSizefor2Typos") val minWordSizefor2Typos: Int? = null, + + @SerialName(value = "typoTolerance") val typoTolerance: TypoTolerance? = null, + + /** Whether to allow typos on numbers (\"numeric tokens\") in the query string. */ + @SerialName(value = "allowTyposOnNumericTokens") val allowTyposOnNumericTokens: Boolean? = null, + + /** List of attributes on which you want to disable typo tolerance. */ + @SerialName(value = "disableTypoToleranceOnAttributes") val disableTypoToleranceOnAttributes: List? = null, + + @SerialName(value = "ignorePlurals") val ignorePlurals: IgnorePlurals? = null, + + @SerialName(value = "removeStopWords") val removeStopWords: RemoveStopWords? = null, + + /** List of characters that the engine shouldn't automatically normalize. */ + @SerialName(value = "keepDiacriticsOnCharacters") val keepDiacriticsOnCharacters: String? = null, + + /** Sets the languages to be used by language-specific settings and functionalities such as ignorePlurals, removeStopWords, and CJK word-detection. */ + @SerialName(value = "queryLanguages") val queryLanguages: List? = null, + + /** Splits compound words into their composing atoms in the query. */ + @SerialName(value = "decompoundQuery") val decompoundQuery: Boolean? = null, + + /** Whether Rules should be globally enabled. */ + @SerialName(value = "enableRules") val enableRules: Boolean? = null, + + /** Enable the Personalization feature. */ + @SerialName(value = "enablePersonalization") val enablePersonalization: Boolean? = null, + + @SerialName(value = "queryType") val queryType: QueryType? = null, + + @SerialName(value = "removeWordsIfNoResults") val removeWordsIfNoResults: RemoveWordsIfNoResults? = null, + + @SerialName(value = "mode") val mode: Mode? = null, + + @SerialName(value = "semanticSearch") val semanticSearch: IndexSettingsAsSearchParamsSemanticSearch? = null, + + /** Enables the advanced query syntax. */ + @SerialName(value = "advancedSyntax") val advancedSyntax: Boolean? = null, + + /** A list of words that should be considered as optional when found in the query. */ + @SerialName(value = "optionalWords") val optionalWords: List? = null, + + /** List of attributes on which you want to disable the exact ranking criterion. */ + @SerialName(value = "disableExactOnAttributes") val disableExactOnAttributes: List? = null, + + @SerialName(value = "exactOnSingleWordQuery") val exactOnSingleWordQuery: ExactOnSingleWordQuery? = null, + + /** List of alternatives that should be considered an exact match by the exact ranking criterion. */ + @SerialName(value = "alternativesAsExact") val alternativesAsExact: List? = null, + + /** Allows you to specify which advanced syntax features are active when ‘advancedSyntax' is enabled. */ + @SerialName(value = "advancedSyntaxFeatures") val advancedSyntaxFeatures: List? = null, + + /** Enriches the API’s response with meta-information as to how the query was processed. */ + @SerialName(value = "explain") val explain: List? = null, + + @SerialName(value = "distinct") val distinct: Distinct? = null, + + /** Name of the de-duplication attribute to be used with the distinct feature. */ + @SerialName(value = "attributeForDistinct") val attributeForDistinct: String? = null, + + /** Whether to take into account an index's synonyms for a particular search. */ + @SerialName(value = "synonyms") val synonyms: Boolean? = null, + + /** Whether to highlight and snippet the original word that matches the synonym or the synonym itself. */ + @SerialName(value = "replaceSynonymsInHighlight") val replaceSynonymsInHighlight: Boolean? = null, + + /** Precision of the proximity ranking criterion. */ + @SerialName(value = "minProximity") val minProximity: Int? = null, + + /** Choose which fields to return in the API response. This parameters applies to search and browse queries. */ + @SerialName(value = "responseFields") val responseFields: List? = null, + + /** Maximum number of facet hits to return during a search for facet values. For performance reasons, the maximum allowed number of returned values is 100. */ + @SerialName(value = "maxFacetHits") val maxFacetHits: Int? = null, + + /** When attribute is ranked above proximity in your ranking formula, proximity is used to select which searchable attribute is matched in the attribute ranking stage. */ + @SerialName(value = "attributeCriteriaComputedByMinProximity") val attributeCriteriaComputedByMinProximity: Boolean? = null, + + @SerialName(value = "renderingContent") val renderingContent: RenderingContent? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/SearchParamsQuery.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/SearchParamsQuery.kt new file mode 100644 index 0000000000..8b27b1585b --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/SearchParamsQuery.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SearchParamsQuery + * + * @param query The text to search in the index. + */ +@Serializable +public data class SearchParamsQuery( + + /** The text to search in the index. */ + @SerialName(value = "query") val query: String? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/SnippetResult.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/SnippetResult.kt new file mode 100644 index 0000000000..93604bd027 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/SnippetResult.kt @@ -0,0 +1,85 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * SnippetResult + */ +@Serializable(SnippetResultSerializer::class) +public sealed interface SnippetResult { + + public data class ListOfSnippetResultOptionWrapper(val value: List) : SnippetResult + + public companion object { + + /** + * SnippetResult as List + * + */ + public fun ListOfSnippetResultOption( + value: List, + ): ListOfSnippetResultOptionWrapper = ListOfSnippetResultOptionWrapper( + value = value, + ) + + /** + * Snippeted attributes show parts of the matched attributes. Only returned when attributesToSnippet is non-empty. + * + * @param `value` Markup text with occurrences highlighted. + * @param matchLevel + */ + public fun SnippetResultOption( + `value`: String, + matchLevel: MatchLevel, + ): SnippetResultOption = com.algolia.client.model.recommend.SnippetResultOption( + `value` = `value`, + matchLevel = matchLevel, + ) + } +} + +internal class SnippetResultSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("SnippetResult") + + override fun serialize(encoder: Encoder, value: SnippetResult) { + when (value) { + is SnippetResult.ListOfSnippetResultOptionWrapper -> ListSerializer(SnippetResultOption.serializer()).serialize(encoder, value.value) + is SnippetResultOption -> SnippetResultOption.serializer().serialize(encoder, value) + } + } + + override fun deserialize(decoder: Decoder): SnippetResult { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize List + if (tree is JsonArray) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize List (error: ${e.message})") + } + } + + // deserialize SnippetResultOption + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize SnippetResultOption (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/SnippetResultOption.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/SnippetResultOption.kt new file mode 100644 index 0000000000..c191781cbc --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/SnippetResultOption.kt @@ -0,0 +1,20 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Snippeted attributes show parts of the matched attributes. Only returned when attributesToSnippet is non-empty. + * + * @param `value` Markup text with occurrences highlighted. + * @param matchLevel + */ +@Serializable +public data class SnippetResultOption( + + /** Markup text with occurrences highlighted. */ + @SerialName(value = "value") val `value`: String, + + @SerialName(value = "matchLevel") val matchLevel: MatchLevel, +) : SnippetResult diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/SortRemainingBy.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/SortRemainingBy.kt new file mode 100644 index 0000000000..f00a9622ce --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/SortRemainingBy.kt @@ -0,0 +1,22 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* + +/** + * How to display the remaining items. - `count`: facet count (descending). - `alpha`: alphabetical (ascending). - `hidden`: show only pinned values. + */ +@Serializable +public enum class SortRemainingBy(public val value: kotlin.String) { + + @SerialName(value = "count") + Count("count"), + + @SerialName(value = "alpha") + Alpha("alpha"), + + @SerialName(value = "hidden") + Hidden("hidden"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/TagFilters.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/TagFilters.kt new file mode 100644 index 0000000000..a40ade3e17 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/TagFilters.kt @@ -0,0 +1,83 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Filter hits by tags. + */ +@Serializable(TagFiltersSerializer::class) +public sealed interface TagFilters { + + public data class ListOfMixedSearchFiltersWrapper(val value: List) : TagFilters + + public data class StringWrapper(val value: String) : TagFilters + + public companion object { + + /** + * TagFilters as List + * + */ + public fun ListOfMixedSearchFilters( + value: List, + ): ListOfMixedSearchFiltersWrapper = ListOfMixedSearchFiltersWrapper( + value = value, + ) + + /** + * TagFilters as String + * + */ + public fun String( + value: String, + ): StringWrapper = StringWrapper( + value = value, + ) + } +} + +internal class TagFiltersSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("TagFilters") + + override fun serialize(encoder: Encoder, value: TagFilters) { + when (value) { + is TagFilters.ListOfMixedSearchFiltersWrapper -> ListSerializer(MixedSearchFilters.serializer()).serialize(encoder, value.value) + is TagFilters.StringWrapper -> String.serializer().serialize(encoder, value.value) + } + } + + override fun deserialize(decoder: Decoder): TagFilters { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize List + if (tree is JsonArray) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize List (error: ${e.message})") + } + } + + // deserialize String + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize String (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/TrendingModels.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/TrendingModels.kt new file mode 100644 index 0000000000..ec328ddba8 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/TrendingModels.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* + +/** + * The trending model to use. + */ +@Serializable +public enum class TrendingModels(public val value: kotlin.String) { + + @SerialName(value = "trending-facets") + Facets("trending-facets"), + + @SerialName(value = "trending-items") + Items("trending-items"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/TrendingRequest.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/TrendingRequest.kt new file mode 100644 index 0000000000..434ff5ef0c --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/TrendingRequest.kt @@ -0,0 +1,42 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * TrendingRequest + * + * @param model + * @param indexName The Algolia index name. + * @param threshold The threshold to use when filtering recommendations by their score. + * @param facetName The facet name to use for trending models. + * @param facetValue The facet value to use for trending models. + * @param maxRecommendations The max number of recommendations to retrieve. If it's set to 0, all the recommendations of the objectID may be returned. + * @param queryParameters + * @param fallbackParameters + */ +@Serializable +public data class TrendingRequest( + + @SerialName(value = "model") val model: TrendingModels, + + /** The Algolia index name. */ + @SerialName(value = "indexName") val indexName: String, + + /** The threshold to use when filtering recommendations by their score. */ + @SerialName(value = "threshold") val threshold: Int, + + /** The facet name to use for trending models. */ + @SerialName(value = "facetName") val facetName: String? = null, + + /** The facet value to use for trending models. */ + @SerialName(value = "facetValue") val facetValue: String? = null, + + /** The max number of recommendations to retrieve. If it's set to 0, all the recommendations of the objectID may be returned. */ + @SerialName(value = "maxRecommendations") val maxRecommendations: Int? = null, + + @SerialName(value = "queryParameters") val queryParameters: SearchParamsObject? = null, + + @SerialName(value = "fallbackParameters") val fallbackParameters: SearchParamsObject? = null, +) : RecommendationsRequest diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/TypoTolerance.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/TypoTolerance.kt new file mode 100644 index 0000000000..128dd9c5f1 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/TypoTolerance.kt @@ -0,0 +1,76 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Controls whether typo tolerance is enabled and how it is applied. + */ +@Serializable(TypoToleranceSerializer::class) +public sealed interface TypoTolerance { + + public data class BooleanWrapper(val value: Boolean) : TypoTolerance + + public companion object { + + /** + * TypoTolerance as Boolean + * + */ + public fun Boolean( + value: Boolean, + ): BooleanWrapper = BooleanWrapper( + value = value, + ) + + /** + * TypoToleranceEnum + */ + public fun of(value: TypoToleranceEnum): TypoToleranceEnum = value + } +} + +internal class TypoToleranceSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("TypoTolerance") + + override fun serialize(encoder: Encoder, value: TypoTolerance) { + when (value) { + is TypoTolerance.BooleanWrapper -> Boolean.serializer().serialize(encoder, value.value) + is TypoToleranceEnum -> TypoToleranceEnum.serializer().serialize(encoder, value) + } + } + + override fun deserialize(decoder: Decoder): TypoTolerance { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize Boolean + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize Boolean (error: ${e.message})") + } + } + + // deserialize TypoToleranceEnum + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize TypoToleranceEnum (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/TypoToleranceEnum.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/TypoToleranceEnum.kt new file mode 100644 index 0000000000..f327e2d33c --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/TypoToleranceEnum.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* + +@Serializable +public enum class TypoToleranceEnum(public val value: kotlin.String) : TypoTolerance { + + @SerialName(value = "min") + Min("min"), + + @SerialName(value = "strict") + Strict("strict"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/Value.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/Value.kt new file mode 100644 index 0000000000..370a4436d3 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/recommend/Value.kt @@ -0,0 +1,20 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.recommend + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Value + * + * @param order Pinned order of facet lists. + * @param sortRemainingBy + */ +@Serializable +public data class Value( + + /** Pinned order of facet lists. */ + @SerialName(value = "order") val order: List? = null, + + @SerialName(value = "sortRemainingBy") val sortRemainingBy: SortRemainingBy? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Acl.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Acl.kt new file mode 100644 index 0000000000..12610a36dc --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Acl.kt @@ -0,0 +1,55 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* + +/** + * List of rights for the API key. The following rights can be used: addObject: allows to add/update an object in the index (copy/move index are also allowed with this right). analytics: allows to retrieve the analytics through the Analytics API. browse: allows to retrieve all index content via the browse API. deleteIndex: allows to delete or clear index content. deleteObject: allows to delete objects from the index. editSettings: allows to change index settings. listIndexes: allows to list all accessible indices. logs: allows to get the logs. recommendation: Allows usage of the Personalization dashboard and the Recommendation API. search: allows to search the index. seeUnretrievableAttributes: disable unretrievableAttributes feature for all operations returning records. settings: allows to get index settings. + */ +@Serializable +public enum class Acl(public val value: kotlin.String) { + + @SerialName(value = "addObject") + AddObject("addObject"), + + @SerialName(value = "analytics") + Analytics("analytics"), + + @SerialName(value = "browse") + Browse("browse"), + + @SerialName(value = "deleteObject") + DeleteObject("deleteObject"), + + @SerialName(value = "deleteIndex") + DeleteIndex("deleteIndex"), + + @SerialName(value = "editSettings") + EditSettings("editSettings"), + + @SerialName(value = "listIndexes") + ListIndexes("listIndexes"), + + @SerialName(value = "logs") + Logs("logs"), + + @SerialName(value = "personalization") + Personalization("personalization"), + + @SerialName(value = "recommendation") + Recommendation("recommendation"), + + @SerialName(value = "search") + Search("search"), + + @SerialName(value = "seeUnretrievableAttributes") + SeeUnretrievableAttributes("seeUnretrievableAttributes"), + + @SerialName(value = "settings") + Settings("settings"), + + @SerialName(value = "usage") + Usage("usage"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Action.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Action.kt new file mode 100644 index 0000000000..29ace1b93f --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Action.kt @@ -0,0 +1,34 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* + +/** + * type of operation. + */ +@Serializable +public enum class Action(public val value: kotlin.String) { + + @SerialName(value = "addObject") + AddObject("addObject"), + + @SerialName(value = "updateObject") + UpdateObject("updateObject"), + + @SerialName(value = "partialUpdateObject") + PartialUpdateObject("partialUpdateObject"), + + @SerialName(value = "partialUpdateObjectNoCreate") + PartialUpdateObjectNoCreate("partialUpdateObjectNoCreate"), + + @SerialName(value = "deleteObject") + DeleteObject("deleteObject"), + + @SerialName(value = "delete") + Delete("delete"), + + @SerialName(value = "clear") + Clear("clear"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AddApiKeyResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AddApiKeyResponse.kt new file mode 100644 index 0000000000..67ff5c568a --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AddApiKeyResponse.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * AddApiKeyResponse + * + * @param key The API key. + * @param createdAt Date of creation (ISO-8601 format). + */ +@Serializable +public data class AddApiKeyResponse( + + /** The API key. */ + @SerialName(value = "key") val key: String, + + /** Date of creation (ISO-8601 format). */ + @SerialName(value = "createdAt") val createdAt: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AdvancedSyntaxFeatures.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AdvancedSyntaxFeatures.kt new file mode 100644 index 0000000000..83dd5a16c4 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AdvancedSyntaxFeatures.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* + +@Serializable +public enum class AdvancedSyntaxFeatures(public val value: kotlin.String) { + + @SerialName(value = "exactPhrase") + ExactPhrase("exactPhrase"), + + @SerialName(value = "excludeWords") + ExcludeWords("excludeWords"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AlternativesAsExact.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AlternativesAsExact.kt new file mode 100644 index 0000000000..f988a055ce --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AlternativesAsExact.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* + +@Serializable +public enum class AlternativesAsExact(public val value: kotlin.String) { + + @SerialName(value = "ignorePlurals") + IgnorePlurals("ignorePlurals"), + + @SerialName(value = "singleWordSynonym") + SingleWordSynonym("singleWordSynonym"), + + @SerialName(value = "multiWordsSynonym") + MultiWordsSynonym("multiWordsSynonym"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Anchoring.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Anchoring.kt new file mode 100644 index 0000000000..52c2b5ebe5 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Anchoring.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* + +/** + * Whether the pattern parameter must match the beginning or the end of the query string, or both, or none. + */ +@Serializable +public enum class Anchoring(public val value: kotlin.String) { + + @SerialName(value = "is") + Is("is"), + + @SerialName(value = "startsWith") + StartsWith("startsWith"), + + @SerialName(value = "endsWith") + EndsWith("endsWith"), + + @SerialName(value = "contains") + Contains("contains"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ApiKey.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ApiKey.kt new file mode 100644 index 0000000000..dc2ee0c467 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ApiKey.kt @@ -0,0 +1,45 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Api Key object. + * + * @param acl Set of permissions associated with the key. + * @param description A comment used to identify a key more easily in the dashboard. It is not interpreted by the API. + * @param indexes Restrict this new API key to a list of indices or index patterns. If the list is empty, all indices are allowed. + * @param maxHitsPerQuery Maximum number of hits this API key can retrieve in one query. If zero, no limit is enforced. + * @param maxQueriesPerIPPerHour Maximum number of API calls per hour allowed from a given IP address or a user token. + * @param queryParameters URL-encoded query string. Force some query parameters to be applied for each query made with this API key. + * @param referers Restrict this new API key to specific referers. If empty or blank, defaults to all referers. + * @param validity Validity limit for this key in seconds. The key will automatically be removed after this period of time. + */ +@Serializable +public data class ApiKey( + + /** Set of permissions associated with the key. */ + @SerialName(value = "acl") val acl: List, + + /** A comment used to identify a key more easily in the dashboard. It is not interpreted by the API. */ + @SerialName(value = "description") val description: String? = null, + + /** Restrict this new API key to a list of indices or index patterns. If the list is empty, all indices are allowed. */ + @SerialName(value = "indexes") val indexes: List? = null, + + /** Maximum number of hits this API key can retrieve in one query. If zero, no limit is enforced. */ + @SerialName(value = "maxHitsPerQuery") val maxHitsPerQuery: Int? = null, + + /** Maximum number of API calls per hour allowed from a given IP address or a user token. */ + @SerialName(value = "maxQueriesPerIPPerHour") val maxQueriesPerIPPerHour: Int? = null, + + /** URL-encoded query string. Force some query parameters to be applied for each query made with this API key. */ + @SerialName(value = "queryParameters") val queryParameters: String? = null, + + /** Restrict this new API key to specific referers. If empty or blank, defaults to all referers. */ + @SerialName(value = "referers") val referers: List? = null, + + /** Validity limit for this key in seconds. The key will automatically be removed after this period of time. */ + @SerialName(value = "validity") val validity: Int? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AroundRadius.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AroundRadius.kt new file mode 100644 index 0000000000..54a21e025e --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AroundRadius.kt @@ -0,0 +1,76 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Define the maximum radius for a geo search (in meters). + */ +@Serializable(AroundRadiusSerializer::class) +public sealed interface AroundRadius { + + public data class IntWrapper(val value: Int) : AroundRadius + + public companion object { + + /** + * AroundRadiusAll + */ + public fun of(value: AroundRadiusAll): AroundRadiusAll = value + + /** + * AroundRadius as Int + * + */ + public fun Number( + value: Int, + ): IntWrapper = IntWrapper( + value = value, + ) + } +} + +internal class AroundRadiusSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("AroundRadius") + + override fun serialize(encoder: Encoder, value: AroundRadius) { + when (value) { + is AroundRadiusAll -> AroundRadiusAll.serializer().serialize(encoder, value) + is AroundRadius.IntWrapper -> Int.serializer().serialize(encoder, value.value) + } + } + + override fun deserialize(decoder: Decoder): AroundRadius { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize AroundRadiusAll + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize AroundRadiusAll (error: ${e.message})") + } + } + + // deserialize Int + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize Int (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AroundRadiusAll.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AroundRadiusAll.kt new file mode 100644 index 0000000000..e2cd09f21f --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AroundRadiusAll.kt @@ -0,0 +1,13 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* + +@Serializable +public enum class AroundRadiusAll(public val value: kotlin.String) : AroundRadius { + + @SerialName(value = "all") + All("all"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AssignUserIdParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AssignUserIdParams.kt new file mode 100644 index 0000000000..dd79d87fd8 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AssignUserIdParams.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Assign userID parameters. + * + * @param cluster Name of the cluster. + */ +@Serializable +public data class AssignUserIdParams( + + /** Name of the cluster. */ + @SerialName(value = "cluster") val cluster: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AttributeToUpdate.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AttributeToUpdate.kt new file mode 100644 index 0000000000..25af8f89ac --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AttributeToUpdate.kt @@ -0,0 +1,85 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * AttributeToUpdate + */ +@Serializable(AttributeToUpdateSerializer::class) +public sealed interface AttributeToUpdate { + + public data class StringWrapper(val value: String) : AttributeToUpdate + + public companion object { + + /** + * To update an attribute without pushing the entire record, you can use these built-in operations. + * + * @param operation + * @param `value` the right-hand side argument to the operation, for example, increment or decrement step, value to add or remove. + */ + public fun BuiltInOperation( + operation: BuiltInOperationType, + `value`: String, + ): BuiltInOperation = com.algolia.client.model.search.BuiltInOperation( + operation = operation, + `value` = `value`, + ) + + /** + * AttributeToUpdate as String + * + */ + public fun String( + value: String, + ): StringWrapper = StringWrapper( + value = value, + ) + } +} + +internal class AttributeToUpdateSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("AttributeToUpdate") + + override fun serialize(encoder: Encoder, value: AttributeToUpdate) { + when (value) { + is BuiltInOperation -> BuiltInOperation.serializer().serialize(encoder, value) + is AttributeToUpdate.StringWrapper -> String.serializer().serialize(encoder, value.value) + } + } + + override fun deserialize(decoder: Decoder): AttributeToUpdate { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize BuiltInOperation + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize BuiltInOperation (error: ${e.message})") + } + } + + // deserialize String + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize String (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AutomaticFacetFilter.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AutomaticFacetFilter.kt new file mode 100644 index 0000000000..2da27a1b6d --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AutomaticFacetFilter.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Automatic facet Filter. + * + * @param facet Attribute to filter on. This must match a facet placeholder in the Rule's pattern. + * @param score Score for the filter. Typically used for optional or disjunctive filters. + * @param disjunctive Whether the filter is disjunctive (true) or conjunctive (false). + */ +@Serializable +public data class AutomaticFacetFilter( + + /** Attribute to filter on. This must match a facet placeholder in the Rule's pattern. */ + @SerialName(value = "facet") val facet: String, + + /** Score for the filter. Typically used for optional or disjunctive filters. */ + @SerialName(value = "score") val score: Int? = null, + + /** Whether the filter is disjunctive (true) or conjunctive (false). */ + @SerialName(value = "disjunctive") val disjunctive: Boolean? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AutomaticFacetFilters.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AutomaticFacetFilters.kt new file mode 100644 index 0000000000..bec1d18344 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/AutomaticFacetFilters.kt @@ -0,0 +1,83 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Names of facets to which automatic filtering must be applied; they must match the facet name of a facet value placeholder in the query pattern. + */ +@Serializable(AutomaticFacetFiltersSerializer::class) +public sealed interface AutomaticFacetFilters { + + public data class ListOfAutomaticFacetFilterWrapper(val value: List) : AutomaticFacetFilters + + public data class ListOfStringWrapper(val value: List) : AutomaticFacetFilters + + public companion object { + + /** + * AutomaticFacetFilters as List + * + */ + public fun ListOfAutomaticFacetFilter( + value: List, + ): ListOfAutomaticFacetFilterWrapper = ListOfAutomaticFacetFilterWrapper( + value = value, + ) + + /** + * AutomaticFacetFilters as List + * + */ + public fun ListOfString( + value: List, + ): ListOfStringWrapper = ListOfStringWrapper( + value = value, + ) + } +} + +internal class AutomaticFacetFiltersSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("AutomaticFacetFilters") + + override fun serialize(encoder: Encoder, value: AutomaticFacetFilters) { + when (value) { + is AutomaticFacetFilters.ListOfAutomaticFacetFilterWrapper -> ListSerializer(AutomaticFacetFilter.serializer()).serialize(encoder, value.value) + is AutomaticFacetFilters.ListOfStringWrapper -> ListSerializer(String.serializer()).serialize(encoder, value.value) + } + } + + override fun deserialize(decoder: Decoder): AutomaticFacetFilters { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize List + if (tree is JsonArray) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize List (error: ${e.message})") + } + } + + // deserialize List + if (tree is JsonArray) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize List (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BaseGetApiKeyResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BaseGetApiKeyResponse.kt new file mode 100644 index 0000000000..a831030098 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BaseGetApiKeyResponse.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * BaseGetApiKeyResponse + * + * @param createdAt Time of the event expressed in milliseconds since the Unix epoch. + * @param `value` The API key. + */ +@Serializable +public data class BaseGetApiKeyResponse( + + /** Time of the event expressed in milliseconds since the Unix epoch. */ + @SerialName(value = "createdAt") val createdAt: Long, + + /** The API key. */ + @SerialName(value = "value") val `value`: String? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BaseIndexSettings.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BaseIndexSettings.kt new file mode 100644 index 0000000000..73d04c4cd4 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BaseIndexSettings.kt @@ -0,0 +1,73 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * BaseIndexSettings + * + * @param replicas Creates replicas, exact copies of an index. + * @param paginationLimitedTo Set the maximum number of hits accessible via pagination. + * @param unretrievableAttributes List of attributes that can't be retrieved at query time. + * @param disableTypoToleranceOnWords A list of words for which you want to turn off typo tolerance. + * @param attributesToTransliterate Specify on which attributes in your index Algolia should apply Japanese transliteration to make words indexed in Katakana or Kanji searchable in Hiragana. + * @param camelCaseAttributes List of attributes on which to do a decomposition of camel case words. + * @param decompoundedAttributes Specify on which attributes in your index Algolia should apply word segmentation, also known as decompounding. + * @param indexLanguages Sets the languages at the index level for language-specific processing such as tokenization and normalization. + * @param disablePrefixOnAttributes List of attributes on which you want to disable prefix matching. + * @param allowCompressionOfIntegerArray Enables compression of large integer arrays. + * @param numericAttributesForFiltering List of numeric attributes that can be used as numerical filters. + * @param separatorsToIndex Control which separators are indexed. + * @param searchableAttributes The complete list of attributes used for searching. + * @param userData Lets you store custom data in your indices. + * @param customNormalization Overrides Algolia's default normalization. + */ +@Serializable +public data class BaseIndexSettings( + + /** Creates replicas, exact copies of an index. */ + @SerialName(value = "replicas") val replicas: List? = null, + + /** Set the maximum number of hits accessible via pagination. */ + @SerialName(value = "paginationLimitedTo") val paginationLimitedTo: Int? = null, + + /** List of attributes that can't be retrieved at query time. */ + @SerialName(value = "unretrievableAttributes") val unretrievableAttributes: List? = null, + + /** A list of words for which you want to turn off typo tolerance. */ + @SerialName(value = "disableTypoToleranceOnWords") val disableTypoToleranceOnWords: List? = null, + + /** Specify on which attributes in your index Algolia should apply Japanese transliteration to make words indexed in Katakana or Kanji searchable in Hiragana. */ + @SerialName(value = "attributesToTransliterate") val attributesToTransliterate: List? = null, + + /** List of attributes on which to do a decomposition of camel case words. */ + @SerialName(value = "camelCaseAttributes") val camelCaseAttributes: List? = null, + + /** Specify on which attributes in your index Algolia should apply word segmentation, also known as decompounding. */ + @SerialName(value = "decompoundedAttributes") val decompoundedAttributes: JsonObject? = null, + + /** Sets the languages at the index level for language-specific processing such as tokenization and normalization. */ + @SerialName(value = "indexLanguages") val indexLanguages: List? = null, + + /** List of attributes on which you want to disable prefix matching. */ + @SerialName(value = "disablePrefixOnAttributes") val disablePrefixOnAttributes: List? = null, + + /** Enables compression of large integer arrays. */ + @SerialName(value = "allowCompressionOfIntegerArray") val allowCompressionOfIntegerArray: Boolean? = null, + + /** List of numeric attributes that can be used as numerical filters. */ + @SerialName(value = "numericAttributesForFiltering") val numericAttributesForFiltering: List? = null, + + /** Control which separators are indexed. */ + @SerialName(value = "separatorsToIndex") val separatorsToIndex: String? = null, + + /** The complete list of attributes used for searching. */ + @SerialName(value = "searchableAttributes") val searchableAttributes: List? = null, + + /** Lets you store custom data in your indices. */ + @SerialName(value = "userData") val userData: JsonObject? = null, + + /** Overrides Algolia's default normalization. */ + @SerialName(value = "customNormalization") val customNormalization: Map>? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BaseSearchParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BaseSearchParams.kt new file mode 100644 index 0000000000..2c6e49b253 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BaseSearchParams.kt @@ -0,0 +1,143 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * BaseSearchParams + * + * @param query The text to search in the index. + * @param similarQuery Overrides the query parameter and performs a more generic search that can be used to find \"similar\" results. + * @param filters Filter the query with numeric, facet and/or tag filters. + * @param facetFilters + * @param optionalFilters + * @param numericFilters + * @param tagFilters + * @param sumOrFiltersScores Determines how to calculate the total score for filtering. + * @param facets Retrieve facets and their facet values. + * @param maxValuesPerFacet Maximum number of facet values to return for each facet during a regular search. + * @param facetingAfterDistinct Force faceting to be applied after de-duplication (via the Distinct setting). + * @param sortFacetValuesBy Controls how facet values are fetched. + * @param page Specify the page to retrieve. + * @param offset Specify the offset of the first hit to return. + * @param length Set the number of hits to retrieve (used only with offset). + * @param aroundLatLng Search for entries around a central geolocation, enabling a geo search within a circular area. + * @param aroundLatLngViaIP Search for entries around a given location automatically computed from the requester's IP address. + * @param aroundRadius + * @param aroundPrecision Precision of geo search (in meters), to add grouping by geo location to the ranking formula. + * @param minimumAroundRadius Minimum radius (in meters) used for a geo search when aroundRadius is not set. + * @param insideBoundingBox Search inside a rectangular area (in geo coordinates). + * @param insidePolygon Search inside a polygon (in geo coordinates). + * @param naturalLanguages This parameter changes the default values of certain parameters and settings that work best for a natural language query, such as ignorePlurals, removeStopWords, removeWordsIfNoResults, analyticsTags and ruleContexts. These parameters and settings work well together when the query is formatted in natural language instead of keywords, for example when your user performs a voice search. + * @param ruleContexts Enables contextual rules. + * @param personalizationImpact Define the impact of the Personalization feature. + * @param userToken Associates a certain user token with the current search. + * @param getRankingInfo Retrieve detailed ranking information. + * @param clickAnalytics Enable the Click Analytics feature. + * @param analytics Whether the current query will be taken into account in the Analytics. + * @param analyticsTags List of tags to apply to the query for analytics purposes. + * @param percentileComputation Whether to include or exclude a query from the processing-time percentile computation. + * @param enableABTest Whether this search should participate in running AB tests. + * @param enableReRanking Whether this search should use AI Re-Ranking. + * @param reRankingApplyFilter + */ +@Serializable +public data class BaseSearchParams( + + /** The text to search in the index. */ + @SerialName(value = "query") val query: String? = null, + + /** Overrides the query parameter and performs a more generic search that can be used to find \"similar\" results. */ + @SerialName(value = "similarQuery") val similarQuery: String? = null, + + /** Filter the query with numeric, facet and/or tag filters. */ + @SerialName(value = "filters") val filters: String? = null, + + @SerialName(value = "facetFilters") val facetFilters: FacetFilters? = null, + + @SerialName(value = "optionalFilters") val optionalFilters: OptionalFilters? = null, + + @SerialName(value = "numericFilters") val numericFilters: NumericFilters? = null, + + @SerialName(value = "tagFilters") val tagFilters: TagFilters? = null, + + /** Determines how to calculate the total score for filtering. */ + @SerialName(value = "sumOrFiltersScores") val sumOrFiltersScores: Boolean? = null, + + /** Retrieve facets and their facet values. */ + @SerialName(value = "facets") val facets: List? = null, + + /** Maximum number of facet values to return for each facet during a regular search. */ + @SerialName(value = "maxValuesPerFacet") val maxValuesPerFacet: Int? = null, + + /** Force faceting to be applied after de-duplication (via the Distinct setting). */ + @SerialName(value = "facetingAfterDistinct") val facetingAfterDistinct: Boolean? = null, + + /** Controls how facet values are fetched. */ + @SerialName(value = "sortFacetValuesBy") val sortFacetValuesBy: String? = null, + + /** Specify the page to retrieve. */ + @SerialName(value = "page") val page: Int? = null, + + /** Specify the offset of the first hit to return. */ + @SerialName(value = "offset") val offset: Int? = null, + + /** Set the number of hits to retrieve (used only with offset). */ + @SerialName(value = "length") val length: Int? = null, + + /** Search for entries around a central geolocation, enabling a geo search within a circular area. */ + @SerialName(value = "aroundLatLng") val aroundLatLng: String? = null, + + /** Search for entries around a given location automatically computed from the requester's IP address. */ + @SerialName(value = "aroundLatLngViaIP") val aroundLatLngViaIP: Boolean? = null, + + @SerialName(value = "aroundRadius") val aroundRadius: AroundRadius? = null, + + /** Precision of geo search (in meters), to add grouping by geo location to the ranking formula. */ + @SerialName(value = "aroundPrecision") val aroundPrecision: Int? = null, + + /** Minimum radius (in meters) used for a geo search when aroundRadius is not set. */ + @SerialName(value = "minimumAroundRadius") val minimumAroundRadius: Int? = null, + + /** Search inside a rectangular area (in geo coordinates). */ + @SerialName(value = "insideBoundingBox") val insideBoundingBox: List? = null, + + /** Search inside a polygon (in geo coordinates). */ + @SerialName(value = "insidePolygon") val insidePolygon: List? = null, + + /** This parameter changes the default values of certain parameters and settings that work best for a natural language query, such as ignorePlurals, removeStopWords, removeWordsIfNoResults, analyticsTags and ruleContexts. These parameters and settings work well together when the query is formatted in natural language instead of keywords, for example when your user performs a voice search. */ + @SerialName(value = "naturalLanguages") val naturalLanguages: List? = null, + + /** Enables contextual rules. */ + @SerialName(value = "ruleContexts") val ruleContexts: List? = null, + + /** Define the impact of the Personalization feature. */ + @SerialName(value = "personalizationImpact") val personalizationImpact: Int? = null, + + /** Associates a certain user token with the current search. */ + @SerialName(value = "userToken") val userToken: String? = null, + + /** Retrieve detailed ranking information. */ + @SerialName(value = "getRankingInfo") val getRankingInfo: Boolean? = null, + + /** Enable the Click Analytics feature. */ + @SerialName(value = "clickAnalytics") val clickAnalytics: Boolean? = null, + + /** Whether the current query will be taken into account in the Analytics. */ + @SerialName(value = "analytics") val analytics: Boolean? = null, + + /** List of tags to apply to the query for analytics purposes. */ + @SerialName(value = "analyticsTags") val analyticsTags: List? = null, + + /** Whether to include or exclude a query from the processing-time percentile computation. */ + @SerialName(value = "percentileComputation") val percentileComputation: Boolean? = null, + + /** Whether this search should participate in running AB tests. */ + @SerialName(value = "enableABTest") val enableABTest: Boolean? = null, + + /** Whether this search should use AI Re-Ranking. */ + @SerialName(value = "enableReRanking") val enableReRanking: Boolean? = null, + + @SerialName(value = "reRankingApplyFilter") val reRankingApplyFilter: ReRankingApplyFilter? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BaseSearchParamsWithoutQuery.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BaseSearchParamsWithoutQuery.kt new file mode 100644 index 0000000000..49e5d0b8ff --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BaseSearchParamsWithoutQuery.kt @@ -0,0 +1,139 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * BaseSearchParamsWithoutQuery + * + * @param similarQuery Overrides the query parameter and performs a more generic search that can be used to find \"similar\" results. + * @param filters Filter the query with numeric, facet and/or tag filters. + * @param facetFilters + * @param optionalFilters + * @param numericFilters + * @param tagFilters + * @param sumOrFiltersScores Determines how to calculate the total score for filtering. + * @param facets Retrieve facets and their facet values. + * @param maxValuesPerFacet Maximum number of facet values to return for each facet during a regular search. + * @param facetingAfterDistinct Force faceting to be applied after de-duplication (via the Distinct setting). + * @param sortFacetValuesBy Controls how facet values are fetched. + * @param page Specify the page to retrieve. + * @param offset Specify the offset of the first hit to return. + * @param length Set the number of hits to retrieve (used only with offset). + * @param aroundLatLng Search for entries around a central geolocation, enabling a geo search within a circular area. + * @param aroundLatLngViaIP Search for entries around a given location automatically computed from the requester's IP address. + * @param aroundRadius + * @param aroundPrecision Precision of geo search (in meters), to add grouping by geo location to the ranking formula. + * @param minimumAroundRadius Minimum radius (in meters) used for a geo search when aroundRadius is not set. + * @param insideBoundingBox Search inside a rectangular area (in geo coordinates). + * @param insidePolygon Search inside a polygon (in geo coordinates). + * @param naturalLanguages This parameter changes the default values of certain parameters and settings that work best for a natural language query, such as ignorePlurals, removeStopWords, removeWordsIfNoResults, analyticsTags and ruleContexts. These parameters and settings work well together when the query is formatted in natural language instead of keywords, for example when your user performs a voice search. + * @param ruleContexts Enables contextual rules. + * @param personalizationImpact Define the impact of the Personalization feature. + * @param userToken Associates a certain user token with the current search. + * @param getRankingInfo Retrieve detailed ranking information. + * @param clickAnalytics Enable the Click Analytics feature. + * @param analytics Whether the current query will be taken into account in the Analytics. + * @param analyticsTags List of tags to apply to the query for analytics purposes. + * @param percentileComputation Whether to include or exclude a query from the processing-time percentile computation. + * @param enableABTest Whether this search should participate in running AB tests. + * @param enableReRanking Whether this search should use AI Re-Ranking. + * @param reRankingApplyFilter + */ +@Serializable +public data class BaseSearchParamsWithoutQuery( + + /** Overrides the query parameter and performs a more generic search that can be used to find \"similar\" results. */ + @SerialName(value = "similarQuery") val similarQuery: String? = null, + + /** Filter the query with numeric, facet and/or tag filters. */ + @SerialName(value = "filters") val filters: String? = null, + + @SerialName(value = "facetFilters") val facetFilters: FacetFilters? = null, + + @SerialName(value = "optionalFilters") val optionalFilters: OptionalFilters? = null, + + @SerialName(value = "numericFilters") val numericFilters: NumericFilters? = null, + + @SerialName(value = "tagFilters") val tagFilters: TagFilters? = null, + + /** Determines how to calculate the total score for filtering. */ + @SerialName(value = "sumOrFiltersScores") val sumOrFiltersScores: Boolean? = null, + + /** Retrieve facets and their facet values. */ + @SerialName(value = "facets") val facets: List? = null, + + /** Maximum number of facet values to return for each facet during a regular search. */ + @SerialName(value = "maxValuesPerFacet") val maxValuesPerFacet: Int? = null, + + /** Force faceting to be applied after de-duplication (via the Distinct setting). */ + @SerialName(value = "facetingAfterDistinct") val facetingAfterDistinct: Boolean? = null, + + /** Controls how facet values are fetched. */ + @SerialName(value = "sortFacetValuesBy") val sortFacetValuesBy: String? = null, + + /** Specify the page to retrieve. */ + @SerialName(value = "page") val page: Int? = null, + + /** Specify the offset of the first hit to return. */ + @SerialName(value = "offset") val offset: Int? = null, + + /** Set the number of hits to retrieve (used only with offset). */ + @SerialName(value = "length") val length: Int? = null, + + /** Search for entries around a central geolocation, enabling a geo search within a circular area. */ + @SerialName(value = "aroundLatLng") val aroundLatLng: String? = null, + + /** Search for entries around a given location automatically computed from the requester's IP address. */ + @SerialName(value = "aroundLatLngViaIP") val aroundLatLngViaIP: Boolean? = null, + + @SerialName(value = "aroundRadius") val aroundRadius: AroundRadius? = null, + + /** Precision of geo search (in meters), to add grouping by geo location to the ranking formula. */ + @SerialName(value = "aroundPrecision") val aroundPrecision: Int? = null, + + /** Minimum radius (in meters) used for a geo search when aroundRadius is not set. */ + @SerialName(value = "minimumAroundRadius") val minimumAroundRadius: Int? = null, + + /** Search inside a rectangular area (in geo coordinates). */ + @SerialName(value = "insideBoundingBox") val insideBoundingBox: List? = null, + + /** Search inside a polygon (in geo coordinates). */ + @SerialName(value = "insidePolygon") val insidePolygon: List? = null, + + /** This parameter changes the default values of certain parameters and settings that work best for a natural language query, such as ignorePlurals, removeStopWords, removeWordsIfNoResults, analyticsTags and ruleContexts. These parameters and settings work well together when the query is formatted in natural language instead of keywords, for example when your user performs a voice search. */ + @SerialName(value = "naturalLanguages") val naturalLanguages: List? = null, + + /** Enables contextual rules. */ + @SerialName(value = "ruleContexts") val ruleContexts: List? = null, + + /** Define the impact of the Personalization feature. */ + @SerialName(value = "personalizationImpact") val personalizationImpact: Int? = null, + + /** Associates a certain user token with the current search. */ + @SerialName(value = "userToken") val userToken: String? = null, + + /** Retrieve detailed ranking information. */ + @SerialName(value = "getRankingInfo") val getRankingInfo: Boolean? = null, + + /** Enable the Click Analytics feature. */ + @SerialName(value = "clickAnalytics") val clickAnalytics: Boolean? = null, + + /** Whether the current query will be taken into account in the Analytics. */ + @SerialName(value = "analytics") val analytics: Boolean? = null, + + /** List of tags to apply to the query for analytics purposes. */ + @SerialName(value = "analyticsTags") val analyticsTags: List? = null, + + /** Whether to include or exclude a query from the processing-time percentile computation. */ + @SerialName(value = "percentileComputation") val percentileComputation: Boolean? = null, + + /** Whether this search should participate in running AB tests. */ + @SerialName(value = "enableABTest") val enableABTest: Boolean? = null, + + /** Whether this search should use AI Re-Ranking. */ + @SerialName(value = "enableReRanking") val enableReRanking: Boolean? = null, + + @SerialName(value = "reRankingApplyFilter") val reRankingApplyFilter: ReRankingApplyFilter? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BaseSearchResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BaseSearchResponse.kt new file mode 100644 index 0000000000..37bf194345 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BaseSearchResponse.kt @@ -0,0 +1,115 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * BaseSearchResponse + * + * @param exhaustiveNbHits Indicate if the nbHits count was exhaustive or approximate. + * @param hitsPerPage Set the number of hits per page. + * @param nbHits Number of hits that the search query matched. + * @param nbPages Number of pages available for the current query. + * @param page Specify the page to retrieve. + * @param params A url-encoded string of all search parameters. + * @param processingTimeMS Time the server took to process the request, in milliseconds. + * @param query The text to search in the index. + * @param abTestID If a search encounters an index that is being A/B tested, abTestID reports the ongoing A/B test ID. + * @param abTestVariantID If a search encounters an index that is being A/B tested, abTestVariantID reports the variant ID of the index used (starting at 1). + * @param aroundLatLng The computed geo location. + * @param automaticRadius The automatically computed radius. For legacy reasons, this parameter is a string and not an integer. + * @param exhaustiveFacetsCount Whether the facet count is exhaustive or approximate. + * @param exhaustiveTypo Indicate if the typo-tolerance search was exhaustive or approximate (only included when typo-tolerance is enabled). + * @param facets A mapping of each facet name to the corresponding facet counts. + * @param facetsStats Statistics for numerical facets. + * @param index Index name used for the query. + * @param indexUsed Index name used for the query. In the case of an A/B test, the targeted index isn't always the index used by the query. + * @param message Used to return warnings about the query. + * @param nbSortedHits The number of hits selected and sorted by the relevant sort algorithm. + * @param redirect + * @param parsedQuery The query string that will be searched, after normalization. + * @param queryAfterRemoval A markup text indicating which parts of the original query have been removed in order to retrieve a non-empty result set. + * @param serverUsed Actual host name of the server that processed the request. + * @param userData Lets you store custom data in your indices. + * @param renderingContent + */ +@Serializable +public data class BaseSearchResponse( + + /** Indicate if the nbHits count was exhaustive or approximate. */ + @SerialName(value = "exhaustiveNbHits") val exhaustiveNbHits: Boolean, + + /** Set the number of hits per page. */ + @SerialName(value = "hitsPerPage") val hitsPerPage: Int, + + /** Number of hits that the search query matched. */ + @SerialName(value = "nbHits") val nbHits: Int, + + /** Number of pages available for the current query. */ + @SerialName(value = "nbPages") val nbPages: Int, + + /** Specify the page to retrieve. */ + @SerialName(value = "page") val page: Int, + + /** A url-encoded string of all search parameters. */ + @SerialName(value = "params") val params: String, + + /** Time the server took to process the request, in milliseconds. */ + @SerialName(value = "processingTimeMS") val processingTimeMS: Int, + + /** The text to search in the index. */ + @SerialName(value = "query") val query: String, + + /** If a search encounters an index that is being A/B tested, abTestID reports the ongoing A/B test ID. */ + @SerialName(value = "abTestID") val abTestID: Int? = null, + + /** If a search encounters an index that is being A/B tested, abTestVariantID reports the variant ID of the index used (starting at 1). */ + @SerialName(value = "abTestVariantID") val abTestVariantID: Int? = null, + + /** The computed geo location. */ + @SerialName(value = "aroundLatLng") val aroundLatLng: String? = null, + + /** The automatically computed radius. For legacy reasons, this parameter is a string and not an integer. */ + @SerialName(value = "automaticRadius") val automaticRadius: String? = null, + + /** Whether the facet count is exhaustive or approximate. */ + @SerialName(value = "exhaustiveFacetsCount") val exhaustiveFacetsCount: Boolean? = null, + + /** Indicate if the typo-tolerance search was exhaustive or approximate (only included when typo-tolerance is enabled). */ + @SerialName(value = "exhaustiveTypo") val exhaustiveTypo: Boolean? = null, + + /** A mapping of each facet name to the corresponding facet counts. */ + @SerialName(value = "facets") val facets: Map>? = null, + + /** Statistics for numerical facets. */ + @SerialName(value = "facets_stats") val facetsStats: Map? = null, + + /** Index name used for the query. */ + @SerialName(value = "index") val index: String? = null, + + /** Index name used for the query. In the case of an A/B test, the targeted index isn't always the index used by the query. */ + @SerialName(value = "indexUsed") val indexUsed: String? = null, + + /** Used to return warnings about the query. */ + @SerialName(value = "message") val message: String? = null, + + /** The number of hits selected and sorted by the relevant sort algorithm. */ + @SerialName(value = "nbSortedHits") val nbSortedHits: Int? = null, + + @SerialName(value = "redirect") val redirect: BaseSearchResponseRedirect? = null, + + /** The query string that will be searched, after normalization. */ + @SerialName(value = "parsedQuery") val parsedQuery: String? = null, + + /** A markup text indicating which parts of the original query have been removed in order to retrieve a non-empty result set. */ + @SerialName(value = "queryAfterRemoval") val queryAfterRemoval: String? = null, + + /** Actual host name of the server that processed the request. */ + @SerialName(value = "serverUsed") val serverUsed: String? = null, + + /** Lets you store custom data in your indices. */ + @SerialName(value = "userData") val userData: JsonObject? = null, + + @SerialName(value = "renderingContent") val renderingContent: RenderingContent? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BaseSearchResponseRedirect.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BaseSearchResponseRedirect.kt new file mode 100644 index 0000000000..19657b5d05 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BaseSearchResponseRedirect.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * This parameter is for internal use only. + * + * @param index + */ +@Serializable +public data class BaseSearchResponseRedirect( + + @SerialName(value = "index") val index: List? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BatchAssignUserIdsParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BatchAssignUserIdsParams.kt new file mode 100644 index 0000000000..44588c4e82 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BatchAssignUserIdsParams.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Assign userID parameters. + * + * @param cluster Name of the cluster. + * @param users userIDs to assign. Note you cannot move users with this method. + */ +@Serializable +public data class BatchAssignUserIdsParams( + + /** Name of the cluster. */ + @SerialName(value = "cluster") val cluster: String, + + /** userIDs to assign. Note you cannot move users with this method. */ + @SerialName(value = "users") val users: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BatchDictionaryEntriesParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BatchDictionaryEntriesParams.kt new file mode 100644 index 0000000000..ea3e3e2331 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BatchDictionaryEntriesParams.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The `batchDictionaryEntries` parameters. + * + * @param requests List of operations to batch. Each operation is described by an `action` and a `body`. + * @param clearExistingDictionaryEntries When `true`, start the batch by removing all the custom entries from the dictionary. + */ +@Serializable +public data class BatchDictionaryEntriesParams( + + /** List of operations to batch. Each operation is described by an `action` and a `body`. */ + @SerialName(value = "requests") val requests: List, + + /** When `true`, start the batch by removing all the custom entries from the dictionary. */ + @SerialName(value = "clearExistingDictionaryEntries") val clearExistingDictionaryEntries: Boolean? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BatchDictionaryEntriesRequest.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BatchDictionaryEntriesRequest.kt new file mode 100644 index 0000000000..39a7e0e8d1 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BatchDictionaryEntriesRequest.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * BatchDictionaryEntriesRequest + * + * @param action + * @param body + */ +@Serializable +public data class BatchDictionaryEntriesRequest( + + @SerialName(value = "action") val action: DictionaryAction, + + @SerialName(value = "body") val body: DictionaryEntry, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BatchParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BatchParams.kt new file mode 100644 index 0000000000..9341c03de9 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BatchParams.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The `multipleBatch` parameters. + * + * @param requests + */ +@Serializable +public data class BatchParams( + + @SerialName(value = "requests") val requests: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BatchRequest.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BatchRequest.kt new file mode 100644 index 0000000000..8f677a5031 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BatchRequest.kt @@ -0,0 +1,20 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * BatchRequest + * + * @param action + * @param body arguments to the operation (depends on the type of the operation). + */ +@Serializable +public data class BatchRequest( + + @SerialName(value = "action") val action: Action, + + /** arguments to the operation (depends on the type of the operation). */ + @SerialName(value = "body") val body: JsonObject, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BatchResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BatchResponse.kt new file mode 100644 index 0000000000..ee0ead37eb --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BatchResponse.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * BatchResponse + * + * @param taskID taskID of the task to wait for. + * @param objectIDs List of objectID. + */ +@Serializable +public data class BatchResponse( + + /** taskID of the task to wait for. */ + @SerialName(value = "taskID") val taskID: Long, + + /** List of objectID. */ + @SerialName(value = "objectIDs") val objectIDs: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BatchWriteParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BatchWriteParams.kt new file mode 100644 index 0000000000..1bdfe8c049 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BatchWriteParams.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The `batch` parameters. + * + * @param requests + */ +@Serializable +public data class BatchWriteParams( + + @SerialName(value = "requests") val requests: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BrowseParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BrowseParams.kt new file mode 100644 index 0000000000..ea28051653 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BrowseParams.kt @@ -0,0 +1,318 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * BrowseParams + */ +@Serializable(BrowseParamsSerializer::class) +public sealed interface BrowseParams { + + public companion object { + + /** + * BrowseParamsObject + * + * @param query The text to search in the index. + * @param similarQuery Overrides the query parameter and performs a more generic search that can be used to find \"similar\" results. + * @param filters Filter the query with numeric, facet and/or tag filters. + * @param facetFilters + * @param optionalFilters + * @param numericFilters + * @param tagFilters + * @param sumOrFiltersScores Determines how to calculate the total score for filtering. + * @param facets Retrieve facets and their facet values. + * @param maxValuesPerFacet Maximum number of facet values to return for each facet during a regular search. + * @param facetingAfterDistinct Force faceting to be applied after de-duplication (via the Distinct setting). + * @param sortFacetValuesBy Controls how facet values are fetched. + * @param page Specify the page to retrieve. + * @param offset Specify the offset of the first hit to return. + * @param length Set the number of hits to retrieve (used only with offset). + * @param aroundLatLng Search for entries around a central geolocation, enabling a geo search within a circular area. + * @param aroundLatLngViaIP Search for entries around a given location automatically computed from the requester's IP address. + * @param aroundRadius + * @param aroundPrecision Precision of geo search (in meters), to add grouping by geo location to the ranking formula. + * @param minimumAroundRadius Minimum radius (in meters) used for a geo search when aroundRadius is not set. + * @param insideBoundingBox Search inside a rectangular area (in geo coordinates). + * @param insidePolygon Search inside a polygon (in geo coordinates). + * @param naturalLanguages This parameter changes the default values of certain parameters and settings that work best for a natural language query, such as ignorePlurals, removeStopWords, removeWordsIfNoResults, analyticsTags and ruleContexts. These parameters and settings work well together when the query is formatted in natural language instead of keywords, for example when your user performs a voice search. + * @param ruleContexts Enables contextual rules. + * @param personalizationImpact Define the impact of the Personalization feature. + * @param userToken Associates a certain user token with the current search. + * @param getRankingInfo Retrieve detailed ranking information. + * @param clickAnalytics Enable the Click Analytics feature. + * @param analytics Whether the current query will be taken into account in the Analytics. + * @param analyticsTags List of tags to apply to the query for analytics purposes. + * @param percentileComputation Whether to include or exclude a query from the processing-time percentile computation. + * @param enableABTest Whether this search should participate in running AB tests. + * @param enableReRanking Whether this search should use AI Re-Ranking. + * @param reRankingApplyFilter + * @param attributesForFaceting The complete list of attributes that will be used for faceting. + * @param attributesToRetrieve This parameter controls which attributes to retrieve and which not to retrieve. + * @param restrictSearchableAttributes Restricts a given query to look in only a subset of your searchable attributes. + * @param ranking Controls how Algolia should sort your results. + * @param customRanking Specifies the custom ranking criterion. + * @param relevancyStrictness Controls the relevancy threshold below which less relevant results aren't included in the results. + * @param attributesToHighlight List of attributes to highlight. + * @param attributesToSnippet List of attributes to snippet, with an optional maximum number of words to snippet. + * @param highlightPreTag The HTML string to insert before the highlighted parts in all highlight and snippet results. + * @param highlightPostTag The HTML string to insert after the highlighted parts in all highlight and snippet results. + * @param snippetEllipsisText String used as an ellipsis indicator when a snippet is truncated. + * @param restrictHighlightAndSnippetArrays Restrict highlighting and snippeting to items that matched the query. + * @param hitsPerPage Set the number of hits per page. + * @param minWordSizefor1Typo Minimum number of characters a word in the query string must contain to accept matches with 1 typo. + * @param minWordSizefor2Typos Minimum number of characters a word in the query string must contain to accept matches with 2 typos. + * @param typoTolerance + * @param allowTyposOnNumericTokens Whether to allow typos on numbers (\"numeric tokens\") in the query string. + * @param disableTypoToleranceOnAttributes List of attributes on which you want to disable typo tolerance. + * @param ignorePlurals + * @param removeStopWords + * @param keepDiacriticsOnCharacters List of characters that the engine shouldn't automatically normalize. + * @param queryLanguages Sets the languages to be used by language-specific settings and functionalities such as ignorePlurals, removeStopWords, and CJK word-detection. + * @param decompoundQuery Splits compound words into their composing atoms in the query. + * @param enableRules Whether Rules should be globally enabled. + * @param enablePersonalization Enable the Personalization feature. + * @param queryType + * @param removeWordsIfNoResults + * @param mode + * @param semanticSearch + * @param advancedSyntax Enables the advanced query syntax. + * @param optionalWords A list of words that should be considered as optional when found in the query. + * @param disableExactOnAttributes List of attributes on which you want to disable the exact ranking criterion. + * @param exactOnSingleWordQuery + * @param alternativesAsExact List of alternatives that should be considered an exact match by the exact ranking criterion. + * @param advancedSyntaxFeatures Allows you to specify which advanced syntax features are active when ‘advancedSyntax' is enabled. + * @param explain Enriches the API’s response with meta-information as to how the query was processed. + * @param distinct + * @param attributeForDistinct Name of the de-duplication attribute to be used with the distinct feature. + * @param synonyms Whether to take into account an index's synonyms for a particular search. + * @param replaceSynonymsInHighlight Whether to highlight and snippet the original word that matches the synonym or the synonym itself. + * @param minProximity Precision of the proximity ranking criterion. + * @param responseFields Choose which fields to return in the API response. This parameters applies to search and browse queries. + * @param maxFacetHits Maximum number of facet hits to return during a search for facet values. For performance reasons, the maximum allowed number of returned values is 100. + * @param attributeCriteriaComputedByMinProximity When attribute is ranked above proximity in your ranking formula, proximity is used to select which searchable attribute is matched in the attribute ranking stage. + * @param renderingContent + * @param cursor Cursor indicating the location to resume browsing from. Must match the value returned by the previous call. + */ + public fun BrowseParamsObject( + query: String? = null, + similarQuery: String? = null, + filters: String? = null, + facetFilters: FacetFilters? = null, + optionalFilters: OptionalFilters? = null, + numericFilters: NumericFilters? = null, + tagFilters: TagFilters? = null, + sumOrFiltersScores: Boolean? = null, + facets: List? = null, + maxValuesPerFacet: Int? = null, + facetingAfterDistinct: Boolean? = null, + sortFacetValuesBy: String? = null, + page: Int? = null, + offset: Int? = null, + length: Int? = null, + aroundLatLng: String? = null, + aroundLatLngViaIP: Boolean? = null, + aroundRadius: AroundRadius? = null, + aroundPrecision: Int? = null, + minimumAroundRadius: Int? = null, + insideBoundingBox: List? = null, + insidePolygon: List? = null, + naturalLanguages: List? = null, + ruleContexts: List? = null, + personalizationImpact: Int? = null, + userToken: String? = null, + getRankingInfo: Boolean? = null, + clickAnalytics: Boolean? = null, + analytics: Boolean? = null, + analyticsTags: List? = null, + percentileComputation: Boolean? = null, + enableABTest: Boolean? = null, + enableReRanking: Boolean? = null, + reRankingApplyFilter: ReRankingApplyFilter? = null, + attributesForFaceting: List? = null, + attributesToRetrieve: List? = null, + restrictSearchableAttributes: List? = null, + ranking: List? = null, + customRanking: List? = null, + relevancyStrictness: Int? = null, + attributesToHighlight: List? = null, + attributesToSnippet: List? = null, + highlightPreTag: String? = null, + highlightPostTag: String? = null, + snippetEllipsisText: String? = null, + restrictHighlightAndSnippetArrays: Boolean? = null, + hitsPerPage: Int? = null, + minWordSizefor1Typo: Int? = null, + minWordSizefor2Typos: Int? = null, + typoTolerance: TypoTolerance? = null, + allowTyposOnNumericTokens: Boolean? = null, + disableTypoToleranceOnAttributes: List? = null, + ignorePlurals: IgnorePlurals? = null, + removeStopWords: RemoveStopWords? = null, + keepDiacriticsOnCharacters: String? = null, + queryLanguages: List? = null, + decompoundQuery: Boolean? = null, + enableRules: Boolean? = null, + enablePersonalization: Boolean? = null, + queryType: QueryType? = null, + removeWordsIfNoResults: RemoveWordsIfNoResults? = null, + mode: Mode? = null, + semanticSearch: IndexSettingsAsSearchParamsSemanticSearch? = null, + advancedSyntax: Boolean? = null, + optionalWords: List? = null, + disableExactOnAttributes: List? = null, + exactOnSingleWordQuery: ExactOnSingleWordQuery? = null, + alternativesAsExact: List? = null, + advancedSyntaxFeatures: List? = null, + explain: List? = null, + distinct: Distinct? = null, + attributeForDistinct: String? = null, + synonyms: Boolean? = null, + replaceSynonymsInHighlight: Boolean? = null, + minProximity: Int? = null, + responseFields: List? = null, + maxFacetHits: Int? = null, + attributeCriteriaComputedByMinProximity: Boolean? = null, + renderingContent: RenderingContent? = null, + cursor: String? = null, + ): BrowseParamsObject = com.algolia.client.model.search.BrowseParamsObject( + query = query, + similarQuery = similarQuery, + filters = filters, + facetFilters = facetFilters, + optionalFilters = optionalFilters, + numericFilters = numericFilters, + tagFilters = tagFilters, + sumOrFiltersScores = sumOrFiltersScores, + facets = facets, + maxValuesPerFacet = maxValuesPerFacet, + facetingAfterDistinct = facetingAfterDistinct, + sortFacetValuesBy = sortFacetValuesBy, + page = page, + offset = offset, + length = length, + aroundLatLng = aroundLatLng, + aroundLatLngViaIP = aroundLatLngViaIP, + aroundRadius = aroundRadius, + aroundPrecision = aroundPrecision, + minimumAroundRadius = minimumAroundRadius, + insideBoundingBox = insideBoundingBox, + insidePolygon = insidePolygon, + naturalLanguages = naturalLanguages, + ruleContexts = ruleContexts, + personalizationImpact = personalizationImpact, + userToken = userToken, + getRankingInfo = getRankingInfo, + clickAnalytics = clickAnalytics, + analytics = analytics, + analyticsTags = analyticsTags, + percentileComputation = percentileComputation, + enableABTest = enableABTest, + enableReRanking = enableReRanking, + reRankingApplyFilter = reRankingApplyFilter, + attributesForFaceting = attributesForFaceting, + attributesToRetrieve = attributesToRetrieve, + restrictSearchableAttributes = restrictSearchableAttributes, + ranking = ranking, + customRanking = customRanking, + relevancyStrictness = relevancyStrictness, + attributesToHighlight = attributesToHighlight, + attributesToSnippet = attributesToSnippet, + highlightPreTag = highlightPreTag, + highlightPostTag = highlightPostTag, + snippetEllipsisText = snippetEllipsisText, + restrictHighlightAndSnippetArrays = restrictHighlightAndSnippetArrays, + hitsPerPage = hitsPerPage, + minWordSizefor1Typo = minWordSizefor1Typo, + minWordSizefor2Typos = minWordSizefor2Typos, + typoTolerance = typoTolerance, + allowTyposOnNumericTokens = allowTyposOnNumericTokens, + disableTypoToleranceOnAttributes = disableTypoToleranceOnAttributes, + ignorePlurals = ignorePlurals, + removeStopWords = removeStopWords, + keepDiacriticsOnCharacters = keepDiacriticsOnCharacters, + queryLanguages = queryLanguages, + decompoundQuery = decompoundQuery, + enableRules = enableRules, + enablePersonalization = enablePersonalization, + queryType = queryType, + removeWordsIfNoResults = removeWordsIfNoResults, + mode = mode, + semanticSearch = semanticSearch, + advancedSyntax = advancedSyntax, + optionalWords = optionalWords, + disableExactOnAttributes = disableExactOnAttributes, + exactOnSingleWordQuery = exactOnSingleWordQuery, + alternativesAsExact = alternativesAsExact, + advancedSyntaxFeatures = advancedSyntaxFeatures, + explain = explain, + distinct = distinct, + attributeForDistinct = attributeForDistinct, + synonyms = synonyms, + replaceSynonymsInHighlight = replaceSynonymsInHighlight, + minProximity = minProximity, + responseFields = responseFields, + maxFacetHits = maxFacetHits, + attributeCriteriaComputedByMinProximity = attributeCriteriaComputedByMinProximity, + renderingContent = renderingContent, + cursor = cursor, + ) + + /** + * SearchParamsString + * + * @param params Search parameters as URL-encoded query string. + */ + public fun SearchParamsString( + params: String? = null, + ): SearchParamsString = com.algolia.client.model.search.SearchParamsString( + params = params, + ) + } +} + +internal class BrowseParamsSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("BrowseParams") + + override fun serialize(encoder: Encoder, value: BrowseParams) { + when (value) { + is BrowseParamsObject -> BrowseParamsObject.serializer().serialize(encoder, value) + is SearchParamsString -> SearchParamsString.serializer().serialize(encoder, value) + } + } + + override fun deserialize(decoder: Decoder): BrowseParams { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize BrowseParamsObject + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize BrowseParamsObject (error: ${e.message})") + } + } + + // deserialize SearchParamsString + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize SearchParamsString (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BrowseParamsObject.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BrowseParamsObject.kt new file mode 100644 index 0000000000..a753de21bd --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BrowseParamsObject.kt @@ -0,0 +1,317 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * BrowseParamsObject + * + * @param query The text to search in the index. + * @param similarQuery Overrides the query parameter and performs a more generic search that can be used to find \"similar\" results. + * @param filters Filter the query with numeric, facet and/or tag filters. + * @param facetFilters + * @param optionalFilters + * @param numericFilters + * @param tagFilters + * @param sumOrFiltersScores Determines how to calculate the total score for filtering. + * @param facets Retrieve facets and their facet values. + * @param maxValuesPerFacet Maximum number of facet values to return for each facet during a regular search. + * @param facetingAfterDistinct Force faceting to be applied after de-duplication (via the Distinct setting). + * @param sortFacetValuesBy Controls how facet values are fetched. + * @param page Specify the page to retrieve. + * @param offset Specify the offset of the first hit to return. + * @param length Set the number of hits to retrieve (used only with offset). + * @param aroundLatLng Search for entries around a central geolocation, enabling a geo search within a circular area. + * @param aroundLatLngViaIP Search for entries around a given location automatically computed from the requester's IP address. + * @param aroundRadius + * @param aroundPrecision Precision of geo search (in meters), to add grouping by geo location to the ranking formula. + * @param minimumAroundRadius Minimum radius (in meters) used for a geo search when aroundRadius is not set. + * @param insideBoundingBox Search inside a rectangular area (in geo coordinates). + * @param insidePolygon Search inside a polygon (in geo coordinates). + * @param naturalLanguages This parameter changes the default values of certain parameters and settings that work best for a natural language query, such as ignorePlurals, removeStopWords, removeWordsIfNoResults, analyticsTags and ruleContexts. These parameters and settings work well together when the query is formatted in natural language instead of keywords, for example when your user performs a voice search. + * @param ruleContexts Enables contextual rules. + * @param personalizationImpact Define the impact of the Personalization feature. + * @param userToken Associates a certain user token with the current search. + * @param getRankingInfo Retrieve detailed ranking information. + * @param clickAnalytics Enable the Click Analytics feature. + * @param analytics Whether the current query will be taken into account in the Analytics. + * @param analyticsTags List of tags to apply to the query for analytics purposes. + * @param percentileComputation Whether to include or exclude a query from the processing-time percentile computation. + * @param enableABTest Whether this search should participate in running AB tests. + * @param enableReRanking Whether this search should use AI Re-Ranking. + * @param reRankingApplyFilter + * @param attributesForFaceting The complete list of attributes that will be used for faceting. + * @param attributesToRetrieve This parameter controls which attributes to retrieve and which not to retrieve. + * @param restrictSearchableAttributes Restricts a given query to look in only a subset of your searchable attributes. + * @param ranking Controls how Algolia should sort your results. + * @param customRanking Specifies the custom ranking criterion. + * @param relevancyStrictness Controls the relevancy threshold below which less relevant results aren't included in the results. + * @param attributesToHighlight List of attributes to highlight. + * @param attributesToSnippet List of attributes to snippet, with an optional maximum number of words to snippet. + * @param highlightPreTag The HTML string to insert before the highlighted parts in all highlight and snippet results. + * @param highlightPostTag The HTML string to insert after the highlighted parts in all highlight and snippet results. + * @param snippetEllipsisText String used as an ellipsis indicator when a snippet is truncated. + * @param restrictHighlightAndSnippetArrays Restrict highlighting and snippeting to items that matched the query. + * @param hitsPerPage Set the number of hits per page. + * @param minWordSizefor1Typo Minimum number of characters a word in the query string must contain to accept matches with 1 typo. + * @param minWordSizefor2Typos Minimum number of characters a word in the query string must contain to accept matches with 2 typos. + * @param typoTolerance + * @param allowTyposOnNumericTokens Whether to allow typos on numbers (\"numeric tokens\") in the query string. + * @param disableTypoToleranceOnAttributes List of attributes on which you want to disable typo tolerance. + * @param ignorePlurals + * @param removeStopWords + * @param keepDiacriticsOnCharacters List of characters that the engine shouldn't automatically normalize. + * @param queryLanguages Sets the languages to be used by language-specific settings and functionalities such as ignorePlurals, removeStopWords, and CJK word-detection. + * @param decompoundQuery Splits compound words into their composing atoms in the query. + * @param enableRules Whether Rules should be globally enabled. + * @param enablePersonalization Enable the Personalization feature. + * @param queryType + * @param removeWordsIfNoResults + * @param mode + * @param semanticSearch + * @param advancedSyntax Enables the advanced query syntax. + * @param optionalWords A list of words that should be considered as optional when found in the query. + * @param disableExactOnAttributes List of attributes on which you want to disable the exact ranking criterion. + * @param exactOnSingleWordQuery + * @param alternativesAsExact List of alternatives that should be considered an exact match by the exact ranking criterion. + * @param advancedSyntaxFeatures Allows you to specify which advanced syntax features are active when ‘advancedSyntax' is enabled. + * @param explain Enriches the API’s response with meta-information as to how the query was processed. + * @param distinct + * @param attributeForDistinct Name of the de-duplication attribute to be used with the distinct feature. + * @param synonyms Whether to take into account an index's synonyms for a particular search. + * @param replaceSynonymsInHighlight Whether to highlight and snippet the original word that matches the synonym or the synonym itself. + * @param minProximity Precision of the proximity ranking criterion. + * @param responseFields Choose which fields to return in the API response. This parameters applies to search and browse queries. + * @param maxFacetHits Maximum number of facet hits to return during a search for facet values. For performance reasons, the maximum allowed number of returned values is 100. + * @param attributeCriteriaComputedByMinProximity When attribute is ranked above proximity in your ranking formula, proximity is used to select which searchable attribute is matched in the attribute ranking stage. + * @param renderingContent + * @param cursor Cursor indicating the location to resume browsing from. Must match the value returned by the previous call. + */ +@Serializable +public data class BrowseParamsObject( + + /** The text to search in the index. */ + @SerialName(value = "query") val query: String? = null, + + /** Overrides the query parameter and performs a more generic search that can be used to find \"similar\" results. */ + @SerialName(value = "similarQuery") val similarQuery: String? = null, + + /** Filter the query with numeric, facet and/or tag filters. */ + @SerialName(value = "filters") val filters: String? = null, + + @SerialName(value = "facetFilters") val facetFilters: FacetFilters? = null, + + @SerialName(value = "optionalFilters") val optionalFilters: OptionalFilters? = null, + + @SerialName(value = "numericFilters") val numericFilters: NumericFilters? = null, + + @SerialName(value = "tagFilters") val tagFilters: TagFilters? = null, + + /** Determines how to calculate the total score for filtering. */ + @SerialName(value = "sumOrFiltersScores") val sumOrFiltersScores: Boolean? = null, + + /** Retrieve facets and their facet values. */ + @SerialName(value = "facets") val facets: List? = null, + + /** Maximum number of facet values to return for each facet during a regular search. */ + @SerialName(value = "maxValuesPerFacet") val maxValuesPerFacet: Int? = null, + + /** Force faceting to be applied after de-duplication (via the Distinct setting). */ + @SerialName(value = "facetingAfterDistinct") val facetingAfterDistinct: Boolean? = null, + + /** Controls how facet values are fetched. */ + @SerialName(value = "sortFacetValuesBy") val sortFacetValuesBy: String? = null, + + /** Specify the page to retrieve. */ + @SerialName(value = "page") val page: Int? = null, + + /** Specify the offset of the first hit to return. */ + @SerialName(value = "offset") val offset: Int? = null, + + /** Set the number of hits to retrieve (used only with offset). */ + @SerialName(value = "length") val length: Int? = null, + + /** Search for entries around a central geolocation, enabling a geo search within a circular area. */ + @SerialName(value = "aroundLatLng") val aroundLatLng: String? = null, + + /** Search for entries around a given location automatically computed from the requester's IP address. */ + @SerialName(value = "aroundLatLngViaIP") val aroundLatLngViaIP: Boolean? = null, + + @SerialName(value = "aroundRadius") val aroundRadius: AroundRadius? = null, + + /** Precision of geo search (in meters), to add grouping by geo location to the ranking formula. */ + @SerialName(value = "aroundPrecision") val aroundPrecision: Int? = null, + + /** Minimum radius (in meters) used for a geo search when aroundRadius is not set. */ + @SerialName(value = "minimumAroundRadius") val minimumAroundRadius: Int? = null, + + /** Search inside a rectangular area (in geo coordinates). */ + @SerialName(value = "insideBoundingBox") val insideBoundingBox: List? = null, + + /** Search inside a polygon (in geo coordinates). */ + @SerialName(value = "insidePolygon") val insidePolygon: List? = null, + + /** This parameter changes the default values of certain parameters and settings that work best for a natural language query, such as ignorePlurals, removeStopWords, removeWordsIfNoResults, analyticsTags and ruleContexts. These parameters and settings work well together when the query is formatted in natural language instead of keywords, for example when your user performs a voice search. */ + @SerialName(value = "naturalLanguages") val naturalLanguages: List? = null, + + /** Enables contextual rules. */ + @SerialName(value = "ruleContexts") val ruleContexts: List? = null, + + /** Define the impact of the Personalization feature. */ + @SerialName(value = "personalizationImpact") val personalizationImpact: Int? = null, + + /** Associates a certain user token with the current search. */ + @SerialName(value = "userToken") val userToken: String? = null, + + /** Retrieve detailed ranking information. */ + @SerialName(value = "getRankingInfo") val getRankingInfo: Boolean? = null, + + /** Enable the Click Analytics feature. */ + @SerialName(value = "clickAnalytics") val clickAnalytics: Boolean? = null, + + /** Whether the current query will be taken into account in the Analytics. */ + @SerialName(value = "analytics") val analytics: Boolean? = null, + + /** List of tags to apply to the query for analytics purposes. */ + @SerialName(value = "analyticsTags") val analyticsTags: List? = null, + + /** Whether to include or exclude a query from the processing-time percentile computation. */ + @SerialName(value = "percentileComputation") val percentileComputation: Boolean? = null, + + /** Whether this search should participate in running AB tests. */ + @SerialName(value = "enableABTest") val enableABTest: Boolean? = null, + + /** Whether this search should use AI Re-Ranking. */ + @SerialName(value = "enableReRanking") val enableReRanking: Boolean? = null, + + @SerialName(value = "reRankingApplyFilter") val reRankingApplyFilter: ReRankingApplyFilter? = null, + + /** The complete list of attributes that will be used for faceting. */ + @SerialName(value = "attributesForFaceting") val attributesForFaceting: List? = null, + + /** This parameter controls which attributes to retrieve and which not to retrieve. */ + @SerialName(value = "attributesToRetrieve") val attributesToRetrieve: List? = null, + + /** Restricts a given query to look in only a subset of your searchable attributes. */ + @SerialName(value = "restrictSearchableAttributes") val restrictSearchableAttributes: List? = null, + + /** Controls how Algolia should sort your results. */ + @SerialName(value = "ranking") val ranking: List? = null, + + /** Specifies the custom ranking criterion. */ + @SerialName(value = "customRanking") val customRanking: List? = null, + + /** Controls the relevancy threshold below which less relevant results aren't included in the results. */ + @SerialName(value = "relevancyStrictness") val relevancyStrictness: Int? = null, + + /** List of attributes to highlight. */ + @SerialName(value = "attributesToHighlight") val attributesToHighlight: List? = null, + + /** List of attributes to snippet, with an optional maximum number of words to snippet. */ + @SerialName(value = "attributesToSnippet") val attributesToSnippet: List? = null, + + /** The HTML string to insert before the highlighted parts in all highlight and snippet results. */ + @SerialName(value = "highlightPreTag") val highlightPreTag: String? = null, + + /** The HTML string to insert after the highlighted parts in all highlight and snippet results. */ + @SerialName(value = "highlightPostTag") val highlightPostTag: String? = null, + + /** String used as an ellipsis indicator when a snippet is truncated. */ + @SerialName(value = "snippetEllipsisText") val snippetEllipsisText: String? = null, + + /** Restrict highlighting and snippeting to items that matched the query. */ + @SerialName(value = "restrictHighlightAndSnippetArrays") val restrictHighlightAndSnippetArrays: Boolean? = null, + + /** Set the number of hits per page. */ + @SerialName(value = "hitsPerPage") val hitsPerPage: Int? = null, + + /** Minimum number of characters a word in the query string must contain to accept matches with 1 typo. */ + @SerialName(value = "minWordSizefor1Typo") val minWordSizefor1Typo: Int? = null, + + /** Minimum number of characters a word in the query string must contain to accept matches with 2 typos. */ + @SerialName(value = "minWordSizefor2Typos") val minWordSizefor2Typos: Int? = null, + + @SerialName(value = "typoTolerance") val typoTolerance: TypoTolerance? = null, + + /** Whether to allow typos on numbers (\"numeric tokens\") in the query string. */ + @SerialName(value = "allowTyposOnNumericTokens") val allowTyposOnNumericTokens: Boolean? = null, + + /** List of attributes on which you want to disable typo tolerance. */ + @SerialName(value = "disableTypoToleranceOnAttributes") val disableTypoToleranceOnAttributes: List? = null, + + @SerialName(value = "ignorePlurals") val ignorePlurals: IgnorePlurals? = null, + + @SerialName(value = "removeStopWords") val removeStopWords: RemoveStopWords? = null, + + /** List of characters that the engine shouldn't automatically normalize. */ + @SerialName(value = "keepDiacriticsOnCharacters") val keepDiacriticsOnCharacters: String? = null, + + /** Sets the languages to be used by language-specific settings and functionalities such as ignorePlurals, removeStopWords, and CJK word-detection. */ + @SerialName(value = "queryLanguages") val queryLanguages: List? = null, + + /** Splits compound words into their composing atoms in the query. */ + @SerialName(value = "decompoundQuery") val decompoundQuery: Boolean? = null, + + /** Whether Rules should be globally enabled. */ + @SerialName(value = "enableRules") val enableRules: Boolean? = null, + + /** Enable the Personalization feature. */ + @SerialName(value = "enablePersonalization") val enablePersonalization: Boolean? = null, + + @SerialName(value = "queryType") val queryType: QueryType? = null, + + @SerialName(value = "removeWordsIfNoResults") val removeWordsIfNoResults: RemoveWordsIfNoResults? = null, + + @SerialName(value = "mode") val mode: Mode? = null, + + @SerialName(value = "semanticSearch") val semanticSearch: IndexSettingsAsSearchParamsSemanticSearch? = null, + + /** Enables the advanced query syntax. */ + @SerialName(value = "advancedSyntax") val advancedSyntax: Boolean? = null, + + /** A list of words that should be considered as optional when found in the query. */ + @SerialName(value = "optionalWords") val optionalWords: List? = null, + + /** List of attributes on which you want to disable the exact ranking criterion. */ + @SerialName(value = "disableExactOnAttributes") val disableExactOnAttributes: List? = null, + + @SerialName(value = "exactOnSingleWordQuery") val exactOnSingleWordQuery: ExactOnSingleWordQuery? = null, + + /** List of alternatives that should be considered an exact match by the exact ranking criterion. */ + @SerialName(value = "alternativesAsExact") val alternativesAsExact: List? = null, + + /** Allows you to specify which advanced syntax features are active when ‘advancedSyntax' is enabled. */ + @SerialName(value = "advancedSyntaxFeatures") val advancedSyntaxFeatures: List? = null, + + /** Enriches the API’s response with meta-information as to how the query was processed. */ + @SerialName(value = "explain") val explain: List? = null, + + @SerialName(value = "distinct") val distinct: Distinct? = null, + + /** Name of the de-duplication attribute to be used with the distinct feature. */ + @SerialName(value = "attributeForDistinct") val attributeForDistinct: String? = null, + + /** Whether to take into account an index's synonyms for a particular search. */ + @SerialName(value = "synonyms") val synonyms: Boolean? = null, + + /** Whether to highlight and snippet the original word that matches the synonym or the synonym itself. */ + @SerialName(value = "replaceSynonymsInHighlight") val replaceSynonymsInHighlight: Boolean? = null, + + /** Precision of the proximity ranking criterion. */ + @SerialName(value = "minProximity") val minProximity: Int? = null, + + /** Choose which fields to return in the API response. This parameters applies to search and browse queries. */ + @SerialName(value = "responseFields") val responseFields: List? = null, + + /** Maximum number of facet hits to return during a search for facet values. For performance reasons, the maximum allowed number of returned values is 100. */ + @SerialName(value = "maxFacetHits") val maxFacetHits: Int? = null, + + /** When attribute is ranked above proximity in your ranking formula, proximity is used to select which searchable attribute is matched in the attribute ranking stage. */ + @SerialName(value = "attributeCriteriaComputedByMinProximity") val attributeCriteriaComputedByMinProximity: Boolean? = null, + + @SerialName(value = "renderingContent") val renderingContent: RenderingContent? = null, + + /** Cursor indicating the location to resume browsing from. Must match the value returned by the previous call. */ + @SerialName(value = "cursor") val cursor: String? = null, +) : BrowseParams diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BrowseResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BrowseResponse.kt new file mode 100644 index 0000000000..6fb89932b5 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BrowseResponse.kt @@ -0,0 +1,122 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * BrowseResponse + * + * @param exhaustiveNbHits Indicate if the nbHits count was exhaustive or approximate. + * @param hitsPerPage Set the number of hits per page. + * @param nbHits Number of hits that the search query matched. + * @param nbPages Number of pages available for the current query. + * @param page Specify the page to retrieve. + * @param params A url-encoded string of all search parameters. + * @param processingTimeMS Time the server took to process the request, in milliseconds. + * @param query The text to search in the index. + * @param hits + * @param abTestID If a search encounters an index that is being A/B tested, abTestID reports the ongoing A/B test ID. + * @param abTestVariantID If a search encounters an index that is being A/B tested, abTestVariantID reports the variant ID of the index used (starting at 1). + * @param aroundLatLng The computed geo location. + * @param automaticRadius The automatically computed radius. For legacy reasons, this parameter is a string and not an integer. + * @param exhaustiveFacetsCount Whether the facet count is exhaustive or approximate. + * @param exhaustiveTypo Indicate if the typo-tolerance search was exhaustive or approximate (only included when typo-tolerance is enabled). + * @param facets A mapping of each facet name to the corresponding facet counts. + * @param facetsStats Statistics for numerical facets. + * @param index Index name used for the query. + * @param indexUsed Index name used for the query. In the case of an A/B test, the targeted index isn't always the index used by the query. + * @param message Used to return warnings about the query. + * @param nbSortedHits The number of hits selected and sorted by the relevant sort algorithm. + * @param redirect + * @param parsedQuery The query string that will be searched, after normalization. + * @param queryAfterRemoval A markup text indicating which parts of the original query have been removed in order to retrieve a non-empty result set. + * @param serverUsed Actual host name of the server that processed the request. + * @param userData Lets you store custom data in your indices. + * @param renderingContent + * @param cursor Cursor indicating the location to resume browsing from. Must match the value returned by the previous call. + */ +@Serializable +public data class BrowseResponse( + + /** Indicate if the nbHits count was exhaustive or approximate. */ + @SerialName(value = "exhaustiveNbHits") val exhaustiveNbHits: Boolean, + + /** Set the number of hits per page. */ + @SerialName(value = "hitsPerPage") val hitsPerPage: Int, + + /** Number of hits that the search query matched. */ + @SerialName(value = "nbHits") val nbHits: Int, + + /** Number of pages available for the current query. */ + @SerialName(value = "nbPages") val nbPages: Int, + + /** Specify the page to retrieve. */ + @SerialName(value = "page") val page: Int, + + /** A url-encoded string of all search parameters. */ + @SerialName(value = "params") val params: String, + + /** Time the server took to process the request, in milliseconds. */ + @SerialName(value = "processingTimeMS") val processingTimeMS: Int, + + /** The text to search in the index. */ + @SerialName(value = "query") val query: String, + + @SerialName(value = "hits") val hits: List, + + /** If a search encounters an index that is being A/B tested, abTestID reports the ongoing A/B test ID. */ + @SerialName(value = "abTestID") val abTestID: Int? = null, + + /** If a search encounters an index that is being A/B tested, abTestVariantID reports the variant ID of the index used (starting at 1). */ + @SerialName(value = "abTestVariantID") val abTestVariantID: Int? = null, + + /** The computed geo location. */ + @SerialName(value = "aroundLatLng") val aroundLatLng: String? = null, + + /** The automatically computed radius. For legacy reasons, this parameter is a string and not an integer. */ + @SerialName(value = "automaticRadius") val automaticRadius: String? = null, + + /** Whether the facet count is exhaustive or approximate. */ + @SerialName(value = "exhaustiveFacetsCount") val exhaustiveFacetsCount: Boolean? = null, + + /** Indicate if the typo-tolerance search was exhaustive or approximate (only included when typo-tolerance is enabled). */ + @SerialName(value = "exhaustiveTypo") val exhaustiveTypo: Boolean? = null, + + /** A mapping of each facet name to the corresponding facet counts. */ + @SerialName(value = "facets") val facets: Map>? = null, + + /** Statistics for numerical facets. */ + @SerialName(value = "facets_stats") val facetsStats: Map? = null, + + /** Index name used for the query. */ + @SerialName(value = "index") val index: String? = null, + + /** Index name used for the query. In the case of an A/B test, the targeted index isn't always the index used by the query. */ + @SerialName(value = "indexUsed") val indexUsed: String? = null, + + /** Used to return warnings about the query. */ + @SerialName(value = "message") val message: String? = null, + + /** The number of hits selected and sorted by the relevant sort algorithm. */ + @SerialName(value = "nbSortedHits") val nbSortedHits: Int? = null, + + @SerialName(value = "redirect") val redirect: BaseSearchResponseRedirect? = null, + + /** The query string that will be searched, after normalization. */ + @SerialName(value = "parsedQuery") val parsedQuery: String? = null, + + /** A markup text indicating which parts of the original query have been removed in order to retrieve a non-empty result set. */ + @SerialName(value = "queryAfterRemoval") val queryAfterRemoval: String? = null, + + /** Actual host name of the server that processed the request. */ + @SerialName(value = "serverUsed") val serverUsed: String? = null, + + /** Lets you store custom data in your indices. */ + @SerialName(value = "userData") val userData: JsonObject? = null, + + @SerialName(value = "renderingContent") val renderingContent: RenderingContent? = null, + + /** Cursor indicating the location to resume browsing from. Must match the value returned by the previous call. */ + @SerialName(value = "cursor") val cursor: String? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BuiltInOperation.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BuiltInOperation.kt new file mode 100644 index 0000000000..49da073242 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BuiltInOperation.kt @@ -0,0 +1,20 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * To update an attribute without pushing the entire record, you can use these built-in operations. + * + * @param operation + * @param `value` the right-hand side argument to the operation, for example, increment or decrement step, value to add or remove. + */ +@Serializable +public data class BuiltInOperation( + + @SerialName(value = "_operation") val operation: BuiltInOperationType, + + /** the right-hand side argument to the operation, for example, increment or decrement step, value to add or remove. */ + @SerialName(value = "value") val `value`: String, +) : AttributeToUpdate diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BuiltInOperationType.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BuiltInOperationType.kt new file mode 100644 index 0000000000..8c81e329c6 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/BuiltInOperationType.kt @@ -0,0 +1,34 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* + +/** + * The operation to apply on the attribute. + */ +@Serializable +public enum class BuiltInOperationType(public val value: kotlin.String) { + + @SerialName(value = "Increment") + Increment("Increment"), + + @SerialName(value = "Decrement") + Decrement("Decrement"), + + @SerialName(value = "Add") + Add("Add"), + + @SerialName(value = "Remove") + Remove("Remove"), + + @SerialName(value = "AddUnique") + AddUnique("AddUnique"), + + @SerialName(value = "IncrementFrom") + IncrementFrom("IncrementFrom"), + + @SerialName(value = "IncrementSet") + IncrementSet("IncrementSet"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Condition.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Condition.kt new file mode 100644 index 0000000000..eacf0e4523 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Condition.kt @@ -0,0 +1,28 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Condition + * + * @param pattern Query pattern syntax. + * @param anchoring + * @param alternatives Whether the pattern matches on plurals, synonyms, and typos. + * @param context Rule context format: [A-Za-z0-9_-]+). + */ +@Serializable +public data class Condition( + + /** Query pattern syntax. */ + @SerialName(value = "pattern") val pattern: String? = null, + + @SerialName(value = "anchoring") val anchoring: Anchoring? = null, + + /** Whether the pattern matches on plurals, synonyms, and typos. */ + @SerialName(value = "alternatives") val alternatives: Boolean? = null, + + /** Rule context format: [A-Za-z0-9_-]+). */ + @SerialName(value = "context") val context: String? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Consequence.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Consequence.kt new file mode 100644 index 0000000000..17fe9d0c9a --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Consequence.kt @@ -0,0 +1,32 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Consequence of the Rule. + * + * @param params + * @param promote Objects to promote as hits. + * @param filterPromotes Only use in combination with the promote consequence. When true, promoted results will be restricted to match the filters of the current search. When false, the promoted results will show up regardless of the filters. + * @param hide Objects to hide from hits. Each object must contain an objectID field. By default, you can hide up to 50 items per rule. + * @param userData Custom JSON object that will be appended to the userData array in the response. This object isn't interpreted by the API. It's limited to 1kB of minified JSON. + */ +@Serializable +public data class Consequence( + + @SerialName(value = "params") val params: ConsequenceParams? = null, + + /** Objects to promote as hits. */ + @SerialName(value = "promote") val promote: List? = null, + + /** Only use in combination with the promote consequence. When true, promoted results will be restricted to match the filters of the current search. When false, the promoted results will show up regardless of the filters. */ + @SerialName(value = "filterPromotes") val filterPromotes: Boolean? = null, + + /** Objects to hide from hits. Each object must contain an objectID field. By default, you can hide up to 50 items per rule. */ + @SerialName(value = "hide") val hide: List? = null, + + /** Custom JSON object that will be appended to the userData array in the response. This object isn't interpreted by the API. It's limited to 1kB of minified JSON. */ + @SerialName(value = "userData") val userData: JsonObject? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ConsequenceHide.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ConsequenceHide.kt new file mode 100644 index 0000000000..d208185694 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ConsequenceHide.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Unique identifier of the object to hide. + * + * @param objectID Unique identifier of the object. + */ +@Serializable +public data class ConsequenceHide( + + /** Unique identifier of the object. */ + @SerialName(value = "objectID") val objectID: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ConsequenceParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ConsequenceParams.kt new file mode 100644 index 0000000000..90aec03991 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ConsequenceParams.kt @@ -0,0 +1,318 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * ConsequenceParams + * + * @param similarQuery Overrides the query parameter and performs a more generic search that can be used to find \"similar\" results. + * @param filters Filter the query with numeric, facet and/or tag filters. + * @param facetFilters + * @param optionalFilters + * @param numericFilters + * @param tagFilters + * @param sumOrFiltersScores Determines how to calculate the total score for filtering. + * @param facets Retrieve facets and their facet values. + * @param maxValuesPerFacet Maximum number of facet values to return for each facet during a regular search. + * @param facetingAfterDistinct Force faceting to be applied after de-duplication (via the Distinct setting). + * @param sortFacetValuesBy Controls how facet values are fetched. + * @param page Specify the page to retrieve. + * @param offset Specify the offset of the first hit to return. + * @param length Set the number of hits to retrieve (used only with offset). + * @param aroundLatLng Search for entries around a central geolocation, enabling a geo search within a circular area. + * @param aroundLatLngViaIP Search for entries around a given location automatically computed from the requester's IP address. + * @param aroundRadius + * @param aroundPrecision Precision of geo search (in meters), to add grouping by geo location to the ranking formula. + * @param minimumAroundRadius Minimum radius (in meters) used for a geo search when aroundRadius is not set. + * @param insideBoundingBox Search inside a rectangular area (in geo coordinates). + * @param insidePolygon Search inside a polygon (in geo coordinates). + * @param naturalLanguages This parameter changes the default values of certain parameters and settings that work best for a natural language query, such as ignorePlurals, removeStopWords, removeWordsIfNoResults, analyticsTags and ruleContexts. These parameters and settings work well together when the query is formatted in natural language instead of keywords, for example when your user performs a voice search. + * @param ruleContexts Enables contextual rules. + * @param personalizationImpact Define the impact of the Personalization feature. + * @param userToken Associates a certain user token with the current search. + * @param getRankingInfo Retrieve detailed ranking information. + * @param clickAnalytics Enable the Click Analytics feature. + * @param analytics Whether the current query will be taken into account in the Analytics. + * @param analyticsTags List of tags to apply to the query for analytics purposes. + * @param percentileComputation Whether to include or exclude a query from the processing-time percentile computation. + * @param enableABTest Whether this search should participate in running AB tests. + * @param enableReRanking Whether this search should use AI Re-Ranking. + * @param reRankingApplyFilter + * @param attributesForFaceting The complete list of attributes that will be used for faceting. + * @param attributesToRetrieve This parameter controls which attributes to retrieve and which not to retrieve. + * @param restrictSearchableAttributes Restricts a given query to look in only a subset of your searchable attributes. + * @param ranking Controls how Algolia should sort your results. + * @param customRanking Specifies the custom ranking criterion. + * @param relevancyStrictness Controls the relevancy threshold below which less relevant results aren't included in the results. + * @param attributesToHighlight List of attributes to highlight. + * @param attributesToSnippet List of attributes to snippet, with an optional maximum number of words to snippet. + * @param highlightPreTag The HTML string to insert before the highlighted parts in all highlight and snippet results. + * @param highlightPostTag The HTML string to insert after the highlighted parts in all highlight and snippet results. + * @param snippetEllipsisText String used as an ellipsis indicator when a snippet is truncated. + * @param restrictHighlightAndSnippetArrays Restrict highlighting and snippeting to items that matched the query. + * @param hitsPerPage Set the number of hits per page. + * @param minWordSizefor1Typo Minimum number of characters a word in the query string must contain to accept matches with 1 typo. + * @param minWordSizefor2Typos Minimum number of characters a word in the query string must contain to accept matches with 2 typos. + * @param typoTolerance + * @param allowTyposOnNumericTokens Whether to allow typos on numbers (\"numeric tokens\") in the query string. + * @param disableTypoToleranceOnAttributes List of attributes on which you want to disable typo tolerance. + * @param ignorePlurals + * @param removeStopWords + * @param keepDiacriticsOnCharacters List of characters that the engine shouldn't automatically normalize. + * @param queryLanguages Sets the languages to be used by language-specific settings and functionalities such as ignorePlurals, removeStopWords, and CJK word-detection. + * @param decompoundQuery Splits compound words into their composing atoms in the query. + * @param enableRules Whether Rules should be globally enabled. + * @param enablePersonalization Enable the Personalization feature. + * @param queryType + * @param removeWordsIfNoResults + * @param mode + * @param semanticSearch + * @param advancedSyntax Enables the advanced query syntax. + * @param optionalWords A list of words that should be considered as optional when found in the query. + * @param disableExactOnAttributes List of attributes on which you want to disable the exact ranking criterion. + * @param exactOnSingleWordQuery + * @param alternativesAsExact List of alternatives that should be considered an exact match by the exact ranking criterion. + * @param advancedSyntaxFeatures Allows you to specify which advanced syntax features are active when ‘advancedSyntax' is enabled. + * @param explain Enriches the API’s response with meta-information as to how the query was processed. + * @param distinct + * @param attributeForDistinct Name of the de-duplication attribute to be used with the distinct feature. + * @param synonyms Whether to take into account an index's synonyms for a particular search. + * @param replaceSynonymsInHighlight Whether to highlight and snippet the original word that matches the synonym or the synonym itself. + * @param minProximity Precision of the proximity ranking criterion. + * @param responseFields Choose which fields to return in the API response. This parameters applies to search and browse queries. + * @param maxFacetHits Maximum number of facet hits to return during a search for facet values. For performance reasons, the maximum allowed number of returned values is 100. + * @param attributeCriteriaComputedByMinProximity When attribute is ranked above proximity in your ranking formula, proximity is used to select which searchable attribute is matched in the attribute ranking stage. + * @param renderingContent + * @param query + * @param automaticFacetFilters + * @param automaticOptionalFacetFilters + */ +@Serializable +public data class ConsequenceParams( + + /** Overrides the query parameter and performs a more generic search that can be used to find \"similar\" results. */ + @SerialName(value = "similarQuery") val similarQuery: String? = null, + + /** Filter the query with numeric, facet and/or tag filters. */ + @SerialName(value = "filters") val filters: String? = null, + + @SerialName(value = "facetFilters") val facetFilters: FacetFilters? = null, + + @SerialName(value = "optionalFilters") val optionalFilters: OptionalFilters? = null, + + @SerialName(value = "numericFilters") val numericFilters: NumericFilters? = null, + + @SerialName(value = "tagFilters") val tagFilters: TagFilters? = null, + + /** Determines how to calculate the total score for filtering. */ + @SerialName(value = "sumOrFiltersScores") val sumOrFiltersScores: Boolean? = null, + + /** Retrieve facets and their facet values. */ + @SerialName(value = "facets") val facets: List? = null, + + /** Maximum number of facet values to return for each facet during a regular search. */ + @SerialName(value = "maxValuesPerFacet") val maxValuesPerFacet: Int? = null, + + /** Force faceting to be applied after de-duplication (via the Distinct setting). */ + @SerialName(value = "facetingAfterDistinct") val facetingAfterDistinct: Boolean? = null, + + /** Controls how facet values are fetched. */ + @SerialName(value = "sortFacetValuesBy") val sortFacetValuesBy: String? = null, + + /** Specify the page to retrieve. */ + @SerialName(value = "page") val page: Int? = null, + + /** Specify the offset of the first hit to return. */ + @SerialName(value = "offset") val offset: Int? = null, + + /** Set the number of hits to retrieve (used only with offset). */ + @SerialName(value = "length") val length: Int? = null, + + /** Search for entries around a central geolocation, enabling a geo search within a circular area. */ + @SerialName(value = "aroundLatLng") val aroundLatLng: String? = null, + + /** Search for entries around a given location automatically computed from the requester's IP address. */ + @SerialName(value = "aroundLatLngViaIP") val aroundLatLngViaIP: Boolean? = null, + + @SerialName(value = "aroundRadius") val aroundRadius: AroundRadius? = null, + + /** Precision of geo search (in meters), to add grouping by geo location to the ranking formula. */ + @SerialName(value = "aroundPrecision") val aroundPrecision: Int? = null, + + /** Minimum radius (in meters) used for a geo search when aroundRadius is not set. */ + @SerialName(value = "minimumAroundRadius") val minimumAroundRadius: Int? = null, + + /** Search inside a rectangular area (in geo coordinates). */ + @SerialName(value = "insideBoundingBox") val insideBoundingBox: List? = null, + + /** Search inside a polygon (in geo coordinates). */ + @SerialName(value = "insidePolygon") val insidePolygon: List? = null, + + /** This parameter changes the default values of certain parameters and settings that work best for a natural language query, such as ignorePlurals, removeStopWords, removeWordsIfNoResults, analyticsTags and ruleContexts. These parameters and settings work well together when the query is formatted in natural language instead of keywords, for example when your user performs a voice search. */ + @SerialName(value = "naturalLanguages") val naturalLanguages: List? = null, + + /** Enables contextual rules. */ + @SerialName(value = "ruleContexts") val ruleContexts: List? = null, + + /** Define the impact of the Personalization feature. */ + @SerialName(value = "personalizationImpact") val personalizationImpact: Int? = null, + + /** Associates a certain user token with the current search. */ + @SerialName(value = "userToken") val userToken: String? = null, + + /** Retrieve detailed ranking information. */ + @SerialName(value = "getRankingInfo") val getRankingInfo: Boolean? = null, + + /** Enable the Click Analytics feature. */ + @SerialName(value = "clickAnalytics") val clickAnalytics: Boolean? = null, + + /** Whether the current query will be taken into account in the Analytics. */ + @SerialName(value = "analytics") val analytics: Boolean? = null, + + /** List of tags to apply to the query for analytics purposes. */ + @SerialName(value = "analyticsTags") val analyticsTags: List? = null, + + /** Whether to include or exclude a query from the processing-time percentile computation. */ + @SerialName(value = "percentileComputation") val percentileComputation: Boolean? = null, + + /** Whether this search should participate in running AB tests. */ + @SerialName(value = "enableABTest") val enableABTest: Boolean? = null, + + /** Whether this search should use AI Re-Ranking. */ + @SerialName(value = "enableReRanking") val enableReRanking: Boolean? = null, + + @SerialName(value = "reRankingApplyFilter") val reRankingApplyFilter: ReRankingApplyFilter? = null, + + /** The complete list of attributes that will be used for faceting. */ + @SerialName(value = "attributesForFaceting") val attributesForFaceting: List? = null, + + /** This parameter controls which attributes to retrieve and which not to retrieve. */ + @SerialName(value = "attributesToRetrieve") val attributesToRetrieve: List? = null, + + /** Restricts a given query to look in only a subset of your searchable attributes. */ + @SerialName(value = "restrictSearchableAttributes") val restrictSearchableAttributes: List? = null, + + /** Controls how Algolia should sort your results. */ + @SerialName(value = "ranking") val ranking: List? = null, + + /** Specifies the custom ranking criterion. */ + @SerialName(value = "customRanking") val customRanking: List? = null, + + /** Controls the relevancy threshold below which less relevant results aren't included in the results. */ + @SerialName(value = "relevancyStrictness") val relevancyStrictness: Int? = null, + + /** List of attributes to highlight. */ + @SerialName(value = "attributesToHighlight") val attributesToHighlight: List? = null, + + /** List of attributes to snippet, with an optional maximum number of words to snippet. */ + @SerialName(value = "attributesToSnippet") val attributesToSnippet: List? = null, + + /** The HTML string to insert before the highlighted parts in all highlight and snippet results. */ + @SerialName(value = "highlightPreTag") val highlightPreTag: String? = null, + + /** The HTML string to insert after the highlighted parts in all highlight and snippet results. */ + @SerialName(value = "highlightPostTag") val highlightPostTag: String? = null, + + /** String used as an ellipsis indicator when a snippet is truncated. */ + @SerialName(value = "snippetEllipsisText") val snippetEllipsisText: String? = null, + + /** Restrict highlighting and snippeting to items that matched the query. */ + @SerialName(value = "restrictHighlightAndSnippetArrays") val restrictHighlightAndSnippetArrays: Boolean? = null, + + /** Set the number of hits per page. */ + @SerialName(value = "hitsPerPage") val hitsPerPage: Int? = null, + + /** Minimum number of characters a word in the query string must contain to accept matches with 1 typo. */ + @SerialName(value = "minWordSizefor1Typo") val minWordSizefor1Typo: Int? = null, + + /** Minimum number of characters a word in the query string must contain to accept matches with 2 typos. */ + @SerialName(value = "minWordSizefor2Typos") val minWordSizefor2Typos: Int? = null, + + @SerialName(value = "typoTolerance") val typoTolerance: TypoTolerance? = null, + + /** Whether to allow typos on numbers (\"numeric tokens\") in the query string. */ + @SerialName(value = "allowTyposOnNumericTokens") val allowTyposOnNumericTokens: Boolean? = null, + + /** List of attributes on which you want to disable typo tolerance. */ + @SerialName(value = "disableTypoToleranceOnAttributes") val disableTypoToleranceOnAttributes: List? = null, + + @SerialName(value = "ignorePlurals") val ignorePlurals: IgnorePlurals? = null, + + @SerialName(value = "removeStopWords") val removeStopWords: RemoveStopWords? = null, + + /** List of characters that the engine shouldn't automatically normalize. */ + @SerialName(value = "keepDiacriticsOnCharacters") val keepDiacriticsOnCharacters: String? = null, + + /** Sets the languages to be used by language-specific settings and functionalities such as ignorePlurals, removeStopWords, and CJK word-detection. */ + @SerialName(value = "queryLanguages") val queryLanguages: List? = null, + + /** Splits compound words into their composing atoms in the query. */ + @SerialName(value = "decompoundQuery") val decompoundQuery: Boolean? = null, + + /** Whether Rules should be globally enabled. */ + @SerialName(value = "enableRules") val enableRules: Boolean? = null, + + /** Enable the Personalization feature. */ + @SerialName(value = "enablePersonalization") val enablePersonalization: Boolean? = null, + + @SerialName(value = "queryType") val queryType: QueryType? = null, + + @SerialName(value = "removeWordsIfNoResults") val removeWordsIfNoResults: RemoveWordsIfNoResults? = null, + + @SerialName(value = "mode") val mode: Mode? = null, + + @SerialName(value = "semanticSearch") val semanticSearch: IndexSettingsAsSearchParamsSemanticSearch? = null, + + /** Enables the advanced query syntax. */ + @SerialName(value = "advancedSyntax") val advancedSyntax: Boolean? = null, + + /** A list of words that should be considered as optional when found in the query. */ + @SerialName(value = "optionalWords") val optionalWords: List? = null, + + /** List of attributes on which you want to disable the exact ranking criterion. */ + @SerialName(value = "disableExactOnAttributes") val disableExactOnAttributes: List? = null, + + @SerialName(value = "exactOnSingleWordQuery") val exactOnSingleWordQuery: ExactOnSingleWordQuery? = null, + + /** List of alternatives that should be considered an exact match by the exact ranking criterion. */ + @SerialName(value = "alternativesAsExact") val alternativesAsExact: List? = null, + + /** Allows you to specify which advanced syntax features are active when ‘advancedSyntax' is enabled. */ + @SerialName(value = "advancedSyntaxFeatures") val advancedSyntaxFeatures: List? = null, + + /** Enriches the API’s response with meta-information as to how the query was processed. */ + @SerialName(value = "explain") val explain: List? = null, + + @SerialName(value = "distinct") val distinct: Distinct? = null, + + /** Name of the de-duplication attribute to be used with the distinct feature. */ + @SerialName(value = "attributeForDistinct") val attributeForDistinct: String? = null, + + /** Whether to take into account an index's synonyms for a particular search. */ + @SerialName(value = "synonyms") val synonyms: Boolean? = null, + + /** Whether to highlight and snippet the original word that matches the synonym or the synonym itself. */ + @SerialName(value = "replaceSynonymsInHighlight") val replaceSynonymsInHighlight: Boolean? = null, + + /** Precision of the proximity ranking criterion. */ + @SerialName(value = "minProximity") val minProximity: Int? = null, + + /** Choose which fields to return in the API response. This parameters applies to search and browse queries. */ + @SerialName(value = "responseFields") val responseFields: List? = null, + + /** Maximum number of facet hits to return during a search for facet values. For performance reasons, the maximum allowed number of returned values is 100. */ + @SerialName(value = "maxFacetHits") val maxFacetHits: Int? = null, + + /** When attribute is ranked above proximity in your ranking formula, proximity is used to select which searchable attribute is matched in the attribute ranking stage. */ + @SerialName(value = "attributeCriteriaComputedByMinProximity") val attributeCriteriaComputedByMinProximity: Boolean? = null, + + @SerialName(value = "renderingContent") val renderingContent: RenderingContent? = null, + + @SerialName(value = "query") val query: ConsequenceQuery? = null, + + @SerialName(value = "automaticFacetFilters") val automaticFacetFilters: AutomaticFacetFilters? = null, + + @SerialName(value = "automaticOptionalFacetFilters") val automaticOptionalFacetFilters: AutomaticFacetFilters? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ConsequenceQuery.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ConsequenceQuery.kt new file mode 100644 index 0000000000..fbbb210eed --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ConsequenceQuery.kt @@ -0,0 +1,85 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * When providing a string, it replaces the entire query string. When providing an object, it describes incremental edits to be made to the query string (but you can't do both). + */ +@Serializable(ConsequenceQuerySerializer::class) +public sealed interface ConsequenceQuery { + + public data class StringWrapper(val value: String) : ConsequenceQuery + + public companion object { + + /** + * ConsequenceQueryObject + * + * @param remove Words to remove. + * @param edits Edits to apply. + */ + public fun ConsequenceQueryObject( + remove: List? = null, + edits: List? = null, + ): ConsequenceQueryObject = com.algolia.client.model.search.ConsequenceQueryObject( + remove = remove, + edits = edits, + ) + + /** + * ConsequenceQuery as String + * + */ + public fun String( + value: String, + ): StringWrapper = StringWrapper( + value = value, + ) + } +} + +internal class ConsequenceQuerySerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("ConsequenceQuery") + + override fun serialize(encoder: Encoder, value: ConsequenceQuery) { + when (value) { + is ConsequenceQueryObject -> ConsequenceQueryObject.serializer().serialize(encoder, value) + is ConsequenceQuery.StringWrapper -> String.serializer().serialize(encoder, value.value) + } + } + + override fun deserialize(decoder: Decoder): ConsequenceQuery { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize ConsequenceQueryObject + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize ConsequenceQueryObject (error: ${e.message})") + } + } + + // deserialize String + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize String (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ConsequenceQueryObject.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ConsequenceQueryObject.kt new file mode 100644 index 0000000000..457cdfb0ed --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ConsequenceQueryObject.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * ConsequenceQueryObject + * + * @param remove Words to remove. + * @param edits Edits to apply. + */ +@Serializable +public data class ConsequenceQueryObject( + + /** Words to remove. */ + @SerialName(value = "remove") val remove: List? = null, + + /** Edits to apply. */ + @SerialName(value = "edits") val edits: List? = null, +) : ConsequenceQuery diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/CreatedAtResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/CreatedAtResponse.kt new file mode 100644 index 0000000000..0c5435d4f5 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/CreatedAtResponse.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The response with a createdAt timestamp. + * + * @param createdAt Date of creation (ISO-8601 format). + */ +@Serializable +public data class CreatedAtResponse( + + /** Date of creation (ISO-8601 format). */ + @SerialName(value = "createdAt") val createdAt: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Cursor.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Cursor.kt new file mode 100644 index 0000000000..ad3400ff30 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Cursor.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Cursor + * + * @param cursor Cursor indicating the location to resume browsing from. Must match the value returned by the previous call. + */ +@Serializable +public data class Cursor( + + /** Cursor indicating the location to resume browsing from. Must match the value returned by the previous call. */ + @SerialName(value = "cursor") val cursor: String? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DeleteApiKeyResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DeleteApiKeyResponse.kt new file mode 100644 index 0000000000..121f533a7b --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DeleteApiKeyResponse.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * DeleteApiKeyResponse + * + * @param deletedAt Date of deletion (ISO-8601 format). + */ +@Serializable +public data class DeleteApiKeyResponse( + + /** Date of deletion (ISO-8601 format). */ + @SerialName(value = "deletedAt") val deletedAt: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DeleteByParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DeleteByParams.kt new file mode 100644 index 0000000000..449685659a --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DeleteByParams.kt @@ -0,0 +1,41 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * DeleteByParams + * + * @param facetFilters + * @param filters Filter the query with numeric, facet and/or tag filters. + * @param numericFilters + * @param tagFilters + * @param aroundLatLng Search for entries around a central geolocation, enabling a geo search within a circular area. + * @param aroundRadius + * @param insideBoundingBox Search inside a rectangular area (in geo coordinates). + * @param insidePolygon Search inside a polygon (in geo coordinates). + */ +@Serializable +public data class DeleteByParams( + + @SerialName(value = "facetFilters") val facetFilters: FacetFilters? = null, + + /** Filter the query with numeric, facet and/or tag filters. */ + @SerialName(value = "filters") val filters: String? = null, + + @SerialName(value = "numericFilters") val numericFilters: NumericFilters? = null, + + @SerialName(value = "tagFilters") val tagFilters: TagFilters? = null, + + /** Search for entries around a central geolocation, enabling a geo search within a circular area. */ + @SerialName(value = "aroundLatLng") val aroundLatLng: String? = null, + + @SerialName(value = "aroundRadius") val aroundRadius: AroundRadius? = null, + + /** Search inside a rectangular area (in geo coordinates). */ + @SerialName(value = "insideBoundingBox") val insideBoundingBox: List? = null, + + /** Search inside a polygon (in geo coordinates). */ + @SerialName(value = "insidePolygon") val insidePolygon: List? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DeleteSourceResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DeleteSourceResponse.kt new file mode 100644 index 0000000000..46673f8931 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DeleteSourceResponse.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * DeleteSourceResponse + * + * @param deletedAt Date of deletion (ISO-8601 format). + */ +@Serializable +public data class DeleteSourceResponse( + + /** Date of deletion (ISO-8601 format). */ + @SerialName(value = "deletedAt") val deletedAt: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DeletedAtResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DeletedAtResponse.kt new file mode 100644 index 0000000000..1f5268b10e --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DeletedAtResponse.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The response with a taskID and a deletedAt timestamp. + * + * @param taskID taskID of the task to wait for. + * @param deletedAt Date of deletion (ISO-8601 format). + */ +@Serializable +public data class DeletedAtResponse( + + /** taskID of the task to wait for. */ + @SerialName(value = "taskID") val taskID: Long, + + /** Date of deletion (ISO-8601 format). */ + @SerialName(value = "deletedAt") val deletedAt: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DictionaryAction.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DictionaryAction.kt new file mode 100644 index 0000000000..7ddcb8f865 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DictionaryAction.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* + +/** + * Actions to perform. + */ +@Serializable +public enum class DictionaryAction(public val value: kotlin.String) { + + @SerialName(value = "addEntry") + AddEntry("addEntry"), + + @SerialName(value = "deleteEntry") + DeleteEntry("deleteEntry"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DictionaryEntry.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DictionaryEntry.kt new file mode 100644 index 0000000000..bbef24828c --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DictionaryEntry.kt @@ -0,0 +1,81 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * A dictionary entry. + * + * @param objectID Unique identifier of the object. + * @param language Language ISO code supported by the dictionary (e.g., \"en\" for English). + * @param word The word of the dictionary entry. + * @param words The words of the dictionary entry. + * @param decomposition A decomposition of the word of the dictionary entry. + * @param state + */ +@Serializable(DictionaryEntrySerializer::class) +public data class DictionaryEntry( + + /** Unique identifier of the object. */ + val objectID: String, + + /** Language ISO code supported by the dictionary (e.g., \"en\" for English). */ + val language: String, + + /** The word of the dictionary entry. */ + val word: String? = null, + + /** The words of the dictionary entry. */ + val words: List? = null, + + /** A decomposition of the word of the dictionary entry. */ + val decomposition: List? = null, + + val state: DictionaryEntryState? = null, + + val additionalProperties: Map? = null, +) + +internal object DictionaryEntrySerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("DictionaryEntry") { + element("objectID") + element("language") + element("word") + element>("words") + element>("decomposition") + element("state") + } + + override fun deserialize(decoder: Decoder): DictionaryEntry { + val input = decoder.asJsonDecoder() + val tree = input.decodeJsonObject() + return DictionaryEntry( + objectID = tree.getValue("objectID").let { input.json.decodeFromJsonElement(it) }, + language = tree.getValue("language").let { input.json.decodeFromJsonElement(it) }, + word = tree["word"]?.let { input.json.decodeFromJsonElement(it) }, + words = tree["words"]?.let { input.json.decodeFromJsonElement(it) }, + decomposition = tree["decomposition"]?.let { input.json.decodeFromJsonElement(it) }, + state = tree["state"]?.let { input.json.decodeFromJsonElement(it) }, + additionalProperties = tree.filterKeys { it !in descriptor.elementNames }, + ) + } + + override fun serialize(encoder: Encoder, value: DictionaryEntry) { + val output = encoder.asJsonEncoder() + val json = buildJsonObject { + put("objectID", output.json.encodeToJsonElement(value.objectID)) + put("language", output.json.encodeToJsonElement(value.language)) + value.word?.let { put("word", output.json.encodeToJsonElement(it)) } + value.words?.let { put("words", output.json.encodeToJsonElement(it)) } + value.decomposition?.let { put("decomposition", output.json.encodeToJsonElement(it)) } + value.state?.let { put("state", output.json.encodeToJsonElement(it)) } + value.additionalProperties?.onEach { (key, element) -> put(key, element) } + } + (encoder as JsonEncoder).encodeJsonElement(json) + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DictionaryEntryState.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DictionaryEntryState.kt new file mode 100644 index 0000000000..2190b25cbc --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DictionaryEntryState.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* + +/** + * The state of the dictionary entry. + */ +@Serializable +public enum class DictionaryEntryState(public val value: kotlin.String) { + + @SerialName(value = "enabled") + Enabled("enabled"), + + @SerialName(value = "disabled") + Disabled("disabled"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DictionaryLanguage.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DictionaryLanguage.kt new file mode 100644 index 0000000000..13ed6af582 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DictionaryLanguage.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Custom entries for a dictionary. + * + * @param nbCustomEntires When nbCustomEntries is set to 0, the user didn't customize the dictionary. The dictionary is still supported with standard, Algolia-provided entries. + */ +@Serializable +public data class DictionaryLanguage( + + /** When nbCustomEntries is set to 0, the user didn't customize the dictionary. The dictionary is still supported with standard, Algolia-provided entries. */ + @SerialName(value = "nbCustomEntires") val nbCustomEntires: Int? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DictionarySettingsParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DictionarySettingsParams.kt new file mode 100644 index 0000000000..7fe47b31cf --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DictionarySettingsParams.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Disable the builtin Algolia entries for a type of dictionary per language. + * + * @param disableStandardEntries + */ +@Serializable +public data class DictionarySettingsParams( + + @SerialName(value = "disableStandardEntries") val disableStandardEntries: StandardEntries, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DictionaryType.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DictionaryType.kt new file mode 100644 index 0000000000..90fca3511a --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/DictionaryType.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* + +@Serializable +public enum class DictionaryType(public val value: kotlin.String) { + + @SerialName(value = "plurals") + Plurals("plurals"), + + @SerialName(value = "stopwords") + Stopwords("stopwords"), + + @SerialName(value = "compounds") + Compounds("compounds"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Distinct.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Distinct.kt new file mode 100644 index 0000000000..ea5bfbfdb4 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Distinct.kt @@ -0,0 +1,83 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Enables de-duplication or grouping of results. + */ +@Serializable(DistinctSerializer::class) +public sealed interface Distinct { + + public data class BooleanWrapper(val value: Boolean) : Distinct + + public data class IntWrapper(val value: Int) : Distinct + + public companion object { + + /** + * Distinct as Boolean + * + */ + public fun Boolean( + value: Boolean, + ): BooleanWrapper = BooleanWrapper( + value = value, + ) + + /** + * Distinct as Int + * + */ + public fun Number( + value: Int, + ): IntWrapper = IntWrapper( + value = value, + ) + } +} + +internal class DistinctSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("Distinct") + + override fun serialize(encoder: Encoder, value: Distinct) { + when (value) { + is Distinct.BooleanWrapper -> Boolean.serializer().serialize(encoder, value.value) + is Distinct.IntWrapper -> Int.serializer().serialize(encoder, value.value) + } + } + + override fun deserialize(decoder: Decoder): Distinct { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize Boolean + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize Boolean (error: ${e.message})") + } + } + + // deserialize Int + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize Int (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Edit.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Edit.kt new file mode 100644 index 0000000000..f7626dfe03 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Edit.kt @@ -0,0 +1,24 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Edit + * + * @param type + * @param delete Text or patterns to remove from the query string. + * @param insert Text that should be inserted in place of the removed text inside the query string. + */ +@Serializable +public data class Edit( + + @SerialName(value = "type") val type: EditType? = null, + + /** Text or patterns to remove from the query string. */ + @SerialName(value = "delete") val delete: String? = null, + + /** Text that should be inserted in place of the removed text inside the query string. */ + @SerialName(value = "insert") val insert: String? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/EditType.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/EditType.kt new file mode 100644 index 0000000000..f52486c7d4 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/EditType.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* + +/** + * Type of edit. + */ +@Serializable +public enum class EditType(public val value: kotlin.String) { + + @SerialName(value = "remove") + Remove("remove"), + + @SerialName(value = "replace") + Replace("replace"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ErrorBase.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ErrorBase.kt new file mode 100644 index 0000000000..aba4126cf8 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ErrorBase.kt @@ -0,0 +1,46 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Error. + * + * @param message + */ +@Serializable(ErrorBaseSerializer::class) +public data class ErrorBase( + + val message: String? = null, + + val additionalProperties: Map? = null, +) + +internal object ErrorBaseSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("ErrorBase") { + element("message") + } + + override fun deserialize(decoder: Decoder): ErrorBase { + val input = decoder.asJsonDecoder() + val tree = input.decodeJsonObject() + return ErrorBase( + message = tree["message"]?.let { input.json.decodeFromJsonElement(it) }, + additionalProperties = tree.filterKeys { it !in descriptor.elementNames }, + ) + } + + override fun serialize(encoder: Encoder, value: ErrorBase) { + val output = encoder.asJsonEncoder() + val json = buildJsonObject { + value.message?.let { put("message", output.json.encodeToJsonElement(it)) } + value.additionalProperties?.onEach { (key, element) -> put(key, element) } + } + (encoder as JsonEncoder).encodeJsonElement(json) + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ExactOnSingleWordQuery.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ExactOnSingleWordQuery.kt new file mode 100644 index 0000000000..1649a4a612 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ExactOnSingleWordQuery.kt @@ -0,0 +1,22 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* + +/** + * Controls how the exact ranking criterion is computed when the query contains only one word. + */ +@Serializable +public enum class ExactOnSingleWordQuery(public val value: kotlin.String) { + + @SerialName(value = "attribute") + Attribute("attribute"), + + @SerialName(value = "none") + None("none"), + + @SerialName(value = "word") + Word("word"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/FacetFilters.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/FacetFilters.kt new file mode 100644 index 0000000000..91e2ec7d46 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/FacetFilters.kt @@ -0,0 +1,83 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Filter hits by facet value. + */ +@Serializable(FacetFiltersSerializer::class) +public sealed interface FacetFilters { + + public data class ListOfMixedSearchFiltersWrapper(val value: List) : FacetFilters + + public data class StringWrapper(val value: String) : FacetFilters + + public companion object { + + /** + * FacetFilters as List + * + */ + public fun ListOfMixedSearchFilters( + value: List, + ): ListOfMixedSearchFiltersWrapper = ListOfMixedSearchFiltersWrapper( + value = value, + ) + + /** + * FacetFilters as String + * + */ + public fun String( + value: String, + ): StringWrapper = StringWrapper( + value = value, + ) + } +} + +internal class FacetFiltersSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("FacetFilters") + + override fun serialize(encoder: Encoder, value: FacetFilters) { + when (value) { + is FacetFilters.ListOfMixedSearchFiltersWrapper -> ListSerializer(MixedSearchFilters.serializer()).serialize(encoder, value.value) + is FacetFilters.StringWrapper -> String.serializer().serialize(encoder, value.value) + } + } + + override fun deserialize(decoder: Decoder): FacetFilters { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize List + if (tree is JsonArray) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize List (error: ${e.message})") + } + } + + // deserialize String + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize String (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/FacetHits.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/FacetHits.kt new file mode 100644 index 0000000000..ffda8be5b0 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/FacetHits.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * FacetHits + * + * @param `value` Raw value of the facet. + * @param highlighted Markup text with occurrences highlighted. + * @param count How many objects contain this facet value. This takes into account the extra search parameters specified in the query. Like for a regular search query, the counts may not be exhaustive. + */ +@Serializable +public data class FacetHits( + + /** Raw value of the facet. */ + @SerialName(value = "value") val `value`: String, + + /** Markup text with occurrences highlighted. */ + @SerialName(value = "highlighted") val highlighted: String, + + /** How many objects contain this facet value. This takes into account the extra search parameters specified in the query. Like for a regular search query, the counts may not be exhaustive. */ + @SerialName(value = "count") val count: Int, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/FacetOrdering.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/FacetOrdering.kt new file mode 100644 index 0000000000..4610dcc15f --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/FacetOrdering.kt @@ -0,0 +1,20 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Defining how facets should be ordered. + * + * @param facets + * @param values The ordering of facet values, within an individual list. + */ +@Serializable +public data class FacetOrdering( + + @SerialName(value = "facets") val facets: Facets? = null, + + /** The ordering of facet values, within an individual list. */ + @SerialName(value = "values") val values: Map? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Facets.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Facets.kt new file mode 100644 index 0000000000..a234361e49 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Facets.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The ordering of facets (widgets). + * + * @param order Pinned order of facet lists. + */ +@Serializable +public data class Facets( + + /** Pinned order of facet lists. */ + @SerialName(value = "order") val order: List? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/FacetsStats.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/FacetsStats.kt new file mode 100644 index 0000000000..de782531a0 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/FacetsStats.kt @@ -0,0 +1,29 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * FacetsStats + * + * @param min The minimum value in the result set. + * @param max The maximum value in the result set. + * @param avg The average facet value in the result set. + * @param sum The sum of all values in the result set. + */ +@Serializable +public data class FacetsStats( + + /** The minimum value in the result set. */ + @SerialName(value = "min") val min: Int? = null, + + /** The maximum value in the result set. */ + @SerialName(value = "max") val max: Int? = null, + + /** The average facet value in the result set. */ + @SerialName(value = "avg") val avg: Int? = null, + + /** The sum of all values in the result set. */ + @SerialName(value = "sum") val sum: Int? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/FetchedIndex.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/FetchedIndex.kt new file mode 100644 index 0000000000..50fba277b8 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/FetchedIndex.kt @@ -0,0 +1,57 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * FetchedIndex + * + * @param name Index name. + * @param createdAt Index creation date. An empty string means that the index has no records. + * @param updatedAt Date of last update (ISO-8601 format). + * @param entries Number of records contained in the index. + * @param dataSize Number of bytes of the index in minified format. + * @param fileSize Number of bytes of the index binary file. + * @param lastBuildTimeS Last build time. + * @param numberOfPendingTasks Number of pending indexing operations. This value is deprecated and should not be used. + * @param pendingTask A boolean which says whether the index has pending tasks. This value is deprecated and should not be used. + * @param primary Only present if the index is a replica. Contains the name of the related primary index. + * @param replicas Only present if the index is a primary index with replicas. Contains the names of all linked replicas. + */ +@Serializable +public data class FetchedIndex( + + /** Index name. */ + @SerialName(value = "name") val name: String, + + /** Index creation date. An empty string means that the index has no records. */ + @SerialName(value = "createdAt") val createdAt: String, + + /** Date of last update (ISO-8601 format). */ + @SerialName(value = "updatedAt") val updatedAt: String, + + /** Number of records contained in the index. */ + @SerialName(value = "entries") val entries: Int, + + /** Number of bytes of the index in minified format. */ + @SerialName(value = "dataSize") val dataSize: Int, + + /** Number of bytes of the index binary file. */ + @SerialName(value = "fileSize") val fileSize: Int, + + /** Last build time. */ + @SerialName(value = "lastBuildTimeS") val lastBuildTimeS: Int, + + /** Number of pending indexing operations. This value is deprecated and should not be used. */ + @SerialName(value = "numberOfPendingTasks") val numberOfPendingTasks: Int, + + /** A boolean which says whether the index has pending tasks. This value is deprecated and should not be used. */ + @SerialName(value = "pendingTask") val pendingTask: Boolean, + + /** Only present if the index is a replica. Contains the name of the related primary index. */ + @SerialName(value = "primary") val primary: String? = null, + + /** Only present if the index is a primary index with replicas. Contains the names of all linked replicas. */ + @SerialName(value = "replicas") val replicas: List? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetApiKeyResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetApiKeyResponse.kt new file mode 100644 index 0000000000..5ae2444deb --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetApiKeyResponse.kt @@ -0,0 +1,53 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * GetApiKeyResponse + * + * @param createdAt Time of the event expressed in milliseconds since the Unix epoch. + * @param acl Set of permissions associated with the key. + * @param `value` The API key. + * @param description A comment used to identify a key more easily in the dashboard. It is not interpreted by the API. + * @param indexes Restrict this new API key to a list of indices or index patterns. If the list is empty, all indices are allowed. + * @param maxHitsPerQuery Maximum number of hits this API key can retrieve in one query. If zero, no limit is enforced. + * @param maxQueriesPerIPPerHour Maximum number of API calls per hour allowed from a given IP address or a user token. + * @param queryParameters URL-encoded query string. Force some query parameters to be applied for each query made with this API key. + * @param referers Restrict this new API key to specific referers. If empty or blank, defaults to all referers. + * @param validity Validity limit for this key in seconds. The key will automatically be removed after this period of time. + */ +@Serializable +public data class GetApiKeyResponse( + + /** Time of the event expressed in milliseconds since the Unix epoch. */ + @SerialName(value = "createdAt") val createdAt: Long, + + /** Set of permissions associated with the key. */ + @SerialName(value = "acl") val acl: List, + + /** The API key. */ + @SerialName(value = "value") val `value`: String? = null, + + /** A comment used to identify a key more easily in the dashboard. It is not interpreted by the API. */ + @SerialName(value = "description") val description: String? = null, + + /** Restrict this new API key to a list of indices or index patterns. If the list is empty, all indices are allowed. */ + @SerialName(value = "indexes") val indexes: List? = null, + + /** Maximum number of hits this API key can retrieve in one query. If zero, no limit is enforced. */ + @SerialName(value = "maxHitsPerQuery") val maxHitsPerQuery: Int? = null, + + /** Maximum number of API calls per hour allowed from a given IP address or a user token. */ + @SerialName(value = "maxQueriesPerIPPerHour") val maxQueriesPerIPPerHour: Int? = null, + + /** URL-encoded query string. Force some query parameters to be applied for each query made with this API key. */ + @SerialName(value = "queryParameters") val queryParameters: String? = null, + + /** Restrict this new API key to specific referers. If empty or blank, defaults to all referers. */ + @SerialName(value = "referers") val referers: List? = null, + + /** Validity limit for this key in seconds. The key will automatically be removed after this period of time. */ + @SerialName(value = "validity") val validity: Int? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetDictionarySettingsResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetDictionarySettingsResponse.kt new file mode 100644 index 0000000000..13777f8fd3 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetDictionarySettingsResponse.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * GetDictionarySettingsResponse + * + * @param disableStandardEntries + */ +@Serializable +public data class GetDictionarySettingsResponse( + + @SerialName(value = "disableStandardEntries") val disableStandardEntries: StandardEntries, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetLogsResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetLogsResponse.kt new file mode 100644 index 0000000000..06299eba46 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetLogsResponse.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * GetLogsResponse + * + * @param logs + */ +@Serializable +public data class GetLogsResponse( + + @SerialName(value = "logs") val logs: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetObjectsParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetObjectsParams.kt new file mode 100644 index 0000000000..1cd854a7f6 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetObjectsParams.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The `getObjects` parameters. + * + * @param requests + */ +@Serializable +public data class GetObjectsParams( + + @SerialName(value = "requests") val requests: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetObjectsRequest.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetObjectsRequest.kt new file mode 100644 index 0000000000..6e5a4c0301 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetObjectsRequest.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * getObjects operation on an index. + * + * @param objectID ID of the object within that index. + * @param indexName name of the index containing the object. + * @param attributesToRetrieve List of attributes to retrieve. By default, all retrievable attributes are returned. + */ +@Serializable +public data class GetObjectsRequest( + + /** ID of the object within that index. */ + @SerialName(value = "objectID") val objectID: String, + + /** name of the index containing the object. */ + @SerialName(value = "indexName") val indexName: String, + + /** List of attributes to retrieve. By default, all retrievable attributes are returned. */ + @SerialName(value = "attributesToRetrieve") val attributesToRetrieve: List? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetObjectsResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetObjectsResponse.kt new file mode 100644 index 0000000000..fab3094764 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetObjectsResponse.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * GetObjectsResponse + * + * @param results List of results fetched. + */ +@Serializable +public data class GetObjectsResponse( + + /** List of results fetched. */ + @SerialName(value = "results") val results: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetTaskResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetTaskResponse.kt new file mode 100644 index 0000000000..9e560e038a --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetTaskResponse.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * GetTaskResponse + * + * @param status + */ +@Serializable +public data class GetTaskResponse( + + @SerialName(value = "status") val status: TaskStatus, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetTopUserIdsResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetTopUserIdsResponse.kt new file mode 100644 index 0000000000..7d41c9de6b --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/GetTopUserIdsResponse.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Array of userIDs and clusters. + * + * @param topUsers Mapping of cluster names to top users. + */ +@Serializable +public data class GetTopUserIdsResponse( + + /** Mapping of cluster names to top users. */ + @SerialName(value = "topUsers") val topUsers: List>>, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/HasPendingMappingsResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/HasPendingMappingsResponse.kt new file mode 100644 index 0000000000..b356c6c5eb --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/HasPendingMappingsResponse.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * HasPendingMappingsResponse + * + * @param pending If there is any clusters with pending mapping state. + * @param clusters Describe cluster pending (migrating, creating, deleting) mapping state. + */ +@Serializable +public data class HasPendingMappingsResponse( + + /** If there is any clusters with pending mapping state. */ + @SerialName(value = "pending") val pending: Boolean, + + /** Describe cluster pending (migrating, creating, deleting) mapping state. */ + @SerialName(value = "clusters") val clusters: Map>? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/HighlightResult.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/HighlightResult.kt new file mode 100644 index 0000000000..e34add5081 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/HighlightResult.kt @@ -0,0 +1,91 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * HighlightResult + */ +@Serializable(HighlightResultSerializer::class) +public sealed interface HighlightResult { + + public data class ListOfHighlightResultOptionWrapper(val value: List) : HighlightResult + + public companion object { + + /** + * Show highlighted section and words matched on a query. + * + * @param `value` Markup text with occurrences highlighted. + * @param matchLevel + * @param matchedWords List of words from the query that matched the object. + * @param fullyHighlighted Whether the entire attribute value is highlighted. + */ + public fun HighlightResultOption( + `value`: String, + matchLevel: MatchLevel, + matchedWords: List, + fullyHighlighted: Boolean? = null, + ): HighlightResultOption = com.algolia.client.model.search.HighlightResultOption( + `value` = `value`, + matchLevel = matchLevel, + matchedWords = matchedWords, + fullyHighlighted = fullyHighlighted, + ) + + /** + * HighlightResult as List + * + */ + public fun ListOfHighlightResultOption( + value: List, + ): ListOfHighlightResultOptionWrapper = ListOfHighlightResultOptionWrapper( + value = value, + ) + } +} + +internal class HighlightResultSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("HighlightResult") + + override fun serialize(encoder: Encoder, value: HighlightResult) { + when (value) { + is HighlightResultOption -> HighlightResultOption.serializer().serialize(encoder, value) + is HighlightResult.ListOfHighlightResultOptionWrapper -> ListSerializer(HighlightResultOption.serializer()).serialize(encoder, value.value) + } + } + + override fun deserialize(decoder: Decoder): HighlightResult { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize HighlightResultOption + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize HighlightResultOption (error: ${e.message})") + } + } + + // deserialize List + if (tree is JsonArray) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize List (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/HighlightResultOption.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/HighlightResultOption.kt new file mode 100644 index 0000000000..b5723cb1c5 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/HighlightResultOption.kt @@ -0,0 +1,28 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Show highlighted section and words matched on a query. + * + * @param `value` Markup text with occurrences highlighted. + * @param matchLevel + * @param matchedWords List of words from the query that matched the object. + * @param fullyHighlighted Whether the entire attribute value is highlighted. + */ +@Serializable +public data class HighlightResultOption( + + /** Markup text with occurrences highlighted. */ + @SerialName(value = "value") val `value`: String, + + @SerialName(value = "matchLevel") val matchLevel: MatchLevel, + + /** List of words from the query that matched the object. */ + @SerialName(value = "matchedWords") val matchedWords: List, + + /** Whether the entire attribute value is highlighted. */ + @SerialName(value = "fullyHighlighted") val fullyHighlighted: Boolean? = null, +) : HighlightResult diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Hit.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Hit.kt new file mode 100644 index 0000000000..ce97cf7766 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Hit.kt @@ -0,0 +1,73 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * A single hit. + * + * @param objectID Unique identifier of the object. + * @param highlightResult Show highlighted section and words matched on a query. + * @param snippetResult Snippeted attributes show parts of the matched attributes. Only returned when attributesToSnippet is non-empty. + * @param rankingInfo + * @param distinctSeqID + */ +@Serializable(HitSerializer::class) +public data class Hit( + + /** Unique identifier of the object. */ + val objectID: String, + + /** Show highlighted section and words matched on a query. */ + val highlightResult: Map? = null, + + /** Snippeted attributes show parts of the matched attributes. Only returned when attributesToSnippet is non-empty. */ + val snippetResult: Map? = null, + + val rankingInfo: RankingInfo? = null, + + val distinctSeqID: Int? = null, + + val additionalProperties: Map? = null, +) + +internal object HitSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("Hit") { + element("objectID") + element>("_highlightResult") + element>("_snippetResult") + element("_rankingInfo") + element("_distinctSeqID") + } + + override fun deserialize(decoder: Decoder): Hit { + val input = decoder.asJsonDecoder() + val tree = input.decodeJsonObject() + return Hit( + objectID = tree.getValue("objectID").let { input.json.decodeFromJsonElement(it) }, + highlightResult = tree["_highlightResult"]?.let { input.json.decodeFromJsonElement(it) }, + snippetResult = tree["_snippetResult"]?.let { input.json.decodeFromJsonElement(it) }, + rankingInfo = tree["_rankingInfo"]?.let { input.json.decodeFromJsonElement(it) }, + distinctSeqID = tree["_distinctSeqID"]?.let { input.json.decodeFromJsonElement(it) }, + additionalProperties = tree.filterKeys { it !in descriptor.elementNames }, + ) + } + + override fun serialize(encoder: Encoder, value: Hit) { + val output = encoder.asJsonEncoder() + val json = buildJsonObject { + put("objectID", output.json.encodeToJsonElement(value.objectID)) + value.highlightResult?.let { put("_highlightResult", output.json.encodeToJsonElement(it)) } + value.snippetResult?.let { put("_snippetResult", output.json.encodeToJsonElement(it)) } + value.rankingInfo?.let { put("_rankingInfo", output.json.encodeToJsonElement(it)) } + value.distinctSeqID?.let { put("_distinctSeqID", output.json.encodeToJsonElement(it)) } + value.additionalProperties?.onEach { (key, element) -> put(key, element) } + } + (encoder as JsonEncoder).encodeJsonElement(json) + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/IgnorePlurals.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/IgnorePlurals.kt new file mode 100644 index 0000000000..97f9eec4c9 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/IgnorePlurals.kt @@ -0,0 +1,83 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Treats singular, plurals, and other forms of declensions as matching terms. ignorePlurals is used in conjunction with the queryLanguages setting. list: language ISO codes for which ignoring plurals should be enabled. This list will override any values that you may have set in queryLanguages. true: enables the ignore plurals functionality, where singulars and plurals are considered equivalent (foot = feet). The languages supported here are either every language (this is the default, see list of languages below), or those set by queryLanguages. false: disables ignore plurals, where singulars and plurals are not considered the same for matching purposes (foot will not find feet). + */ +@Serializable(IgnorePluralsSerializer::class) +public sealed interface IgnorePlurals { + + public data class BooleanWrapper(val value: Boolean) : IgnorePlurals + + public data class ListOfStringWrapper(val value: List) : IgnorePlurals + + public companion object { + + /** + * IgnorePlurals as Boolean + * + */ + public fun Boolean( + value: Boolean, + ): BooleanWrapper = BooleanWrapper( + value = value, + ) + + /** + * IgnorePlurals as List + * + */ + public fun ListOfString( + value: List, + ): ListOfStringWrapper = ListOfStringWrapper( + value = value, + ) + } +} + +internal class IgnorePluralsSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("IgnorePlurals") + + override fun serialize(encoder: Encoder, value: IgnorePlurals) { + when (value) { + is IgnorePlurals.BooleanWrapper -> Boolean.serializer().serialize(encoder, value.value) + is IgnorePlurals.ListOfStringWrapper -> ListSerializer(String.serializer()).serialize(encoder, value.value) + } + } + + override fun deserialize(decoder: Decoder): IgnorePlurals { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize Boolean + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize Boolean (error: ${e.message})") + } + } + + // deserialize List + if (tree is JsonArray) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize List (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/IndexSettings.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/IndexSettings.kt new file mode 100644 index 0000000000..6c717edcd0 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/IndexSettings.kt @@ -0,0 +1,243 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The Algolia index settings. + * + * @param replicas Creates replicas, exact copies of an index. + * @param paginationLimitedTo Set the maximum number of hits accessible via pagination. + * @param unretrievableAttributes List of attributes that can't be retrieved at query time. + * @param disableTypoToleranceOnWords A list of words for which you want to turn off typo tolerance. + * @param attributesToTransliterate Specify on which attributes in your index Algolia should apply Japanese transliteration to make words indexed in Katakana or Kanji searchable in Hiragana. + * @param camelCaseAttributes List of attributes on which to do a decomposition of camel case words. + * @param decompoundedAttributes Specify on which attributes in your index Algolia should apply word segmentation, also known as decompounding. + * @param indexLanguages Sets the languages at the index level for language-specific processing such as tokenization and normalization. + * @param disablePrefixOnAttributes List of attributes on which you want to disable prefix matching. + * @param allowCompressionOfIntegerArray Enables compression of large integer arrays. + * @param numericAttributesForFiltering List of numeric attributes that can be used as numerical filters. + * @param separatorsToIndex Control which separators are indexed. + * @param searchableAttributes The complete list of attributes used for searching. + * @param userData Lets you store custom data in your indices. + * @param customNormalization Overrides Algolia's default normalization. + * @param attributesForFaceting The complete list of attributes that will be used for faceting. + * @param attributesToRetrieve This parameter controls which attributes to retrieve and which not to retrieve. + * @param restrictSearchableAttributes Restricts a given query to look in only a subset of your searchable attributes. + * @param ranking Controls how Algolia should sort your results. + * @param customRanking Specifies the custom ranking criterion. + * @param relevancyStrictness Controls the relevancy threshold below which less relevant results aren't included in the results. + * @param attributesToHighlight List of attributes to highlight. + * @param attributesToSnippet List of attributes to snippet, with an optional maximum number of words to snippet. + * @param highlightPreTag The HTML string to insert before the highlighted parts in all highlight and snippet results. + * @param highlightPostTag The HTML string to insert after the highlighted parts in all highlight and snippet results. + * @param snippetEllipsisText String used as an ellipsis indicator when a snippet is truncated. + * @param restrictHighlightAndSnippetArrays Restrict highlighting and snippeting to items that matched the query. + * @param hitsPerPage Set the number of hits per page. + * @param minWordSizefor1Typo Minimum number of characters a word in the query string must contain to accept matches with 1 typo. + * @param minWordSizefor2Typos Minimum number of characters a word in the query string must contain to accept matches with 2 typos. + * @param typoTolerance + * @param allowTyposOnNumericTokens Whether to allow typos on numbers (\"numeric tokens\") in the query string. + * @param disableTypoToleranceOnAttributes List of attributes on which you want to disable typo tolerance. + * @param ignorePlurals + * @param removeStopWords + * @param keepDiacriticsOnCharacters List of characters that the engine shouldn't automatically normalize. + * @param queryLanguages Sets the languages to be used by language-specific settings and functionalities such as ignorePlurals, removeStopWords, and CJK word-detection. + * @param decompoundQuery Splits compound words into their composing atoms in the query. + * @param enableRules Whether Rules should be globally enabled. + * @param enablePersonalization Enable the Personalization feature. + * @param queryType + * @param removeWordsIfNoResults + * @param mode + * @param semanticSearch + * @param advancedSyntax Enables the advanced query syntax. + * @param optionalWords A list of words that should be considered as optional when found in the query. + * @param disableExactOnAttributes List of attributes on which you want to disable the exact ranking criterion. + * @param exactOnSingleWordQuery + * @param alternativesAsExact List of alternatives that should be considered an exact match by the exact ranking criterion. + * @param advancedSyntaxFeatures Allows you to specify which advanced syntax features are active when ‘advancedSyntax' is enabled. + * @param explain Enriches the API’s response with meta-information as to how the query was processed. + * @param distinct + * @param attributeForDistinct Name of the de-duplication attribute to be used with the distinct feature. + * @param synonyms Whether to take into account an index's synonyms for a particular search. + * @param replaceSynonymsInHighlight Whether to highlight and snippet the original word that matches the synonym or the synonym itself. + * @param minProximity Precision of the proximity ranking criterion. + * @param responseFields Choose which fields to return in the API response. This parameters applies to search and browse queries. + * @param maxFacetHits Maximum number of facet hits to return during a search for facet values. For performance reasons, the maximum allowed number of returned values is 100. + * @param attributeCriteriaComputedByMinProximity When attribute is ranked above proximity in your ranking formula, proximity is used to select which searchable attribute is matched in the attribute ranking stage. + * @param renderingContent + */ +@Serializable +public data class IndexSettings( + + /** Creates replicas, exact copies of an index. */ + @SerialName(value = "replicas") val replicas: List? = null, + + /** Set the maximum number of hits accessible via pagination. */ + @SerialName(value = "paginationLimitedTo") val paginationLimitedTo: Int? = null, + + /** List of attributes that can't be retrieved at query time. */ + @SerialName(value = "unretrievableAttributes") val unretrievableAttributes: List? = null, + + /** A list of words for which you want to turn off typo tolerance. */ + @SerialName(value = "disableTypoToleranceOnWords") val disableTypoToleranceOnWords: List? = null, + + /** Specify on which attributes in your index Algolia should apply Japanese transliteration to make words indexed in Katakana or Kanji searchable in Hiragana. */ + @SerialName(value = "attributesToTransliterate") val attributesToTransliterate: List? = null, + + /** List of attributes on which to do a decomposition of camel case words. */ + @SerialName(value = "camelCaseAttributes") val camelCaseAttributes: List? = null, + + /** Specify on which attributes in your index Algolia should apply word segmentation, also known as decompounding. */ + @SerialName(value = "decompoundedAttributes") val decompoundedAttributes: JsonObject? = null, + + /** Sets the languages at the index level for language-specific processing such as tokenization and normalization. */ + @SerialName(value = "indexLanguages") val indexLanguages: List? = null, + + /** List of attributes on which you want to disable prefix matching. */ + @SerialName(value = "disablePrefixOnAttributes") val disablePrefixOnAttributes: List? = null, + + /** Enables compression of large integer arrays. */ + @SerialName(value = "allowCompressionOfIntegerArray") val allowCompressionOfIntegerArray: Boolean? = null, + + /** List of numeric attributes that can be used as numerical filters. */ + @SerialName(value = "numericAttributesForFiltering") val numericAttributesForFiltering: List? = null, + + /** Control which separators are indexed. */ + @SerialName(value = "separatorsToIndex") val separatorsToIndex: String? = null, + + /** The complete list of attributes used for searching. */ + @SerialName(value = "searchableAttributes") val searchableAttributes: List? = null, + + /** Lets you store custom data in your indices. */ + @SerialName(value = "userData") val userData: JsonObject? = null, + + /** Overrides Algolia's default normalization. */ + @SerialName(value = "customNormalization") val customNormalization: Map>? = null, + + /** The complete list of attributes that will be used for faceting. */ + @SerialName(value = "attributesForFaceting") val attributesForFaceting: List? = null, + + /** This parameter controls which attributes to retrieve and which not to retrieve. */ + @SerialName(value = "attributesToRetrieve") val attributesToRetrieve: List? = null, + + /** Restricts a given query to look in only a subset of your searchable attributes. */ + @SerialName(value = "restrictSearchableAttributes") val restrictSearchableAttributes: List? = null, + + /** Controls how Algolia should sort your results. */ + @SerialName(value = "ranking") val ranking: List? = null, + + /** Specifies the custom ranking criterion. */ + @SerialName(value = "customRanking") val customRanking: List? = null, + + /** Controls the relevancy threshold below which less relevant results aren't included in the results. */ + @SerialName(value = "relevancyStrictness") val relevancyStrictness: Int? = null, + + /** List of attributes to highlight. */ + @SerialName(value = "attributesToHighlight") val attributesToHighlight: List? = null, + + /** List of attributes to snippet, with an optional maximum number of words to snippet. */ + @SerialName(value = "attributesToSnippet") val attributesToSnippet: List? = null, + + /** The HTML string to insert before the highlighted parts in all highlight and snippet results. */ + @SerialName(value = "highlightPreTag") val highlightPreTag: String? = null, + + /** The HTML string to insert after the highlighted parts in all highlight and snippet results. */ + @SerialName(value = "highlightPostTag") val highlightPostTag: String? = null, + + /** String used as an ellipsis indicator when a snippet is truncated. */ + @SerialName(value = "snippetEllipsisText") val snippetEllipsisText: String? = null, + + /** Restrict highlighting and snippeting to items that matched the query. */ + @SerialName(value = "restrictHighlightAndSnippetArrays") val restrictHighlightAndSnippetArrays: Boolean? = null, + + /** Set the number of hits per page. */ + @SerialName(value = "hitsPerPage") val hitsPerPage: Int? = null, + + /** Minimum number of characters a word in the query string must contain to accept matches with 1 typo. */ + @SerialName(value = "minWordSizefor1Typo") val minWordSizefor1Typo: Int? = null, + + /** Minimum number of characters a word in the query string must contain to accept matches with 2 typos. */ + @SerialName(value = "minWordSizefor2Typos") val minWordSizefor2Typos: Int? = null, + + @SerialName(value = "typoTolerance") val typoTolerance: TypoTolerance? = null, + + /** Whether to allow typos on numbers (\"numeric tokens\") in the query string. */ + @SerialName(value = "allowTyposOnNumericTokens") val allowTyposOnNumericTokens: Boolean? = null, + + /** List of attributes on which you want to disable typo tolerance. */ + @SerialName(value = "disableTypoToleranceOnAttributes") val disableTypoToleranceOnAttributes: List? = null, + + @SerialName(value = "ignorePlurals") val ignorePlurals: IgnorePlurals? = null, + + @SerialName(value = "removeStopWords") val removeStopWords: RemoveStopWords? = null, + + /** List of characters that the engine shouldn't automatically normalize. */ + @SerialName(value = "keepDiacriticsOnCharacters") val keepDiacriticsOnCharacters: String? = null, + + /** Sets the languages to be used by language-specific settings and functionalities such as ignorePlurals, removeStopWords, and CJK word-detection. */ + @SerialName(value = "queryLanguages") val queryLanguages: List? = null, + + /** Splits compound words into their composing atoms in the query. */ + @SerialName(value = "decompoundQuery") val decompoundQuery: Boolean? = null, + + /** Whether Rules should be globally enabled. */ + @SerialName(value = "enableRules") val enableRules: Boolean? = null, + + /** Enable the Personalization feature. */ + @SerialName(value = "enablePersonalization") val enablePersonalization: Boolean? = null, + + @SerialName(value = "queryType") val queryType: QueryType? = null, + + @SerialName(value = "removeWordsIfNoResults") val removeWordsIfNoResults: RemoveWordsIfNoResults? = null, + + @SerialName(value = "mode") val mode: Mode? = null, + + @SerialName(value = "semanticSearch") val semanticSearch: IndexSettingsAsSearchParamsSemanticSearch? = null, + + /** Enables the advanced query syntax. */ + @SerialName(value = "advancedSyntax") val advancedSyntax: Boolean? = null, + + /** A list of words that should be considered as optional when found in the query. */ + @SerialName(value = "optionalWords") val optionalWords: List? = null, + + /** List of attributes on which you want to disable the exact ranking criterion. */ + @SerialName(value = "disableExactOnAttributes") val disableExactOnAttributes: List? = null, + + @SerialName(value = "exactOnSingleWordQuery") val exactOnSingleWordQuery: ExactOnSingleWordQuery? = null, + + /** List of alternatives that should be considered an exact match by the exact ranking criterion. */ + @SerialName(value = "alternativesAsExact") val alternativesAsExact: List? = null, + + /** Allows you to specify which advanced syntax features are active when ‘advancedSyntax' is enabled. */ + @SerialName(value = "advancedSyntaxFeatures") val advancedSyntaxFeatures: List? = null, + + /** Enriches the API’s response with meta-information as to how the query was processed. */ + @SerialName(value = "explain") val explain: List? = null, + + @SerialName(value = "distinct") val distinct: Distinct? = null, + + /** Name of the de-duplication attribute to be used with the distinct feature. */ + @SerialName(value = "attributeForDistinct") val attributeForDistinct: String? = null, + + /** Whether to take into account an index's synonyms for a particular search. */ + @SerialName(value = "synonyms") val synonyms: Boolean? = null, + + /** Whether to highlight and snippet the original word that matches the synonym or the synonym itself. */ + @SerialName(value = "replaceSynonymsInHighlight") val replaceSynonymsInHighlight: Boolean? = null, + + /** Precision of the proximity ranking criterion. */ + @SerialName(value = "minProximity") val minProximity: Int? = null, + + /** Choose which fields to return in the API response. This parameters applies to search and browse queries. */ + @SerialName(value = "responseFields") val responseFields: List? = null, + + /** Maximum number of facet hits to return during a search for facet values. For performance reasons, the maximum allowed number of returned values is 100. */ + @SerialName(value = "maxFacetHits") val maxFacetHits: Int? = null, + + /** When attribute is ranked above proximity in your ranking formula, proximity is used to select which searchable attribute is matched in the attribute ranking stage. */ + @SerialName(value = "attributeCriteriaComputedByMinProximity") val attributeCriteriaComputedByMinProximity: Boolean? = null, + + @SerialName(value = "renderingContent") val renderingContent: RenderingContent? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/IndexSettingsAsSearchParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/IndexSettingsAsSearchParams.kt new file mode 100644 index 0000000000..2a67445757 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/IndexSettingsAsSearchParams.kt @@ -0,0 +1,183 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * IndexSettingsAsSearchParams + * + * @param attributesForFaceting The complete list of attributes that will be used for faceting. + * @param attributesToRetrieve This parameter controls which attributes to retrieve and which not to retrieve. + * @param restrictSearchableAttributes Restricts a given query to look in only a subset of your searchable attributes. + * @param ranking Controls how Algolia should sort your results. + * @param customRanking Specifies the custom ranking criterion. + * @param relevancyStrictness Controls the relevancy threshold below which less relevant results aren't included in the results. + * @param attributesToHighlight List of attributes to highlight. + * @param attributesToSnippet List of attributes to snippet, with an optional maximum number of words to snippet. + * @param highlightPreTag The HTML string to insert before the highlighted parts in all highlight and snippet results. + * @param highlightPostTag The HTML string to insert after the highlighted parts in all highlight and snippet results. + * @param snippetEllipsisText String used as an ellipsis indicator when a snippet is truncated. + * @param restrictHighlightAndSnippetArrays Restrict highlighting and snippeting to items that matched the query. + * @param hitsPerPage Set the number of hits per page. + * @param minWordSizefor1Typo Minimum number of characters a word in the query string must contain to accept matches with 1 typo. + * @param minWordSizefor2Typos Minimum number of characters a word in the query string must contain to accept matches with 2 typos. + * @param typoTolerance + * @param allowTyposOnNumericTokens Whether to allow typos on numbers (\"numeric tokens\") in the query string. + * @param disableTypoToleranceOnAttributes List of attributes on which you want to disable typo tolerance. + * @param ignorePlurals + * @param removeStopWords + * @param keepDiacriticsOnCharacters List of characters that the engine shouldn't automatically normalize. + * @param queryLanguages Sets the languages to be used by language-specific settings and functionalities such as ignorePlurals, removeStopWords, and CJK word-detection. + * @param decompoundQuery Splits compound words into their composing atoms in the query. + * @param enableRules Whether Rules should be globally enabled. + * @param enablePersonalization Enable the Personalization feature. + * @param queryType + * @param removeWordsIfNoResults + * @param mode + * @param semanticSearch + * @param advancedSyntax Enables the advanced query syntax. + * @param optionalWords A list of words that should be considered as optional when found in the query. + * @param disableExactOnAttributes List of attributes on which you want to disable the exact ranking criterion. + * @param exactOnSingleWordQuery + * @param alternativesAsExact List of alternatives that should be considered an exact match by the exact ranking criterion. + * @param advancedSyntaxFeatures Allows you to specify which advanced syntax features are active when ‘advancedSyntax' is enabled. + * @param explain Enriches the API’s response with meta-information as to how the query was processed. + * @param distinct + * @param attributeForDistinct Name of the de-duplication attribute to be used with the distinct feature. + * @param synonyms Whether to take into account an index's synonyms for a particular search. + * @param replaceSynonymsInHighlight Whether to highlight and snippet the original word that matches the synonym or the synonym itself. + * @param minProximity Precision of the proximity ranking criterion. + * @param responseFields Choose which fields to return in the API response. This parameters applies to search and browse queries. + * @param maxFacetHits Maximum number of facet hits to return during a search for facet values. For performance reasons, the maximum allowed number of returned values is 100. + * @param attributeCriteriaComputedByMinProximity When attribute is ranked above proximity in your ranking formula, proximity is used to select which searchable attribute is matched in the attribute ranking stage. + * @param renderingContent + */ +@Serializable +public data class IndexSettingsAsSearchParams( + + /** The complete list of attributes that will be used for faceting. */ + @SerialName(value = "attributesForFaceting") val attributesForFaceting: List? = null, + + /** This parameter controls which attributes to retrieve and which not to retrieve. */ + @SerialName(value = "attributesToRetrieve") val attributesToRetrieve: List? = null, + + /** Restricts a given query to look in only a subset of your searchable attributes. */ + @SerialName(value = "restrictSearchableAttributes") val restrictSearchableAttributes: List? = null, + + /** Controls how Algolia should sort your results. */ + @SerialName(value = "ranking") val ranking: List? = null, + + /** Specifies the custom ranking criterion. */ + @SerialName(value = "customRanking") val customRanking: List? = null, + + /** Controls the relevancy threshold below which less relevant results aren't included in the results. */ + @SerialName(value = "relevancyStrictness") val relevancyStrictness: Int? = null, + + /** List of attributes to highlight. */ + @SerialName(value = "attributesToHighlight") val attributesToHighlight: List? = null, + + /** List of attributes to snippet, with an optional maximum number of words to snippet. */ + @SerialName(value = "attributesToSnippet") val attributesToSnippet: List? = null, + + /** The HTML string to insert before the highlighted parts in all highlight and snippet results. */ + @SerialName(value = "highlightPreTag") val highlightPreTag: String? = null, + + /** The HTML string to insert after the highlighted parts in all highlight and snippet results. */ + @SerialName(value = "highlightPostTag") val highlightPostTag: String? = null, + + /** String used as an ellipsis indicator when a snippet is truncated. */ + @SerialName(value = "snippetEllipsisText") val snippetEllipsisText: String? = null, + + /** Restrict highlighting and snippeting to items that matched the query. */ + @SerialName(value = "restrictHighlightAndSnippetArrays") val restrictHighlightAndSnippetArrays: Boolean? = null, + + /** Set the number of hits per page. */ + @SerialName(value = "hitsPerPage") val hitsPerPage: Int? = null, + + /** Minimum number of characters a word in the query string must contain to accept matches with 1 typo. */ + @SerialName(value = "minWordSizefor1Typo") val minWordSizefor1Typo: Int? = null, + + /** Minimum number of characters a word in the query string must contain to accept matches with 2 typos. */ + @SerialName(value = "minWordSizefor2Typos") val minWordSizefor2Typos: Int? = null, + + @SerialName(value = "typoTolerance") val typoTolerance: TypoTolerance? = null, + + /** Whether to allow typos on numbers (\"numeric tokens\") in the query string. */ + @SerialName(value = "allowTyposOnNumericTokens") val allowTyposOnNumericTokens: Boolean? = null, + + /** List of attributes on which you want to disable typo tolerance. */ + @SerialName(value = "disableTypoToleranceOnAttributes") val disableTypoToleranceOnAttributes: List? = null, + + @SerialName(value = "ignorePlurals") val ignorePlurals: IgnorePlurals? = null, + + @SerialName(value = "removeStopWords") val removeStopWords: RemoveStopWords? = null, + + /** List of characters that the engine shouldn't automatically normalize. */ + @SerialName(value = "keepDiacriticsOnCharacters") val keepDiacriticsOnCharacters: String? = null, + + /** Sets the languages to be used by language-specific settings and functionalities such as ignorePlurals, removeStopWords, and CJK word-detection. */ + @SerialName(value = "queryLanguages") val queryLanguages: List? = null, + + /** Splits compound words into their composing atoms in the query. */ + @SerialName(value = "decompoundQuery") val decompoundQuery: Boolean? = null, + + /** Whether Rules should be globally enabled. */ + @SerialName(value = "enableRules") val enableRules: Boolean? = null, + + /** Enable the Personalization feature. */ + @SerialName(value = "enablePersonalization") val enablePersonalization: Boolean? = null, + + @SerialName(value = "queryType") val queryType: QueryType? = null, + + @SerialName(value = "removeWordsIfNoResults") val removeWordsIfNoResults: RemoveWordsIfNoResults? = null, + + @SerialName(value = "mode") val mode: Mode? = null, + + @SerialName(value = "semanticSearch") val semanticSearch: IndexSettingsAsSearchParamsSemanticSearch? = null, + + /** Enables the advanced query syntax. */ + @SerialName(value = "advancedSyntax") val advancedSyntax: Boolean? = null, + + /** A list of words that should be considered as optional when found in the query. */ + @SerialName(value = "optionalWords") val optionalWords: List? = null, + + /** List of attributes on which you want to disable the exact ranking criterion. */ + @SerialName(value = "disableExactOnAttributes") val disableExactOnAttributes: List? = null, + + @SerialName(value = "exactOnSingleWordQuery") val exactOnSingleWordQuery: ExactOnSingleWordQuery? = null, + + /** List of alternatives that should be considered an exact match by the exact ranking criterion. */ + @SerialName(value = "alternativesAsExact") val alternativesAsExact: List? = null, + + /** Allows you to specify which advanced syntax features are active when ‘advancedSyntax' is enabled. */ + @SerialName(value = "advancedSyntaxFeatures") val advancedSyntaxFeatures: List? = null, + + /** Enriches the API’s response with meta-information as to how the query was processed. */ + @SerialName(value = "explain") val explain: List? = null, + + @SerialName(value = "distinct") val distinct: Distinct? = null, + + /** Name of the de-duplication attribute to be used with the distinct feature. */ + @SerialName(value = "attributeForDistinct") val attributeForDistinct: String? = null, + + /** Whether to take into account an index's synonyms for a particular search. */ + @SerialName(value = "synonyms") val synonyms: Boolean? = null, + + /** Whether to highlight and snippet the original word that matches the synonym or the synonym itself. */ + @SerialName(value = "replaceSynonymsInHighlight") val replaceSynonymsInHighlight: Boolean? = null, + + /** Precision of the proximity ranking criterion. */ + @SerialName(value = "minProximity") val minProximity: Int? = null, + + /** Choose which fields to return in the API response. This parameters applies to search and browse queries. */ + @SerialName(value = "responseFields") val responseFields: List? = null, + + /** Maximum number of facet hits to return during a search for facet values. For performance reasons, the maximum allowed number of returned values is 100. */ + @SerialName(value = "maxFacetHits") val maxFacetHits: Int? = null, + + /** When attribute is ranked above proximity in your ranking formula, proximity is used to select which searchable attribute is matched in the attribute ranking stage. */ + @SerialName(value = "attributeCriteriaComputedByMinProximity") val attributeCriteriaComputedByMinProximity: Boolean? = null, + + @SerialName(value = "renderingContent") val renderingContent: RenderingContent? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/IndexSettingsAsSearchParamsSemanticSearch.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/IndexSettingsAsSearchParamsSemanticSearch.kt new file mode 100644 index 0000000000..73d048a5c0 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/IndexSettingsAsSearchParamsSemanticSearch.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The settings relevant for configuration of the semantic search engine. These settings are only used when the mode is set to 'neuralSearch'. + * + * @param eventSources When null, the current index / replica group will be used as the event source. + */ +@Serializable +public data class IndexSettingsAsSearchParamsSemanticSearch( + + /** When null, the current index / replica group will be used as the event source. */ + @SerialName(value = "eventSources") val eventSources: List? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Languages.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Languages.kt new file mode 100644 index 0000000000..b0da826a8c --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Languages.kt @@ -0,0 +1,22 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * A dictionary language. + * + * @param plurals + * @param stopwords + * @param compounds + */ +@Serializable +public data class Languages( + + @SerialName(value = "plurals") val plurals: DictionaryLanguage, + + @SerialName(value = "stopwords") val stopwords: DictionaryLanguage, + + @SerialName(value = "compounds") val compounds: DictionaryLanguage, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ListApiKeysResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ListApiKeysResponse.kt new file mode 100644 index 0000000000..bcb9700adb --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ListApiKeysResponse.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * ListApiKeysResponse + * + * @param keys List of api keys. + */ +@Serializable +public data class ListApiKeysResponse( + + /** List of api keys. */ + @SerialName(value = "keys") val keys: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ListClustersResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ListClustersResponse.kt new file mode 100644 index 0000000000..139d2a873b --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ListClustersResponse.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Array of clusters. + * + * @param topUsers Mapping of cluster names to top users. + */ +@Serializable +public data class ListClustersResponse( + + /** Mapping of cluster names to top users. */ + @SerialName(value = "topUsers") val topUsers: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ListIndicesResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ListIndicesResponse.kt new file mode 100644 index 0000000000..59000d166a --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ListIndicesResponse.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * ListIndicesResponse + * + * @param items List of the fetched indices. + * @param nbPages Number of pages. + */ +@Serializable +public data class ListIndicesResponse( + + /** List of the fetched indices. */ + @SerialName(value = "items") val items: List, + + /** Number of pages. */ + @SerialName(value = "nbPages") val nbPages: Int? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ListUserIdsResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ListUserIdsResponse.kt new file mode 100644 index 0000000000..98edce606b --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ListUserIdsResponse.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * UserIDs data. + * + * @param userIDs List of userIDs. + */ +@Serializable +public data class ListUserIdsResponse( + + /** List of userIDs. */ + @SerialName(value = "userIDs") val userIDs: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Log.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Log.kt new file mode 100644 index 0000000000..37ade61d9a --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Log.kt @@ -0,0 +1,73 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Log + * + * @param timestamp Timestamp in ISO-8601 format. + * @param method HTTP method of the performed request. + * @param answerCode HTTP response code. + * @param queryBody Request body. Truncated after 1000 characters. + * @param answer Answer body. Truncated after 1000 characters. + * @param url Request URL. + * @param ip IP of the client which performed the request. + * @param queryHeaders Request Headers (API Key is obfuscated). + * @param sha1 SHA1 signature of the log entry. + * @param nbApiCalls Number of API calls. + * @param processingTimeMs Processing time for the query. It doesn't include network time. + * @param index Index targeted by the query. + * @param queryParams Query parameters sent with the request. + * @param queryNbHits Number of hits returned for the query. + * @param innerQueries Array of all performed queries for the given request. + */ +@Serializable +public data class Log( + + /** Timestamp in ISO-8601 format. */ + @SerialName(value = "timestamp") val timestamp: String, + + /** HTTP method of the performed request. */ + @SerialName(value = "method") val method: String, + + /** HTTP response code. */ + @SerialName(value = "answer_code") val answerCode: String, + + /** Request body. Truncated after 1000 characters. */ + @SerialName(value = "query_body") val queryBody: String, + + /** Answer body. Truncated after 1000 characters. */ + @SerialName(value = "answer") val answer: String, + + /** Request URL. */ + @SerialName(value = "url") val url: String, + + /** IP of the client which performed the request. */ + @SerialName(value = "ip") val ip: String, + + /** Request Headers (API Key is obfuscated). */ + @SerialName(value = "query_headers") val queryHeaders: String, + + /** SHA1 signature of the log entry. */ + @SerialName(value = "sha1") val sha1: String, + + /** Number of API calls. */ + @SerialName(value = "nb_api_calls") val nbApiCalls: String, + + /** Processing time for the query. It doesn't include network time. */ + @SerialName(value = "processing_time_ms") val processingTimeMs: String, + + /** Index targeted by the query. */ + @SerialName(value = "index") val index: String? = null, + + /** Query parameters sent with the request. */ + @SerialName(value = "query_params") val queryParams: String? = null, + + /** Number of hits returned for the query. */ + @SerialName(value = "query_nb_hits") val queryNbHits: String? = null, + + /** Array of all performed queries for the given request. */ + @SerialName(value = "inner_queries") val innerQueries: List? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/LogQuery.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/LogQuery.kt new file mode 100644 index 0000000000..bd71ee9b0a --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/LogQuery.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * LogQuery + * + * @param indexName Index targeted by the query. + * @param userToken User identifier. + * @param queryId QueryID for the given query. + */ +@Serializable +public data class LogQuery( + + /** Index targeted by the query. */ + @SerialName(value = "index_name") val indexName: String? = null, + + /** User identifier. */ + @SerialName(value = "user_token") val userToken: String? = null, + + /** QueryID for the given query. */ + @SerialName(value = "query_id") val queryId: String? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/LogType.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/LogType.kt new file mode 100644 index 0000000000..de3a268370 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/LogType.kt @@ -0,0 +1,22 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* + +@Serializable +public enum class LogType(public val value: kotlin.String) { + + @SerialName(value = "all") + All("all"), + + @SerialName(value = "query") + Query("query"), + + @SerialName(value = "build") + Build("build"), + + @SerialName(value = "error") + Error("error"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/MatchLevel.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/MatchLevel.kt new file mode 100644 index 0000000000..c99ca8e27a --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/MatchLevel.kt @@ -0,0 +1,22 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* + +/** + * Indicates how well the attribute matched the search query. + */ +@Serializable +public enum class MatchLevel(public val value: kotlin.String) { + + @SerialName(value = "none") + None("none"), + + @SerialName(value = "partial") + Partial("partial"), + + @SerialName(value = "full") + Full("full"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/MatchedGeoLocation.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/MatchedGeoLocation.kt new file mode 100644 index 0000000000..3c2d672ea8 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/MatchedGeoLocation.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * MatchedGeoLocation + * + * @param lat Latitude of the matched location. + * @param lng Longitude of the matched location. + * @param distance Distance between the matched location and the search location (in meters). + */ +@Serializable +public data class MatchedGeoLocation( + + /** Latitude of the matched location. */ + @SerialName(value = "lat") val lat: Double? = null, + + /** Longitude of the matched location. */ + @SerialName(value = "lng") val lng: Double? = null, + + /** Distance between the matched location and the search location (in meters). */ + @SerialName(value = "distance") val distance: Int? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/MixedSearchFilters.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/MixedSearchFilters.kt new file mode 100644 index 0000000000..f82d9eaa4f --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/MixedSearchFilters.kt @@ -0,0 +1,83 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * MixedSearchFilters + */ +@Serializable(MixedSearchFiltersSerializer::class) +public sealed interface MixedSearchFilters { + + public data class ListOfStringWrapper(val value: List) : MixedSearchFilters + + public data class StringWrapper(val value: String) : MixedSearchFilters + + public companion object { + + /** + * MixedSearchFilters as List + * + */ + public fun ListOfString( + value: List, + ): ListOfStringWrapper = ListOfStringWrapper( + value = value, + ) + + /** + * MixedSearchFilters as String + * + */ + public fun String( + value: String, + ): StringWrapper = StringWrapper( + value = value, + ) + } +} + +internal class MixedSearchFiltersSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("MixedSearchFilters") + + override fun serialize(encoder: Encoder, value: MixedSearchFilters) { + when (value) { + is MixedSearchFilters.ListOfStringWrapper -> ListSerializer(String.serializer()).serialize(encoder, value.value) + is MixedSearchFilters.StringWrapper -> String.serializer().serialize(encoder, value.value) + } + } + + override fun deserialize(decoder: Decoder): MixedSearchFilters { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize List + if (tree is JsonArray) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize List (error: ${e.message})") + } + } + + // deserialize String + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize String (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Mode.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Mode.kt new file mode 100644 index 0000000000..6582593eb8 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Mode.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* + +/** + * The search mode that the index will use to query for results. + */ +@Serializable +public enum class Mode(public val value: kotlin.String) { + + @SerialName(value = "neuralSearch") + NeuralSearch("neuralSearch"), + + @SerialName(value = "keywordSearch") + KeywordSearch("keywordSearch"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/MultipleBatchRequest.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/MultipleBatchRequest.kt new file mode 100644 index 0000000000..3d3c00f18b --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/MultipleBatchRequest.kt @@ -0,0 +1,24 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * MultipleBatchRequest + * + * @param action + * @param body arguments to the operation (depends on the type of the operation). + * @param indexName Index to target for this operation. + */ +@Serializable +public data class MultipleBatchRequest( + + @SerialName(value = "action") val action: Action, + + /** arguments to the operation (depends on the type of the operation). */ + @SerialName(value = "body") val body: JsonObject, + + /** Index to target for this operation. */ + @SerialName(value = "indexName") val indexName: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/MultipleBatchResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/MultipleBatchResponse.kt new file mode 100644 index 0000000000..ee52e675db --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/MultipleBatchResponse.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * MultipleBatchResponse + * + * @param taskID List of tasksIDs per index. + * @param objectIDs List of objectID. + */ +@Serializable +public data class MultipleBatchResponse( + + /** List of tasksIDs per index. */ + @SerialName(value = "taskID") val taskID: Map, + + /** List of objectID. */ + @SerialName(value = "objectIDs") val objectIDs: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/NumericFilters.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/NumericFilters.kt new file mode 100644 index 0000000000..65eb9b02e3 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/NumericFilters.kt @@ -0,0 +1,83 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Filter on numeric attributes. + */ +@Serializable(NumericFiltersSerializer::class) +public sealed interface NumericFilters { + + public data class ListOfMixedSearchFiltersWrapper(val value: List) : NumericFilters + + public data class StringWrapper(val value: String) : NumericFilters + + public companion object { + + /** + * NumericFilters as List + * + */ + public fun ListOfMixedSearchFilters( + value: List, + ): ListOfMixedSearchFiltersWrapper = ListOfMixedSearchFiltersWrapper( + value = value, + ) + + /** + * NumericFilters as String + * + */ + public fun String( + value: String, + ): StringWrapper = StringWrapper( + value = value, + ) + } +} + +internal class NumericFiltersSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("NumericFilters") + + override fun serialize(encoder: Encoder, value: NumericFilters) { + when (value) { + is NumericFilters.ListOfMixedSearchFiltersWrapper -> ListSerializer(MixedSearchFilters.serializer()).serialize(encoder, value.value) + is NumericFilters.StringWrapper -> String.serializer().serialize(encoder, value.value) + } + } + + override fun deserialize(decoder: Decoder): NumericFilters { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize List + if (tree is JsonArray) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize List (error: ${e.message})") + } + } + + // deserialize String + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize String (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/OperationIndexParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/OperationIndexParams.kt new file mode 100644 index 0000000000..991c709ea8 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/OperationIndexParams.kt @@ -0,0 +1,24 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * OperationIndexParams + * + * @param operation + * @param destination The Algolia index name. + * @param scope Scope of the data to copy. When absent, a full copy is performed. When present, only the selected scopes are copied. + */ +@Serializable +public data class OperationIndexParams( + + @SerialName(value = "operation") val operation: OperationType, + + /** The Algolia index name. */ + @SerialName(value = "destination") val destination: String, + + /** Scope of the data to copy. When absent, a full copy is performed. When present, only the selected scopes are copied. */ + @SerialName(value = "scope") val scope: List? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/OperationType.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/OperationType.kt new file mode 100644 index 0000000000..39ac768451 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/OperationType.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* + +/** + * Type of operation to perform (move or copy). + */ +@Serializable +public enum class OperationType(public val value: kotlin.String) { + + @SerialName(value = "move") + Move("move"), + + @SerialName(value = "copy") + Copy("copy"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/OptionalFilters.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/OptionalFilters.kt new file mode 100644 index 0000000000..3351de1fa2 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/OptionalFilters.kt @@ -0,0 +1,83 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Create filters for ranking purposes, where records that match the filter are ranked higher, or lower in the case of a negative optional filter. + */ +@Serializable(OptionalFiltersSerializer::class) +public sealed interface OptionalFilters { + + public data class ListOfMixedSearchFiltersWrapper(val value: List) : OptionalFilters + + public data class StringWrapper(val value: String) : OptionalFilters + + public companion object { + + /** + * OptionalFilters as List + * + */ + public fun ListOfMixedSearchFilters( + value: List, + ): ListOfMixedSearchFiltersWrapper = ListOfMixedSearchFiltersWrapper( + value = value, + ) + + /** + * OptionalFilters as String + * + */ + public fun String( + value: String, + ): StringWrapper = StringWrapper( + value = value, + ) + } +} + +internal class OptionalFiltersSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("OptionalFilters") + + override fun serialize(encoder: Encoder, value: OptionalFilters) { + when (value) { + is OptionalFilters.ListOfMixedSearchFiltersWrapper -> ListSerializer(MixedSearchFilters.serializer()).serialize(encoder, value.value) + is OptionalFilters.StringWrapper -> String.serializer().serialize(encoder, value.value) + } + } + + override fun deserialize(decoder: Decoder): OptionalFilters { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize List + if (tree is JsonArray) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize List (error: ${e.message})") + } + } + + // deserialize String + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize String (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Params.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Params.kt new file mode 100644 index 0000000000..01a7fcd247 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Params.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Additional search parameters. Any valid search parameter is allowed. + * + * @param query + * @param automaticFacetFilters + * @param automaticOptionalFacetFilters + * @param renderingContent + */ +@Serializable +public data class Params( + + @SerialName(value = "query") val query: ConsequenceQuery? = null, + + @SerialName(value = "automaticFacetFilters") val automaticFacetFilters: AutomaticFacetFilters? = null, + + @SerialName(value = "automaticOptionalFacetFilters") val automaticOptionalFacetFilters: AutomaticFacetFilters? = null, + + @SerialName(value = "renderingContent") val renderingContent: RenderingContent? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Personalization.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Personalization.kt new file mode 100644 index 0000000000..0ad7cbe325 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Personalization.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Personalization + * + * @param filtersScore The score of the filters. + * @param rankingScore The score of the ranking. + * @param score The score of the event. + */ +@Serializable +public data class Personalization( + + /** The score of the filters. */ + @SerialName(value = "filtersScore") val filtersScore: Int? = null, + + /** The score of the ranking. */ + @SerialName(value = "rankingScore") val rankingScore: Int? = null, + + /** The score of the event. */ + @SerialName(value = "score") val score: Int? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Promote.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Promote.kt new file mode 100644 index 0000000000..1bc8d1ef68 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Promote.kt @@ -0,0 +1,87 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Promote + */ +@Serializable(PromoteSerializer::class) +public sealed interface Promote { + + public companion object { + + /** + * Single objectID to promote as hits. + * + * @param objectID Unique identifier of the object to promote. + * @param position The position to promote the objects to (zero-based). If you pass objectIDs, the objects are placed at this position as a group. For example, if you pass four objectIDs to position 0, the objects take the first four positions. + */ + public fun PromoteObjectID( + objectID: String, + position: Int, + ): PromoteObjectID = com.algolia.client.model.search.PromoteObjectID( + objectID = objectID, + position = position, + ) + + /** + * Multiple objectIDs to promote as hits. + * + * @param objectIDs Array of unique identifiers of the objects to promote. + * @param position The position to promote the objects to (zero-based). If you pass objectIDs, the objects are placed at this position as a group. For example, if you pass four objectIDs to position 0, the objects take the first four positions. + */ + public fun PromoteObjectIDs( + objectIDs: List, + position: Int, + ): PromoteObjectIDs = com.algolia.client.model.search.PromoteObjectIDs( + objectIDs = objectIDs, + position = position, + ) + } +} + +internal class PromoteSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("Promote") + + override fun serialize(encoder: Encoder, value: Promote) { + when (value) { + is PromoteObjectID -> PromoteObjectID.serializer().serialize(encoder, value) + is PromoteObjectIDs -> PromoteObjectIDs.serializer().serialize(encoder, value) + } + } + + override fun deserialize(decoder: Decoder): Promote { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize PromoteObjectID + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize PromoteObjectID (error: ${e.message})") + } + } + + // deserialize PromoteObjectIDs + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize PromoteObjectIDs (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/PromoteObjectID.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/PromoteObjectID.kt new file mode 100644 index 0000000000..5cb3f1cd06 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/PromoteObjectID.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Single objectID to promote as hits. + * + * @param objectID Unique identifier of the object to promote. + * @param position The position to promote the objects to (zero-based). If you pass objectIDs, the objects are placed at this position as a group. For example, if you pass four objectIDs to position 0, the objects take the first four positions. + */ +@Serializable +public data class PromoteObjectID( + + /** Unique identifier of the object to promote. */ + @SerialName(value = "objectID") val objectID: String, + + /** The position to promote the objects to (zero-based). If you pass objectIDs, the objects are placed at this position as a group. For example, if you pass four objectIDs to position 0, the objects take the first four positions. */ + @SerialName(value = "position") val position: Int, +) : Promote diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/PromoteObjectIDs.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/PromoteObjectIDs.kt new file mode 100644 index 0000000000..304d9135c4 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/PromoteObjectIDs.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Multiple objectIDs to promote as hits. + * + * @param objectIDs Array of unique identifiers of the objects to promote. + * @param position The position to promote the objects to (zero-based). If you pass objectIDs, the objects are placed at this position as a group. For example, if you pass four objectIDs to position 0, the objects take the first four positions. + */ +@Serializable +public data class PromoteObjectIDs( + + /** Array of unique identifiers of the objects to promote. */ + @SerialName(value = "objectIDs") val objectIDs: List, + + /** The position to promote the objects to (zero-based). If you pass objectIDs, the objects are placed at this position as a group. For example, if you pass four objectIDs to position 0, the objects take the first four positions. */ + @SerialName(value = "position") val position: Int, +) : Promote diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/QueryType.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/QueryType.kt new file mode 100644 index 0000000000..b85d923345 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/QueryType.kt @@ -0,0 +1,22 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* + +/** + * Controls if and how query words are interpreted as prefixes. + */ +@Serializable +public enum class QueryType(public val value: kotlin.String) { + + @SerialName(value = "prefixLast") + PrefixLast("prefixLast"), + + @SerialName(value = "prefixAll") + PrefixAll("prefixAll"), + + @SerialName(value = "prefixNone") + PrefixNone("prefixNone"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/RankingInfo.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/RankingInfo.kt new file mode 100644 index 0000000000..b53130a080 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/RankingInfo.kt @@ -0,0 +1,63 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * RankingInfo + * + * @param filters This field is reserved for advanced usage. + * @param firstMatchedWord Position of the most important matched attribute in the attributes to index list. + * @param geoDistance Distance between the geo location in the search query and the best matching geo location in the record, divided by the geo precision (in meters). + * @param nbExactWords Number of exactly matched words. + * @param nbTypos Number of typos encountered when matching the record. + * @param promoted Present and set to true if a Rule promoted the hit. + * @param userScore Custom ranking for the object, expressed as a single integer value. + * @param words Number of matched words, including prefixes and typos. + * @param geoPrecision Precision used when computing the geo distance, in meters. + * @param matchedGeoLocation + * @param personalization + * @param proximityDistance When the query contains more than one word, the sum of the distances between matched words (in meters). + * @param promotedByReRanking Wether the record are promoted by the re-ranking strategy. + */ +@Serializable +public data class RankingInfo( + + /** This field is reserved for advanced usage. */ + @SerialName(value = "filters") val filters: Int, + + /** Position of the most important matched attribute in the attributes to index list. */ + @SerialName(value = "firstMatchedWord") val firstMatchedWord: Int, + + /** Distance between the geo location in the search query and the best matching geo location in the record, divided by the geo precision (in meters). */ + @SerialName(value = "geoDistance") val geoDistance: Int, + + /** Number of exactly matched words. */ + @SerialName(value = "nbExactWords") val nbExactWords: Int, + + /** Number of typos encountered when matching the record. */ + @SerialName(value = "nbTypos") val nbTypos: Int, + + /** Present and set to true if a Rule promoted the hit. */ + @SerialName(value = "promoted") val promoted: Boolean, + + /** Custom ranking for the object, expressed as a single integer value. */ + @SerialName(value = "userScore") val userScore: Int, + + /** Number of matched words, including prefixes and typos. */ + @SerialName(value = "words") val words: Int, + + /** Precision used when computing the geo distance, in meters. */ + @SerialName(value = "geoPrecision") val geoPrecision: Int? = null, + + @SerialName(value = "matchedGeoLocation") val matchedGeoLocation: MatchedGeoLocation? = null, + + @SerialName(value = "personalization") val personalization: Personalization? = null, + + /** When the query contains more than one word, the sum of the distances between matched words (in meters). */ + @SerialName(value = "proximityDistance") val proximityDistance: Int? = null, + + /** Wether the record are promoted by the re-ranking strategy. */ + @SerialName(value = "promotedByReRanking") val promotedByReRanking: Boolean? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ReRankingApplyFilter.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ReRankingApplyFilter.kt new file mode 100644 index 0000000000..45c50f3b80 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ReRankingApplyFilter.kt @@ -0,0 +1,83 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * When Dynamic Re-Ranking is enabled, only records that match these filters will be impacted by Dynamic Re-Ranking. + */ +@Serializable(ReRankingApplyFilterSerializer::class) +public sealed interface ReRankingApplyFilter { + + public data class ListOfMixedSearchFiltersWrapper(val value: List) : ReRankingApplyFilter + + public data class StringWrapper(val value: String) : ReRankingApplyFilter + + public companion object { + + /** + * ReRankingApplyFilter as List + * + */ + public fun ListOfMixedSearchFilters( + value: List, + ): ListOfMixedSearchFiltersWrapper = ListOfMixedSearchFiltersWrapper( + value = value, + ) + + /** + * ReRankingApplyFilter as String + * + */ + public fun String( + value: String, + ): StringWrapper = StringWrapper( + value = value, + ) + } +} + +internal class ReRankingApplyFilterSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("ReRankingApplyFilter") + + override fun serialize(encoder: Encoder, value: ReRankingApplyFilter) { + when (value) { + is ReRankingApplyFilter.ListOfMixedSearchFiltersWrapper -> ListSerializer(MixedSearchFilters.serializer()).serialize(encoder, value.value) + is ReRankingApplyFilter.StringWrapper -> String.serializer().serialize(encoder, value.value) + } + } + + override fun deserialize(decoder: Decoder): ReRankingApplyFilter { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize List + if (tree is JsonArray) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize List (error: ${e.message})") + } + } + + // deserialize String + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize String (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/RedirectRuleIndexMetadata.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/RedirectRuleIndexMetadata.kt new file mode 100644 index 0000000000..ed34db500c --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/RedirectRuleIndexMetadata.kt @@ -0,0 +1,32 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * RedirectRuleIndexMetadata + * + * @param source Source index for the redirect rule. + * @param dest Destination index for the redirect rule. + * @param reason Reason for the redirect rule. + * @param succeed Status for the redirect rule. + * @param `data` + */ +@Serializable +public data class RedirectRuleIndexMetadata( + + /** Source index for the redirect rule. */ + @SerialName(value = "source") val source: String, + + /** Destination index for the redirect rule. */ + @SerialName(value = "dest") val dest: String, + + /** Reason for the redirect rule. */ + @SerialName(value = "reason") val reason: String, + + /** Status for the redirect rule. */ + @SerialName(value = "succeed") val succeed: Boolean, + + @SerialName(value = "data") val `data`: RedirectRuleIndexMetadataData, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/RedirectRuleIndexMetadataData.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/RedirectRuleIndexMetadataData.kt new file mode 100644 index 0000000000..6623d12295 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/RedirectRuleIndexMetadataData.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Data for the redirect rule. + * + * @param ruleObjectID + */ +@Serializable +public data class RedirectRuleIndexMetadataData( + + @SerialName(value = "ruleObjectID") val ruleObjectID: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/RemoveStopWords.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/RemoveStopWords.kt new file mode 100644 index 0000000000..5af5f9cfe8 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/RemoveStopWords.kt @@ -0,0 +1,83 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Removes stop (common) words from the query before executing it. removeStopWords is used in conjunction with the queryLanguages setting. list: language ISO codes for which ignoring plurals should be enabled. This list will override any values that you may have set in queryLanguages. true: enables the stop word functionality, ensuring that stop words are removed from consideration in a search. The languages supported here are either every language, or those set by queryLanguages. false: disables stop word functionality, allowing stop words to be taken into account in a search. + */ +@Serializable(RemoveStopWordsSerializer::class) +public sealed interface RemoveStopWords { + + public data class BooleanWrapper(val value: Boolean) : RemoveStopWords + + public data class ListOfStringWrapper(val value: List) : RemoveStopWords + + public companion object { + + /** + * RemoveStopWords as Boolean + * + */ + public fun Boolean( + value: Boolean, + ): BooleanWrapper = BooleanWrapper( + value = value, + ) + + /** + * RemoveStopWords as List + * + */ + public fun ListOfString( + value: List, + ): ListOfStringWrapper = ListOfStringWrapper( + value = value, + ) + } +} + +internal class RemoveStopWordsSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("RemoveStopWords") + + override fun serialize(encoder: Encoder, value: RemoveStopWords) { + when (value) { + is RemoveStopWords.BooleanWrapper -> Boolean.serializer().serialize(encoder, value.value) + is RemoveStopWords.ListOfStringWrapper -> ListSerializer(String.serializer()).serialize(encoder, value.value) + } + } + + override fun deserialize(decoder: Decoder): RemoveStopWords { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize Boolean + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize Boolean (error: ${e.message})") + } + } + + // deserialize List + if (tree is JsonArray) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize List (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/RemoveUserIdResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/RemoveUserIdResponse.kt new file mode 100644 index 0000000000..833da2d502 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/RemoveUserIdResponse.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * RemoveUserIdResponse + * + * @param deletedAt Date of deletion (ISO-8601 format). + */ +@Serializable +public data class RemoveUserIdResponse( + + /** Date of deletion (ISO-8601 format). */ + @SerialName(value = "deletedAt") val deletedAt: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/RemoveWordsIfNoResults.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/RemoveWordsIfNoResults.kt new file mode 100644 index 0000000000..24a60160e9 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/RemoveWordsIfNoResults.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* + +/** + * Selects a strategy to remove words from the query when it doesn't match any hits. + */ +@Serializable +public enum class RemoveWordsIfNoResults(public val value: kotlin.String) { + + @SerialName(value = "none") + None("none"), + + @SerialName(value = "lastWords") + LastWords("lastWords"), + + @SerialName(value = "firstWords") + FirstWords("firstWords"), + + @SerialName(value = "allOptional") + AllOptional("allOptional"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/RenderingContent.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/RenderingContent.kt new file mode 100644 index 0000000000..2aa1f72b77 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/RenderingContent.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Content defining how the search interface should be rendered. Can be set via the settings for a default value and can be overridden via rules. + * + * @param facetOrdering + */ +@Serializable +public data class RenderingContent( + + @SerialName(value = "facetOrdering") val facetOrdering: FacetOrdering? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ReplaceSourceResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ReplaceSourceResponse.kt new file mode 100644 index 0000000000..12b09c7c2b --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ReplaceSourceResponse.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * ReplaceSourceResponse + * + * @param updatedAt Date of last update (ISO-8601 format). + */ +@Serializable +public data class ReplaceSourceResponse( + + /** Date of last update (ISO-8601 format). */ + @SerialName(value = "updatedAt") val updatedAt: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Rule.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Rule.kt new file mode 100644 index 0000000000..69ab300448 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Rule.kt @@ -0,0 +1,36 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Rule object. + * + * @param objectID Unique identifier of the object. + * @param conditions A list of conditions that should apply to activate a Rule. You can use up to 25 conditions per Rule. + * @param consequence + * @param description This field is intended for Rule management purposes, in particular to ease searching for Rules and presenting them to human readers. It's not interpreted by the API. + * @param enabled Whether the Rule is enabled. Disabled Rules remain in the index, but aren't applied at query time. + * @param validity By default, Rules are permanently valid. When validity periods are specified, the Rule applies only during those periods; it's ignored the rest of the time. The list must not be empty. + */ +@Serializable +public data class Rule( + + /** Unique identifier of the object. */ + @SerialName(value = "objectID") val objectID: String, + + /** A list of conditions that should apply to activate a Rule. You can use up to 25 conditions per Rule. */ + @SerialName(value = "conditions") val conditions: List? = null, + + @SerialName(value = "consequence") val consequence: Consequence? = null, + + /** This field is intended for Rule management purposes, in particular to ease searching for Rules and presenting them to human readers. It's not interpreted by the API. */ + @SerialName(value = "description") val description: String? = null, + + /** Whether the Rule is enabled. Disabled Rules remain in the index, but aren't applied at query time. */ + @SerialName(value = "enabled") val enabled: Boolean? = null, + + /** By default, Rules are permanently valid. When validity periods are specified, the Rule applies only during those periods; it's ignored the rest of the time. The list must not be empty. */ + @SerialName(value = "validity") val validity: List? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SaveObjectResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SaveObjectResponse.kt new file mode 100644 index 0000000000..2416a5c4f3 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SaveObjectResponse.kt @@ -0,0 +1,24 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SaveObjectResponse + * + * @param createdAt + * @param taskID taskID of the task to wait for. + * @param objectID Unique identifier of the object. + */ +@Serializable +public data class SaveObjectResponse( + + @SerialName(value = "createdAt") val createdAt: String, + + /** taskID of the task to wait for. */ + @SerialName(value = "taskID") val taskID: Long, + + /** Unique identifier of the object. */ + @SerialName(value = "objectID") val objectID: String? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SaveSynonymResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SaveSynonymResponse.kt new file mode 100644 index 0000000000..cb5814834a --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SaveSynonymResponse.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SaveSynonymResponse + * + * @param taskID taskID of the task to wait for. + * @param updatedAt Date of last update (ISO-8601 format). + * @param id objectID of the inserted object. + */ +@Serializable +public data class SaveSynonymResponse( + + /** taskID of the task to wait for. */ + @SerialName(value = "taskID") val taskID: Long, + + /** Date of last update (ISO-8601 format). */ + @SerialName(value = "updatedAt") val updatedAt: String, + + /** objectID of the inserted object. */ + @SerialName(value = "id") val id: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ScopeType.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ScopeType.kt new file mode 100644 index 0000000000..72bc936934 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/ScopeType.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* + +@Serializable +public enum class ScopeType(public val value: kotlin.String) { + + @SerialName(value = "settings") + Settings("settings"), + + @SerialName(value = "synonyms") + Synonyms("synonyms"), + + @SerialName(value = "rules") + Rules("rules"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchDictionaryEntriesParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchDictionaryEntriesParams.kt new file mode 100644 index 0000000000..894c196660 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchDictionaryEntriesParams.kt @@ -0,0 +1,29 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The `searchDictionaryEntries` parameters. + * + * @param query The text to search in the index. + * @param page Specify the page to retrieve. + * @param hitsPerPage Set the number of hits per page. + * @param language Language ISO code supported by the dictionary (e.g., \"en\" for English). + */ +@Serializable +public data class SearchDictionaryEntriesParams( + + /** The text to search in the index. */ + @SerialName(value = "query") val query: String, + + /** Specify the page to retrieve. */ + @SerialName(value = "page") val page: Int? = null, + + /** Set the number of hits per page. */ + @SerialName(value = "hitsPerPage") val hitsPerPage: Int? = null, + + /** Language ISO code supported by the dictionary (e.g., \"en\" for English). */ + @SerialName(value = "language") val language: String? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchForFacetValuesRequest.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchForFacetValuesRequest.kt new file mode 100644 index 0000000000..8e64ab592b --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchForFacetValuesRequest.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SearchForFacetValuesRequest + * + * @param params Search parameters as URL-encoded query string. + * @param facetQuery Text to search inside the facet's values. + * @param maxFacetHits Maximum number of facet hits to return during a search for facet values. For performance reasons, the maximum allowed number of returned values is 100. + */ +@Serializable +public data class SearchForFacetValuesRequest( + + /** Search parameters as URL-encoded query string. */ + @SerialName(value = "params") val params: String? = null, + + /** Text to search inside the facet's values. */ + @SerialName(value = "facetQuery") val facetQuery: String? = null, + + /** Maximum number of facet hits to return during a search for facet values. For performance reasons, the maximum allowed number of returned values is 100. */ + @SerialName(value = "maxFacetHits") val maxFacetHits: Int? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchForFacetValuesResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchForFacetValuesResponse.kt new file mode 100644 index 0000000000..07593f7c0f --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchForFacetValuesResponse.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SearchForFacetValuesResponse + * + * @param facetHits + */ +@Serializable +public data class SearchForFacetValuesResponse( + + @SerialName(value = "facetHits") val facetHits: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchForFacets.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchForFacets.kt new file mode 100644 index 0000000000..eacc01030d --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchForFacets.kt @@ -0,0 +1,332 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SearchForFacets + * + * @param facet The `facet` name. + * @param indexName The Algolia index name. + * @param type + * @param params Search parameters as URL-encoded query string. + * @param query The text to search in the index. + * @param similarQuery Overrides the query parameter and performs a more generic search that can be used to find \"similar\" results. + * @param filters Filter the query with numeric, facet and/or tag filters. + * @param facetFilters + * @param optionalFilters + * @param numericFilters + * @param tagFilters + * @param sumOrFiltersScores Determines how to calculate the total score for filtering. + * @param facets Retrieve facets and their facet values. + * @param maxValuesPerFacet Maximum number of facet values to return for each facet during a regular search. + * @param facetingAfterDistinct Force faceting to be applied after de-duplication (via the Distinct setting). + * @param sortFacetValuesBy Controls how facet values are fetched. + * @param page Specify the page to retrieve. + * @param offset Specify the offset of the first hit to return. + * @param length Set the number of hits to retrieve (used only with offset). + * @param aroundLatLng Search for entries around a central geolocation, enabling a geo search within a circular area. + * @param aroundLatLngViaIP Search for entries around a given location automatically computed from the requester's IP address. + * @param aroundRadius + * @param aroundPrecision Precision of geo search (in meters), to add grouping by geo location to the ranking formula. + * @param minimumAroundRadius Minimum radius (in meters) used for a geo search when aroundRadius is not set. + * @param insideBoundingBox Search inside a rectangular area (in geo coordinates). + * @param insidePolygon Search inside a polygon (in geo coordinates). + * @param naturalLanguages This parameter changes the default values of certain parameters and settings that work best for a natural language query, such as ignorePlurals, removeStopWords, removeWordsIfNoResults, analyticsTags and ruleContexts. These parameters and settings work well together when the query is formatted in natural language instead of keywords, for example when your user performs a voice search. + * @param ruleContexts Enables contextual rules. + * @param personalizationImpact Define the impact of the Personalization feature. + * @param userToken Associates a certain user token with the current search. + * @param getRankingInfo Retrieve detailed ranking information. + * @param clickAnalytics Enable the Click Analytics feature. + * @param analytics Whether the current query will be taken into account in the Analytics. + * @param analyticsTags List of tags to apply to the query for analytics purposes. + * @param percentileComputation Whether to include or exclude a query from the processing-time percentile computation. + * @param enableABTest Whether this search should participate in running AB tests. + * @param enableReRanking Whether this search should use AI Re-Ranking. + * @param reRankingApplyFilter + * @param attributesForFaceting The complete list of attributes that will be used for faceting. + * @param attributesToRetrieve This parameter controls which attributes to retrieve and which not to retrieve. + * @param restrictSearchableAttributes Restricts a given query to look in only a subset of your searchable attributes. + * @param ranking Controls how Algolia should sort your results. + * @param customRanking Specifies the custom ranking criterion. + * @param relevancyStrictness Controls the relevancy threshold below which less relevant results aren't included in the results. + * @param attributesToHighlight List of attributes to highlight. + * @param attributesToSnippet List of attributes to snippet, with an optional maximum number of words to snippet. + * @param highlightPreTag The HTML string to insert before the highlighted parts in all highlight and snippet results. + * @param highlightPostTag The HTML string to insert after the highlighted parts in all highlight and snippet results. + * @param snippetEllipsisText String used as an ellipsis indicator when a snippet is truncated. + * @param restrictHighlightAndSnippetArrays Restrict highlighting and snippeting to items that matched the query. + * @param hitsPerPage Set the number of hits per page. + * @param minWordSizefor1Typo Minimum number of characters a word in the query string must contain to accept matches with 1 typo. + * @param minWordSizefor2Typos Minimum number of characters a word in the query string must contain to accept matches with 2 typos. + * @param typoTolerance + * @param allowTyposOnNumericTokens Whether to allow typos on numbers (\"numeric tokens\") in the query string. + * @param disableTypoToleranceOnAttributes List of attributes on which you want to disable typo tolerance. + * @param ignorePlurals + * @param removeStopWords + * @param keepDiacriticsOnCharacters List of characters that the engine shouldn't automatically normalize. + * @param queryLanguages Sets the languages to be used by language-specific settings and functionalities such as ignorePlurals, removeStopWords, and CJK word-detection. + * @param decompoundQuery Splits compound words into their composing atoms in the query. + * @param enableRules Whether Rules should be globally enabled. + * @param enablePersonalization Enable the Personalization feature. + * @param queryType + * @param removeWordsIfNoResults + * @param mode + * @param semanticSearch + * @param advancedSyntax Enables the advanced query syntax. + * @param optionalWords A list of words that should be considered as optional when found in the query. + * @param disableExactOnAttributes List of attributes on which you want to disable the exact ranking criterion. + * @param exactOnSingleWordQuery + * @param alternativesAsExact List of alternatives that should be considered an exact match by the exact ranking criterion. + * @param advancedSyntaxFeatures Allows you to specify which advanced syntax features are active when ‘advancedSyntax' is enabled. + * @param explain Enriches the API’s response with meta-information as to how the query was processed. + * @param distinct + * @param attributeForDistinct Name of the de-duplication attribute to be used with the distinct feature. + * @param synonyms Whether to take into account an index's synonyms for a particular search. + * @param replaceSynonymsInHighlight Whether to highlight and snippet the original word that matches the synonym or the synonym itself. + * @param minProximity Precision of the proximity ranking criterion. + * @param responseFields Choose which fields to return in the API response. This parameters applies to search and browse queries. + * @param maxFacetHits Maximum number of facet hits to return during a search for facet values. For performance reasons, the maximum allowed number of returned values is 100. + * @param attributeCriteriaComputedByMinProximity When attribute is ranked above proximity in your ranking formula, proximity is used to select which searchable attribute is matched in the attribute ranking stage. + * @param renderingContent + * @param facetQuery Text to search inside the facet's values. + */ +@Serializable +public data class SearchForFacets( + + /** The `facet` name. */ + @SerialName(value = "facet") val facet: String, + + /** The Algolia index name. */ + @SerialName(value = "indexName") val indexName: String, + + @SerialName(value = "type") val type: SearchTypeFacet, + + /** Search parameters as URL-encoded query string. */ + @SerialName(value = "params") val params: String? = null, + + /** The text to search in the index. */ + @SerialName(value = "query") val query: String? = null, + + /** Overrides the query parameter and performs a more generic search that can be used to find \"similar\" results. */ + @SerialName(value = "similarQuery") val similarQuery: String? = null, + + /** Filter the query with numeric, facet and/or tag filters. */ + @SerialName(value = "filters") val filters: String? = null, + + @SerialName(value = "facetFilters") val facetFilters: FacetFilters? = null, + + @SerialName(value = "optionalFilters") val optionalFilters: OptionalFilters? = null, + + @SerialName(value = "numericFilters") val numericFilters: NumericFilters? = null, + + @SerialName(value = "tagFilters") val tagFilters: TagFilters? = null, + + /** Determines how to calculate the total score for filtering. */ + @SerialName(value = "sumOrFiltersScores") val sumOrFiltersScores: Boolean? = null, + + /** Retrieve facets and their facet values. */ + @SerialName(value = "facets") val facets: List? = null, + + /** Maximum number of facet values to return for each facet during a regular search. */ + @SerialName(value = "maxValuesPerFacet") val maxValuesPerFacet: Int? = null, + + /** Force faceting to be applied after de-duplication (via the Distinct setting). */ + @SerialName(value = "facetingAfterDistinct") val facetingAfterDistinct: Boolean? = null, + + /** Controls how facet values are fetched. */ + @SerialName(value = "sortFacetValuesBy") val sortFacetValuesBy: String? = null, + + /** Specify the page to retrieve. */ + @SerialName(value = "page") val page: Int? = null, + + /** Specify the offset of the first hit to return. */ + @SerialName(value = "offset") val offset: Int? = null, + + /** Set the number of hits to retrieve (used only with offset). */ + @SerialName(value = "length") val length: Int? = null, + + /** Search for entries around a central geolocation, enabling a geo search within a circular area. */ + @SerialName(value = "aroundLatLng") val aroundLatLng: String? = null, + + /** Search for entries around a given location automatically computed from the requester's IP address. */ + @SerialName(value = "aroundLatLngViaIP") val aroundLatLngViaIP: Boolean? = null, + + @SerialName(value = "aroundRadius") val aroundRadius: AroundRadius? = null, + + /** Precision of geo search (in meters), to add grouping by geo location to the ranking formula. */ + @SerialName(value = "aroundPrecision") val aroundPrecision: Int? = null, + + /** Minimum radius (in meters) used for a geo search when aroundRadius is not set. */ + @SerialName(value = "minimumAroundRadius") val minimumAroundRadius: Int? = null, + + /** Search inside a rectangular area (in geo coordinates). */ + @SerialName(value = "insideBoundingBox") val insideBoundingBox: List? = null, + + /** Search inside a polygon (in geo coordinates). */ + @SerialName(value = "insidePolygon") val insidePolygon: List? = null, + + /** This parameter changes the default values of certain parameters and settings that work best for a natural language query, such as ignorePlurals, removeStopWords, removeWordsIfNoResults, analyticsTags and ruleContexts. These parameters and settings work well together when the query is formatted in natural language instead of keywords, for example when your user performs a voice search. */ + @SerialName(value = "naturalLanguages") val naturalLanguages: List? = null, + + /** Enables contextual rules. */ + @SerialName(value = "ruleContexts") val ruleContexts: List? = null, + + /** Define the impact of the Personalization feature. */ + @SerialName(value = "personalizationImpact") val personalizationImpact: Int? = null, + + /** Associates a certain user token with the current search. */ + @SerialName(value = "userToken") val userToken: String? = null, + + /** Retrieve detailed ranking information. */ + @SerialName(value = "getRankingInfo") val getRankingInfo: Boolean? = null, + + /** Enable the Click Analytics feature. */ + @SerialName(value = "clickAnalytics") val clickAnalytics: Boolean? = null, + + /** Whether the current query will be taken into account in the Analytics. */ + @SerialName(value = "analytics") val analytics: Boolean? = null, + + /** List of tags to apply to the query for analytics purposes. */ + @SerialName(value = "analyticsTags") val analyticsTags: List? = null, + + /** Whether to include or exclude a query from the processing-time percentile computation. */ + @SerialName(value = "percentileComputation") val percentileComputation: Boolean? = null, + + /** Whether this search should participate in running AB tests. */ + @SerialName(value = "enableABTest") val enableABTest: Boolean? = null, + + /** Whether this search should use AI Re-Ranking. */ + @SerialName(value = "enableReRanking") val enableReRanking: Boolean? = null, + + @SerialName(value = "reRankingApplyFilter") val reRankingApplyFilter: ReRankingApplyFilter? = null, + + /** The complete list of attributes that will be used for faceting. */ + @SerialName(value = "attributesForFaceting") val attributesForFaceting: List? = null, + + /** This parameter controls which attributes to retrieve and which not to retrieve. */ + @SerialName(value = "attributesToRetrieve") val attributesToRetrieve: List? = null, + + /** Restricts a given query to look in only a subset of your searchable attributes. */ + @SerialName(value = "restrictSearchableAttributes") val restrictSearchableAttributes: List? = null, + + /** Controls how Algolia should sort your results. */ + @SerialName(value = "ranking") val ranking: List? = null, + + /** Specifies the custom ranking criterion. */ + @SerialName(value = "customRanking") val customRanking: List? = null, + + /** Controls the relevancy threshold below which less relevant results aren't included in the results. */ + @SerialName(value = "relevancyStrictness") val relevancyStrictness: Int? = null, + + /** List of attributes to highlight. */ + @SerialName(value = "attributesToHighlight") val attributesToHighlight: List? = null, + + /** List of attributes to snippet, with an optional maximum number of words to snippet. */ + @SerialName(value = "attributesToSnippet") val attributesToSnippet: List? = null, + + /** The HTML string to insert before the highlighted parts in all highlight and snippet results. */ + @SerialName(value = "highlightPreTag") val highlightPreTag: String? = null, + + /** The HTML string to insert after the highlighted parts in all highlight and snippet results. */ + @SerialName(value = "highlightPostTag") val highlightPostTag: String? = null, + + /** String used as an ellipsis indicator when a snippet is truncated. */ + @SerialName(value = "snippetEllipsisText") val snippetEllipsisText: String? = null, + + /** Restrict highlighting and snippeting to items that matched the query. */ + @SerialName(value = "restrictHighlightAndSnippetArrays") val restrictHighlightAndSnippetArrays: Boolean? = null, + + /** Set the number of hits per page. */ + @SerialName(value = "hitsPerPage") val hitsPerPage: Int? = null, + + /** Minimum number of characters a word in the query string must contain to accept matches with 1 typo. */ + @SerialName(value = "minWordSizefor1Typo") val minWordSizefor1Typo: Int? = null, + + /** Minimum number of characters a word in the query string must contain to accept matches with 2 typos. */ + @SerialName(value = "minWordSizefor2Typos") val minWordSizefor2Typos: Int? = null, + + @SerialName(value = "typoTolerance") val typoTolerance: TypoTolerance? = null, + + /** Whether to allow typos on numbers (\"numeric tokens\") in the query string. */ + @SerialName(value = "allowTyposOnNumericTokens") val allowTyposOnNumericTokens: Boolean? = null, + + /** List of attributes on which you want to disable typo tolerance. */ + @SerialName(value = "disableTypoToleranceOnAttributes") val disableTypoToleranceOnAttributes: List? = null, + + @SerialName(value = "ignorePlurals") val ignorePlurals: IgnorePlurals? = null, + + @SerialName(value = "removeStopWords") val removeStopWords: RemoveStopWords? = null, + + /** List of characters that the engine shouldn't automatically normalize. */ + @SerialName(value = "keepDiacriticsOnCharacters") val keepDiacriticsOnCharacters: String? = null, + + /** Sets the languages to be used by language-specific settings and functionalities such as ignorePlurals, removeStopWords, and CJK word-detection. */ + @SerialName(value = "queryLanguages") val queryLanguages: List? = null, + + /** Splits compound words into their composing atoms in the query. */ + @SerialName(value = "decompoundQuery") val decompoundQuery: Boolean? = null, + + /** Whether Rules should be globally enabled. */ + @SerialName(value = "enableRules") val enableRules: Boolean? = null, + + /** Enable the Personalization feature. */ + @SerialName(value = "enablePersonalization") val enablePersonalization: Boolean? = null, + + @SerialName(value = "queryType") val queryType: QueryType? = null, + + @SerialName(value = "removeWordsIfNoResults") val removeWordsIfNoResults: RemoveWordsIfNoResults? = null, + + @SerialName(value = "mode") val mode: Mode? = null, + + @SerialName(value = "semanticSearch") val semanticSearch: IndexSettingsAsSearchParamsSemanticSearch? = null, + + /** Enables the advanced query syntax. */ + @SerialName(value = "advancedSyntax") val advancedSyntax: Boolean? = null, + + /** A list of words that should be considered as optional when found in the query. */ + @SerialName(value = "optionalWords") val optionalWords: List? = null, + + /** List of attributes on which you want to disable the exact ranking criterion. */ + @SerialName(value = "disableExactOnAttributes") val disableExactOnAttributes: List? = null, + + @SerialName(value = "exactOnSingleWordQuery") val exactOnSingleWordQuery: ExactOnSingleWordQuery? = null, + + /** List of alternatives that should be considered an exact match by the exact ranking criterion. */ + @SerialName(value = "alternativesAsExact") val alternativesAsExact: List? = null, + + /** Allows you to specify which advanced syntax features are active when ‘advancedSyntax' is enabled. */ + @SerialName(value = "advancedSyntaxFeatures") val advancedSyntaxFeatures: List? = null, + + /** Enriches the API’s response with meta-information as to how the query was processed. */ + @SerialName(value = "explain") val explain: List? = null, + + @SerialName(value = "distinct") val distinct: Distinct? = null, + + /** Name of the de-duplication attribute to be used with the distinct feature. */ + @SerialName(value = "attributeForDistinct") val attributeForDistinct: String? = null, + + /** Whether to take into account an index's synonyms for a particular search. */ + @SerialName(value = "synonyms") val synonyms: Boolean? = null, + + /** Whether to highlight and snippet the original word that matches the synonym or the synonym itself. */ + @SerialName(value = "replaceSynonymsInHighlight") val replaceSynonymsInHighlight: Boolean? = null, + + /** Precision of the proximity ranking criterion. */ + @SerialName(value = "minProximity") val minProximity: Int? = null, + + /** Choose which fields to return in the API response. This parameters applies to search and browse queries. */ + @SerialName(value = "responseFields") val responseFields: List? = null, + + /** Maximum number of facet hits to return during a search for facet values. For performance reasons, the maximum allowed number of returned values is 100. */ + @SerialName(value = "maxFacetHits") val maxFacetHits: Int? = null, + + /** When attribute is ranked above proximity in your ranking formula, proximity is used to select which searchable attribute is matched in the attribute ranking stage. */ + @SerialName(value = "attributeCriteriaComputedByMinProximity") val attributeCriteriaComputedByMinProximity: Boolean? = null, + + @SerialName(value = "renderingContent") val renderingContent: RenderingContent? = null, + + /** Text to search inside the facet's values. */ + @SerialName(value = "facetQuery") val facetQuery: String? = null, +) : SearchQuery diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchForFacetsOptions.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchForFacetsOptions.kt new file mode 100644 index 0000000000..3671e61992 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchForFacetsOptions.kt @@ -0,0 +1,32 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SearchForFacetsOptions + * + * @param facet The `facet` name. + * @param indexName The Algolia index name. + * @param type + * @param facetQuery Text to search inside the facet's values. + * @param maxFacetHits Maximum number of facet hits to return during a search for facet values. For performance reasons, the maximum allowed number of returned values is 100. + */ +@Serializable +public data class SearchForFacetsOptions( + + /** The `facet` name. */ + @SerialName(value = "facet") val facet: String, + + /** The Algolia index name. */ + @SerialName(value = "indexName") val indexName: String, + + @SerialName(value = "type") val type: SearchTypeFacet, + + /** Text to search inside the facet's values. */ + @SerialName(value = "facetQuery") val facetQuery: String? = null, + + /** Maximum number of facet hits to return during a search for facet values. For performance reasons, the maximum allowed number of returned values is 100. */ + @SerialName(value = "maxFacetHits") val maxFacetHits: Int? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchForHits.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchForHits.kt new file mode 100644 index 0000000000..a4ba884d13 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchForHits.kt @@ -0,0 +1,324 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SearchForHits + * + * @param indexName The Algolia index name. + * @param params Search parameters as URL-encoded query string. + * @param query The text to search in the index. + * @param similarQuery Overrides the query parameter and performs a more generic search that can be used to find \"similar\" results. + * @param filters Filter the query with numeric, facet and/or tag filters. + * @param facetFilters + * @param optionalFilters + * @param numericFilters + * @param tagFilters + * @param sumOrFiltersScores Determines how to calculate the total score for filtering. + * @param facets Retrieve facets and their facet values. + * @param maxValuesPerFacet Maximum number of facet values to return for each facet during a regular search. + * @param facetingAfterDistinct Force faceting to be applied after de-duplication (via the Distinct setting). + * @param sortFacetValuesBy Controls how facet values are fetched. + * @param page Specify the page to retrieve. + * @param offset Specify the offset of the first hit to return. + * @param length Set the number of hits to retrieve (used only with offset). + * @param aroundLatLng Search for entries around a central geolocation, enabling a geo search within a circular area. + * @param aroundLatLngViaIP Search for entries around a given location automatically computed from the requester's IP address. + * @param aroundRadius + * @param aroundPrecision Precision of geo search (in meters), to add grouping by geo location to the ranking formula. + * @param minimumAroundRadius Minimum radius (in meters) used for a geo search when aroundRadius is not set. + * @param insideBoundingBox Search inside a rectangular area (in geo coordinates). + * @param insidePolygon Search inside a polygon (in geo coordinates). + * @param naturalLanguages This parameter changes the default values of certain parameters and settings that work best for a natural language query, such as ignorePlurals, removeStopWords, removeWordsIfNoResults, analyticsTags and ruleContexts. These parameters and settings work well together when the query is formatted in natural language instead of keywords, for example when your user performs a voice search. + * @param ruleContexts Enables contextual rules. + * @param personalizationImpact Define the impact of the Personalization feature. + * @param userToken Associates a certain user token with the current search. + * @param getRankingInfo Retrieve detailed ranking information. + * @param clickAnalytics Enable the Click Analytics feature. + * @param analytics Whether the current query will be taken into account in the Analytics. + * @param analyticsTags List of tags to apply to the query for analytics purposes. + * @param percentileComputation Whether to include or exclude a query from the processing-time percentile computation. + * @param enableABTest Whether this search should participate in running AB tests. + * @param enableReRanking Whether this search should use AI Re-Ranking. + * @param reRankingApplyFilter + * @param attributesForFaceting The complete list of attributes that will be used for faceting. + * @param attributesToRetrieve This parameter controls which attributes to retrieve and which not to retrieve. + * @param restrictSearchableAttributes Restricts a given query to look in only a subset of your searchable attributes. + * @param ranking Controls how Algolia should sort your results. + * @param customRanking Specifies the custom ranking criterion. + * @param relevancyStrictness Controls the relevancy threshold below which less relevant results aren't included in the results. + * @param attributesToHighlight List of attributes to highlight. + * @param attributesToSnippet List of attributes to snippet, with an optional maximum number of words to snippet. + * @param highlightPreTag The HTML string to insert before the highlighted parts in all highlight and snippet results. + * @param highlightPostTag The HTML string to insert after the highlighted parts in all highlight and snippet results. + * @param snippetEllipsisText String used as an ellipsis indicator when a snippet is truncated. + * @param restrictHighlightAndSnippetArrays Restrict highlighting and snippeting to items that matched the query. + * @param hitsPerPage Set the number of hits per page. + * @param minWordSizefor1Typo Minimum number of characters a word in the query string must contain to accept matches with 1 typo. + * @param minWordSizefor2Typos Minimum number of characters a word in the query string must contain to accept matches with 2 typos. + * @param typoTolerance + * @param allowTyposOnNumericTokens Whether to allow typos on numbers (\"numeric tokens\") in the query string. + * @param disableTypoToleranceOnAttributes List of attributes on which you want to disable typo tolerance. + * @param ignorePlurals + * @param removeStopWords + * @param keepDiacriticsOnCharacters List of characters that the engine shouldn't automatically normalize. + * @param queryLanguages Sets the languages to be used by language-specific settings and functionalities such as ignorePlurals, removeStopWords, and CJK word-detection. + * @param decompoundQuery Splits compound words into their composing atoms in the query. + * @param enableRules Whether Rules should be globally enabled. + * @param enablePersonalization Enable the Personalization feature. + * @param queryType + * @param removeWordsIfNoResults + * @param mode + * @param semanticSearch + * @param advancedSyntax Enables the advanced query syntax. + * @param optionalWords A list of words that should be considered as optional when found in the query. + * @param disableExactOnAttributes List of attributes on which you want to disable the exact ranking criterion. + * @param exactOnSingleWordQuery + * @param alternativesAsExact List of alternatives that should be considered an exact match by the exact ranking criterion. + * @param advancedSyntaxFeatures Allows you to specify which advanced syntax features are active when ‘advancedSyntax' is enabled. + * @param explain Enriches the API’s response with meta-information as to how the query was processed. + * @param distinct + * @param attributeForDistinct Name of the de-duplication attribute to be used with the distinct feature. + * @param synonyms Whether to take into account an index's synonyms for a particular search. + * @param replaceSynonymsInHighlight Whether to highlight and snippet the original word that matches the synonym or the synonym itself. + * @param minProximity Precision of the proximity ranking criterion. + * @param responseFields Choose which fields to return in the API response. This parameters applies to search and browse queries. + * @param maxFacetHits Maximum number of facet hits to return during a search for facet values. For performance reasons, the maximum allowed number of returned values is 100. + * @param attributeCriteriaComputedByMinProximity When attribute is ranked above proximity in your ranking formula, proximity is used to select which searchable attribute is matched in the attribute ranking stage. + * @param renderingContent + * @param type + */ +@Serializable +public data class SearchForHits( + + /** The Algolia index name. */ + @SerialName(value = "indexName") val indexName: String, + + /** Search parameters as URL-encoded query string. */ + @SerialName(value = "params") val params: String? = null, + + /** The text to search in the index. */ + @SerialName(value = "query") val query: String? = null, + + /** Overrides the query parameter and performs a more generic search that can be used to find \"similar\" results. */ + @SerialName(value = "similarQuery") val similarQuery: String? = null, + + /** Filter the query with numeric, facet and/or tag filters. */ + @SerialName(value = "filters") val filters: String? = null, + + @SerialName(value = "facetFilters") val facetFilters: FacetFilters? = null, + + @SerialName(value = "optionalFilters") val optionalFilters: OptionalFilters? = null, + + @SerialName(value = "numericFilters") val numericFilters: NumericFilters? = null, + + @SerialName(value = "tagFilters") val tagFilters: TagFilters? = null, + + /** Determines how to calculate the total score for filtering. */ + @SerialName(value = "sumOrFiltersScores") val sumOrFiltersScores: Boolean? = null, + + /** Retrieve facets and their facet values. */ + @SerialName(value = "facets") val facets: List? = null, + + /** Maximum number of facet values to return for each facet during a regular search. */ + @SerialName(value = "maxValuesPerFacet") val maxValuesPerFacet: Int? = null, + + /** Force faceting to be applied after de-duplication (via the Distinct setting). */ + @SerialName(value = "facetingAfterDistinct") val facetingAfterDistinct: Boolean? = null, + + /** Controls how facet values are fetched. */ + @SerialName(value = "sortFacetValuesBy") val sortFacetValuesBy: String? = null, + + /** Specify the page to retrieve. */ + @SerialName(value = "page") val page: Int? = null, + + /** Specify the offset of the first hit to return. */ + @SerialName(value = "offset") val offset: Int? = null, + + /** Set the number of hits to retrieve (used only with offset). */ + @SerialName(value = "length") val length: Int? = null, + + /** Search for entries around a central geolocation, enabling a geo search within a circular area. */ + @SerialName(value = "aroundLatLng") val aroundLatLng: String? = null, + + /** Search for entries around a given location automatically computed from the requester's IP address. */ + @SerialName(value = "aroundLatLngViaIP") val aroundLatLngViaIP: Boolean? = null, + + @SerialName(value = "aroundRadius") val aroundRadius: AroundRadius? = null, + + /** Precision of geo search (in meters), to add grouping by geo location to the ranking formula. */ + @SerialName(value = "aroundPrecision") val aroundPrecision: Int? = null, + + /** Minimum radius (in meters) used for a geo search when aroundRadius is not set. */ + @SerialName(value = "minimumAroundRadius") val minimumAroundRadius: Int? = null, + + /** Search inside a rectangular area (in geo coordinates). */ + @SerialName(value = "insideBoundingBox") val insideBoundingBox: List? = null, + + /** Search inside a polygon (in geo coordinates). */ + @SerialName(value = "insidePolygon") val insidePolygon: List? = null, + + /** This parameter changes the default values of certain parameters and settings that work best for a natural language query, such as ignorePlurals, removeStopWords, removeWordsIfNoResults, analyticsTags and ruleContexts. These parameters and settings work well together when the query is formatted in natural language instead of keywords, for example when your user performs a voice search. */ + @SerialName(value = "naturalLanguages") val naturalLanguages: List? = null, + + /** Enables contextual rules. */ + @SerialName(value = "ruleContexts") val ruleContexts: List? = null, + + /** Define the impact of the Personalization feature. */ + @SerialName(value = "personalizationImpact") val personalizationImpact: Int? = null, + + /** Associates a certain user token with the current search. */ + @SerialName(value = "userToken") val userToken: String? = null, + + /** Retrieve detailed ranking information. */ + @SerialName(value = "getRankingInfo") val getRankingInfo: Boolean? = null, + + /** Enable the Click Analytics feature. */ + @SerialName(value = "clickAnalytics") val clickAnalytics: Boolean? = null, + + /** Whether the current query will be taken into account in the Analytics. */ + @SerialName(value = "analytics") val analytics: Boolean? = null, + + /** List of tags to apply to the query for analytics purposes. */ + @SerialName(value = "analyticsTags") val analyticsTags: List? = null, + + /** Whether to include or exclude a query from the processing-time percentile computation. */ + @SerialName(value = "percentileComputation") val percentileComputation: Boolean? = null, + + /** Whether this search should participate in running AB tests. */ + @SerialName(value = "enableABTest") val enableABTest: Boolean? = null, + + /** Whether this search should use AI Re-Ranking. */ + @SerialName(value = "enableReRanking") val enableReRanking: Boolean? = null, + + @SerialName(value = "reRankingApplyFilter") val reRankingApplyFilter: ReRankingApplyFilter? = null, + + /** The complete list of attributes that will be used for faceting. */ + @SerialName(value = "attributesForFaceting") val attributesForFaceting: List? = null, + + /** This parameter controls which attributes to retrieve and which not to retrieve. */ + @SerialName(value = "attributesToRetrieve") val attributesToRetrieve: List? = null, + + /** Restricts a given query to look in only a subset of your searchable attributes. */ + @SerialName(value = "restrictSearchableAttributes") val restrictSearchableAttributes: List? = null, + + /** Controls how Algolia should sort your results. */ + @SerialName(value = "ranking") val ranking: List? = null, + + /** Specifies the custom ranking criterion. */ + @SerialName(value = "customRanking") val customRanking: List? = null, + + /** Controls the relevancy threshold below which less relevant results aren't included in the results. */ + @SerialName(value = "relevancyStrictness") val relevancyStrictness: Int? = null, + + /** List of attributes to highlight. */ + @SerialName(value = "attributesToHighlight") val attributesToHighlight: List? = null, + + /** List of attributes to snippet, with an optional maximum number of words to snippet. */ + @SerialName(value = "attributesToSnippet") val attributesToSnippet: List? = null, + + /** The HTML string to insert before the highlighted parts in all highlight and snippet results. */ + @SerialName(value = "highlightPreTag") val highlightPreTag: String? = null, + + /** The HTML string to insert after the highlighted parts in all highlight and snippet results. */ + @SerialName(value = "highlightPostTag") val highlightPostTag: String? = null, + + /** String used as an ellipsis indicator when a snippet is truncated. */ + @SerialName(value = "snippetEllipsisText") val snippetEllipsisText: String? = null, + + /** Restrict highlighting and snippeting to items that matched the query. */ + @SerialName(value = "restrictHighlightAndSnippetArrays") val restrictHighlightAndSnippetArrays: Boolean? = null, + + /** Set the number of hits per page. */ + @SerialName(value = "hitsPerPage") val hitsPerPage: Int? = null, + + /** Minimum number of characters a word in the query string must contain to accept matches with 1 typo. */ + @SerialName(value = "minWordSizefor1Typo") val minWordSizefor1Typo: Int? = null, + + /** Minimum number of characters a word in the query string must contain to accept matches with 2 typos. */ + @SerialName(value = "minWordSizefor2Typos") val minWordSizefor2Typos: Int? = null, + + @SerialName(value = "typoTolerance") val typoTolerance: TypoTolerance? = null, + + /** Whether to allow typos on numbers (\"numeric tokens\") in the query string. */ + @SerialName(value = "allowTyposOnNumericTokens") val allowTyposOnNumericTokens: Boolean? = null, + + /** List of attributes on which you want to disable typo tolerance. */ + @SerialName(value = "disableTypoToleranceOnAttributes") val disableTypoToleranceOnAttributes: List? = null, + + @SerialName(value = "ignorePlurals") val ignorePlurals: IgnorePlurals? = null, + + @SerialName(value = "removeStopWords") val removeStopWords: RemoveStopWords? = null, + + /** List of characters that the engine shouldn't automatically normalize. */ + @SerialName(value = "keepDiacriticsOnCharacters") val keepDiacriticsOnCharacters: String? = null, + + /** Sets the languages to be used by language-specific settings and functionalities such as ignorePlurals, removeStopWords, and CJK word-detection. */ + @SerialName(value = "queryLanguages") val queryLanguages: List? = null, + + /** Splits compound words into their composing atoms in the query. */ + @SerialName(value = "decompoundQuery") val decompoundQuery: Boolean? = null, + + /** Whether Rules should be globally enabled. */ + @SerialName(value = "enableRules") val enableRules: Boolean? = null, + + /** Enable the Personalization feature. */ + @SerialName(value = "enablePersonalization") val enablePersonalization: Boolean? = null, + + @SerialName(value = "queryType") val queryType: QueryType? = null, + + @SerialName(value = "removeWordsIfNoResults") val removeWordsIfNoResults: RemoveWordsIfNoResults? = null, + + @SerialName(value = "mode") val mode: Mode? = null, + + @SerialName(value = "semanticSearch") val semanticSearch: IndexSettingsAsSearchParamsSemanticSearch? = null, + + /** Enables the advanced query syntax. */ + @SerialName(value = "advancedSyntax") val advancedSyntax: Boolean? = null, + + /** A list of words that should be considered as optional when found in the query. */ + @SerialName(value = "optionalWords") val optionalWords: List? = null, + + /** List of attributes on which you want to disable the exact ranking criterion. */ + @SerialName(value = "disableExactOnAttributes") val disableExactOnAttributes: List? = null, + + @SerialName(value = "exactOnSingleWordQuery") val exactOnSingleWordQuery: ExactOnSingleWordQuery? = null, + + /** List of alternatives that should be considered an exact match by the exact ranking criterion. */ + @SerialName(value = "alternativesAsExact") val alternativesAsExact: List? = null, + + /** Allows you to specify which advanced syntax features are active when ‘advancedSyntax' is enabled. */ + @SerialName(value = "advancedSyntaxFeatures") val advancedSyntaxFeatures: List? = null, + + /** Enriches the API’s response with meta-information as to how the query was processed. */ + @SerialName(value = "explain") val explain: List? = null, + + @SerialName(value = "distinct") val distinct: Distinct? = null, + + /** Name of the de-duplication attribute to be used with the distinct feature. */ + @SerialName(value = "attributeForDistinct") val attributeForDistinct: String? = null, + + /** Whether to take into account an index's synonyms for a particular search. */ + @SerialName(value = "synonyms") val synonyms: Boolean? = null, + + /** Whether to highlight and snippet the original word that matches the synonym or the synonym itself. */ + @SerialName(value = "replaceSynonymsInHighlight") val replaceSynonymsInHighlight: Boolean? = null, + + /** Precision of the proximity ranking criterion. */ + @SerialName(value = "minProximity") val minProximity: Int? = null, + + /** Choose which fields to return in the API response. This parameters applies to search and browse queries. */ + @SerialName(value = "responseFields") val responseFields: List? = null, + + /** Maximum number of facet hits to return during a search for facet values. For performance reasons, the maximum allowed number of returned values is 100. */ + @SerialName(value = "maxFacetHits") val maxFacetHits: Int? = null, + + /** When attribute is ranked above proximity in your ranking formula, proximity is used to select which searchable attribute is matched in the attribute ranking stage. */ + @SerialName(value = "attributeCriteriaComputedByMinProximity") val attributeCriteriaComputedByMinProximity: Boolean? = null, + + @SerialName(value = "renderingContent") val renderingContent: RenderingContent? = null, + + @SerialName(value = "type") val type: SearchTypeDefault? = null, +) : SearchQuery diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchForHitsOptions.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchForHitsOptions.kt new file mode 100644 index 0000000000..329838f341 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchForHitsOptions.kt @@ -0,0 +1,20 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SearchForHitsOptions + * + * @param indexName The Algolia index name. + * @param type + */ +@Serializable +public data class SearchForHitsOptions( + + /** The Algolia index name. */ + @SerialName(value = "indexName") val indexName: String, + + @SerialName(value = "type") val type: SearchTypeDefault? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchHits.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchHits.kt new file mode 100644 index 0000000000..a2d29e6cdb --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchHits.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SearchHits + * + * @param hits + */ +@Serializable +public data class SearchHits( + + @SerialName(value = "hits") val hits: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchMethodParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchMethodParams.kt new file mode 100644 index 0000000000..0ac5d30d69 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchMethodParams.kt @@ -0,0 +1,19 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SearchMethodParams + * + * @param requests + * @param strategy + */ +@Serializable +public data class SearchMethodParams( + + @SerialName(value = "requests") val requests: List, + + @SerialName(value = "strategy") val strategy: SearchStrategy? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchParams.kt new file mode 100644 index 0000000000..3c01729924 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchParams.kt @@ -0,0 +1,315 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * SearchParams + */ +@Serializable(SearchParamsSerializer::class) +public sealed interface SearchParams { + + public companion object { + + /** + * SearchParamsObject + * + * @param query The text to search in the index. + * @param similarQuery Overrides the query parameter and performs a more generic search that can be used to find \"similar\" results. + * @param filters Filter the query with numeric, facet and/or tag filters. + * @param facetFilters + * @param optionalFilters + * @param numericFilters + * @param tagFilters + * @param sumOrFiltersScores Determines how to calculate the total score for filtering. + * @param facets Retrieve facets and their facet values. + * @param maxValuesPerFacet Maximum number of facet values to return for each facet during a regular search. + * @param facetingAfterDistinct Force faceting to be applied after de-duplication (via the Distinct setting). + * @param sortFacetValuesBy Controls how facet values are fetched. + * @param page Specify the page to retrieve. + * @param offset Specify the offset of the first hit to return. + * @param length Set the number of hits to retrieve (used only with offset). + * @param aroundLatLng Search for entries around a central geolocation, enabling a geo search within a circular area. + * @param aroundLatLngViaIP Search for entries around a given location automatically computed from the requester's IP address. + * @param aroundRadius + * @param aroundPrecision Precision of geo search (in meters), to add grouping by geo location to the ranking formula. + * @param minimumAroundRadius Minimum radius (in meters) used for a geo search when aroundRadius is not set. + * @param insideBoundingBox Search inside a rectangular area (in geo coordinates). + * @param insidePolygon Search inside a polygon (in geo coordinates). + * @param naturalLanguages This parameter changes the default values of certain parameters and settings that work best for a natural language query, such as ignorePlurals, removeStopWords, removeWordsIfNoResults, analyticsTags and ruleContexts. These parameters and settings work well together when the query is formatted in natural language instead of keywords, for example when your user performs a voice search. + * @param ruleContexts Enables contextual rules. + * @param personalizationImpact Define the impact of the Personalization feature. + * @param userToken Associates a certain user token with the current search. + * @param getRankingInfo Retrieve detailed ranking information. + * @param clickAnalytics Enable the Click Analytics feature. + * @param analytics Whether the current query will be taken into account in the Analytics. + * @param analyticsTags List of tags to apply to the query for analytics purposes. + * @param percentileComputation Whether to include or exclude a query from the processing-time percentile computation. + * @param enableABTest Whether this search should participate in running AB tests. + * @param enableReRanking Whether this search should use AI Re-Ranking. + * @param reRankingApplyFilter + * @param attributesForFaceting The complete list of attributes that will be used for faceting. + * @param attributesToRetrieve This parameter controls which attributes to retrieve and which not to retrieve. + * @param restrictSearchableAttributes Restricts a given query to look in only a subset of your searchable attributes. + * @param ranking Controls how Algolia should sort your results. + * @param customRanking Specifies the custom ranking criterion. + * @param relevancyStrictness Controls the relevancy threshold below which less relevant results aren't included in the results. + * @param attributesToHighlight List of attributes to highlight. + * @param attributesToSnippet List of attributes to snippet, with an optional maximum number of words to snippet. + * @param highlightPreTag The HTML string to insert before the highlighted parts in all highlight and snippet results. + * @param highlightPostTag The HTML string to insert after the highlighted parts in all highlight and snippet results. + * @param snippetEllipsisText String used as an ellipsis indicator when a snippet is truncated. + * @param restrictHighlightAndSnippetArrays Restrict highlighting and snippeting to items that matched the query. + * @param hitsPerPage Set the number of hits per page. + * @param minWordSizefor1Typo Minimum number of characters a word in the query string must contain to accept matches with 1 typo. + * @param minWordSizefor2Typos Minimum number of characters a word in the query string must contain to accept matches with 2 typos. + * @param typoTolerance + * @param allowTyposOnNumericTokens Whether to allow typos on numbers (\"numeric tokens\") in the query string. + * @param disableTypoToleranceOnAttributes List of attributes on which you want to disable typo tolerance. + * @param ignorePlurals + * @param removeStopWords + * @param keepDiacriticsOnCharacters List of characters that the engine shouldn't automatically normalize. + * @param queryLanguages Sets the languages to be used by language-specific settings and functionalities such as ignorePlurals, removeStopWords, and CJK word-detection. + * @param decompoundQuery Splits compound words into their composing atoms in the query. + * @param enableRules Whether Rules should be globally enabled. + * @param enablePersonalization Enable the Personalization feature. + * @param queryType + * @param removeWordsIfNoResults + * @param mode + * @param semanticSearch + * @param advancedSyntax Enables the advanced query syntax. + * @param optionalWords A list of words that should be considered as optional when found in the query. + * @param disableExactOnAttributes List of attributes on which you want to disable the exact ranking criterion. + * @param exactOnSingleWordQuery + * @param alternativesAsExact List of alternatives that should be considered an exact match by the exact ranking criterion. + * @param advancedSyntaxFeatures Allows you to specify which advanced syntax features are active when ‘advancedSyntax' is enabled. + * @param explain Enriches the API’s response with meta-information as to how the query was processed. + * @param distinct + * @param attributeForDistinct Name of the de-duplication attribute to be used with the distinct feature. + * @param synonyms Whether to take into account an index's synonyms for a particular search. + * @param replaceSynonymsInHighlight Whether to highlight and snippet the original word that matches the synonym or the synonym itself. + * @param minProximity Precision of the proximity ranking criterion. + * @param responseFields Choose which fields to return in the API response. This parameters applies to search and browse queries. + * @param maxFacetHits Maximum number of facet hits to return during a search for facet values. For performance reasons, the maximum allowed number of returned values is 100. + * @param attributeCriteriaComputedByMinProximity When attribute is ranked above proximity in your ranking formula, proximity is used to select which searchable attribute is matched in the attribute ranking stage. + * @param renderingContent + */ + public fun SearchParamsObject( + query: String? = null, + similarQuery: String? = null, + filters: String? = null, + facetFilters: FacetFilters? = null, + optionalFilters: OptionalFilters? = null, + numericFilters: NumericFilters? = null, + tagFilters: TagFilters? = null, + sumOrFiltersScores: Boolean? = null, + facets: List? = null, + maxValuesPerFacet: Int? = null, + facetingAfterDistinct: Boolean? = null, + sortFacetValuesBy: String? = null, + page: Int? = null, + offset: Int? = null, + length: Int? = null, + aroundLatLng: String? = null, + aroundLatLngViaIP: Boolean? = null, + aroundRadius: AroundRadius? = null, + aroundPrecision: Int? = null, + minimumAroundRadius: Int? = null, + insideBoundingBox: List? = null, + insidePolygon: List? = null, + naturalLanguages: List? = null, + ruleContexts: List? = null, + personalizationImpact: Int? = null, + userToken: String? = null, + getRankingInfo: Boolean? = null, + clickAnalytics: Boolean? = null, + analytics: Boolean? = null, + analyticsTags: List? = null, + percentileComputation: Boolean? = null, + enableABTest: Boolean? = null, + enableReRanking: Boolean? = null, + reRankingApplyFilter: ReRankingApplyFilter? = null, + attributesForFaceting: List? = null, + attributesToRetrieve: List? = null, + restrictSearchableAttributes: List? = null, + ranking: List? = null, + customRanking: List? = null, + relevancyStrictness: Int? = null, + attributesToHighlight: List? = null, + attributesToSnippet: List? = null, + highlightPreTag: String? = null, + highlightPostTag: String? = null, + snippetEllipsisText: String? = null, + restrictHighlightAndSnippetArrays: Boolean? = null, + hitsPerPage: Int? = null, + minWordSizefor1Typo: Int? = null, + minWordSizefor2Typos: Int? = null, + typoTolerance: TypoTolerance? = null, + allowTyposOnNumericTokens: Boolean? = null, + disableTypoToleranceOnAttributes: List? = null, + ignorePlurals: IgnorePlurals? = null, + removeStopWords: RemoveStopWords? = null, + keepDiacriticsOnCharacters: String? = null, + queryLanguages: List? = null, + decompoundQuery: Boolean? = null, + enableRules: Boolean? = null, + enablePersonalization: Boolean? = null, + queryType: QueryType? = null, + removeWordsIfNoResults: RemoveWordsIfNoResults? = null, + mode: Mode? = null, + semanticSearch: IndexSettingsAsSearchParamsSemanticSearch? = null, + advancedSyntax: Boolean? = null, + optionalWords: List? = null, + disableExactOnAttributes: List? = null, + exactOnSingleWordQuery: ExactOnSingleWordQuery? = null, + alternativesAsExact: List? = null, + advancedSyntaxFeatures: List? = null, + explain: List? = null, + distinct: Distinct? = null, + attributeForDistinct: String? = null, + synonyms: Boolean? = null, + replaceSynonymsInHighlight: Boolean? = null, + minProximity: Int? = null, + responseFields: List? = null, + maxFacetHits: Int? = null, + attributeCriteriaComputedByMinProximity: Boolean? = null, + renderingContent: RenderingContent? = null, + ): SearchParamsObject = com.algolia.client.model.search.SearchParamsObject( + query = query, + similarQuery = similarQuery, + filters = filters, + facetFilters = facetFilters, + optionalFilters = optionalFilters, + numericFilters = numericFilters, + tagFilters = tagFilters, + sumOrFiltersScores = sumOrFiltersScores, + facets = facets, + maxValuesPerFacet = maxValuesPerFacet, + facetingAfterDistinct = facetingAfterDistinct, + sortFacetValuesBy = sortFacetValuesBy, + page = page, + offset = offset, + length = length, + aroundLatLng = aroundLatLng, + aroundLatLngViaIP = aroundLatLngViaIP, + aroundRadius = aroundRadius, + aroundPrecision = aroundPrecision, + minimumAroundRadius = minimumAroundRadius, + insideBoundingBox = insideBoundingBox, + insidePolygon = insidePolygon, + naturalLanguages = naturalLanguages, + ruleContexts = ruleContexts, + personalizationImpact = personalizationImpact, + userToken = userToken, + getRankingInfo = getRankingInfo, + clickAnalytics = clickAnalytics, + analytics = analytics, + analyticsTags = analyticsTags, + percentileComputation = percentileComputation, + enableABTest = enableABTest, + enableReRanking = enableReRanking, + reRankingApplyFilter = reRankingApplyFilter, + attributesForFaceting = attributesForFaceting, + attributesToRetrieve = attributesToRetrieve, + restrictSearchableAttributes = restrictSearchableAttributes, + ranking = ranking, + customRanking = customRanking, + relevancyStrictness = relevancyStrictness, + attributesToHighlight = attributesToHighlight, + attributesToSnippet = attributesToSnippet, + highlightPreTag = highlightPreTag, + highlightPostTag = highlightPostTag, + snippetEllipsisText = snippetEllipsisText, + restrictHighlightAndSnippetArrays = restrictHighlightAndSnippetArrays, + hitsPerPage = hitsPerPage, + minWordSizefor1Typo = minWordSizefor1Typo, + minWordSizefor2Typos = minWordSizefor2Typos, + typoTolerance = typoTolerance, + allowTyposOnNumericTokens = allowTyposOnNumericTokens, + disableTypoToleranceOnAttributes = disableTypoToleranceOnAttributes, + ignorePlurals = ignorePlurals, + removeStopWords = removeStopWords, + keepDiacriticsOnCharacters = keepDiacriticsOnCharacters, + queryLanguages = queryLanguages, + decompoundQuery = decompoundQuery, + enableRules = enableRules, + enablePersonalization = enablePersonalization, + queryType = queryType, + removeWordsIfNoResults = removeWordsIfNoResults, + mode = mode, + semanticSearch = semanticSearch, + advancedSyntax = advancedSyntax, + optionalWords = optionalWords, + disableExactOnAttributes = disableExactOnAttributes, + exactOnSingleWordQuery = exactOnSingleWordQuery, + alternativesAsExact = alternativesAsExact, + advancedSyntaxFeatures = advancedSyntaxFeatures, + explain = explain, + distinct = distinct, + attributeForDistinct = attributeForDistinct, + synonyms = synonyms, + replaceSynonymsInHighlight = replaceSynonymsInHighlight, + minProximity = minProximity, + responseFields = responseFields, + maxFacetHits = maxFacetHits, + attributeCriteriaComputedByMinProximity = attributeCriteriaComputedByMinProximity, + renderingContent = renderingContent, + ) + + /** + * SearchParamsString + * + * @param params Search parameters as URL-encoded query string. + */ + public fun SearchParamsString( + params: String? = null, + ): SearchParamsString = com.algolia.client.model.search.SearchParamsString( + params = params, + ) + } +} + +internal class SearchParamsSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("SearchParams") + + override fun serialize(encoder: Encoder, value: SearchParams) { + when (value) { + is SearchParamsObject -> SearchParamsObject.serializer().serialize(encoder, value) + is SearchParamsString -> SearchParamsString.serializer().serialize(encoder, value) + } + } + + override fun deserialize(decoder: Decoder): SearchParams { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize SearchParamsObject + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize SearchParamsObject (error: ${e.message})") + } + } + + // deserialize SearchParamsString + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize SearchParamsString (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchParamsObject.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchParamsObject.kt new file mode 100644 index 0000000000..26bdee6b03 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchParamsObject.kt @@ -0,0 +1,313 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SearchParamsObject + * + * @param query The text to search in the index. + * @param similarQuery Overrides the query parameter and performs a more generic search that can be used to find \"similar\" results. + * @param filters Filter the query with numeric, facet and/or tag filters. + * @param facetFilters + * @param optionalFilters + * @param numericFilters + * @param tagFilters + * @param sumOrFiltersScores Determines how to calculate the total score for filtering. + * @param facets Retrieve facets and their facet values. + * @param maxValuesPerFacet Maximum number of facet values to return for each facet during a regular search. + * @param facetingAfterDistinct Force faceting to be applied after de-duplication (via the Distinct setting). + * @param sortFacetValuesBy Controls how facet values are fetched. + * @param page Specify the page to retrieve. + * @param offset Specify the offset of the first hit to return. + * @param length Set the number of hits to retrieve (used only with offset). + * @param aroundLatLng Search for entries around a central geolocation, enabling a geo search within a circular area. + * @param aroundLatLngViaIP Search for entries around a given location automatically computed from the requester's IP address. + * @param aroundRadius + * @param aroundPrecision Precision of geo search (in meters), to add grouping by geo location to the ranking formula. + * @param minimumAroundRadius Minimum radius (in meters) used for a geo search when aroundRadius is not set. + * @param insideBoundingBox Search inside a rectangular area (in geo coordinates). + * @param insidePolygon Search inside a polygon (in geo coordinates). + * @param naturalLanguages This parameter changes the default values of certain parameters and settings that work best for a natural language query, such as ignorePlurals, removeStopWords, removeWordsIfNoResults, analyticsTags and ruleContexts. These parameters and settings work well together when the query is formatted in natural language instead of keywords, for example when your user performs a voice search. + * @param ruleContexts Enables contextual rules. + * @param personalizationImpact Define the impact of the Personalization feature. + * @param userToken Associates a certain user token with the current search. + * @param getRankingInfo Retrieve detailed ranking information. + * @param clickAnalytics Enable the Click Analytics feature. + * @param analytics Whether the current query will be taken into account in the Analytics. + * @param analyticsTags List of tags to apply to the query for analytics purposes. + * @param percentileComputation Whether to include or exclude a query from the processing-time percentile computation. + * @param enableABTest Whether this search should participate in running AB tests. + * @param enableReRanking Whether this search should use AI Re-Ranking. + * @param reRankingApplyFilter + * @param attributesForFaceting The complete list of attributes that will be used for faceting. + * @param attributesToRetrieve This parameter controls which attributes to retrieve and which not to retrieve. + * @param restrictSearchableAttributes Restricts a given query to look in only a subset of your searchable attributes. + * @param ranking Controls how Algolia should sort your results. + * @param customRanking Specifies the custom ranking criterion. + * @param relevancyStrictness Controls the relevancy threshold below which less relevant results aren't included in the results. + * @param attributesToHighlight List of attributes to highlight. + * @param attributesToSnippet List of attributes to snippet, with an optional maximum number of words to snippet. + * @param highlightPreTag The HTML string to insert before the highlighted parts in all highlight and snippet results. + * @param highlightPostTag The HTML string to insert after the highlighted parts in all highlight and snippet results. + * @param snippetEllipsisText String used as an ellipsis indicator when a snippet is truncated. + * @param restrictHighlightAndSnippetArrays Restrict highlighting and snippeting to items that matched the query. + * @param hitsPerPage Set the number of hits per page. + * @param minWordSizefor1Typo Minimum number of characters a word in the query string must contain to accept matches with 1 typo. + * @param minWordSizefor2Typos Minimum number of characters a word in the query string must contain to accept matches with 2 typos. + * @param typoTolerance + * @param allowTyposOnNumericTokens Whether to allow typos on numbers (\"numeric tokens\") in the query string. + * @param disableTypoToleranceOnAttributes List of attributes on which you want to disable typo tolerance. + * @param ignorePlurals + * @param removeStopWords + * @param keepDiacriticsOnCharacters List of characters that the engine shouldn't automatically normalize. + * @param queryLanguages Sets the languages to be used by language-specific settings and functionalities such as ignorePlurals, removeStopWords, and CJK word-detection. + * @param decompoundQuery Splits compound words into their composing atoms in the query. + * @param enableRules Whether Rules should be globally enabled. + * @param enablePersonalization Enable the Personalization feature. + * @param queryType + * @param removeWordsIfNoResults + * @param mode + * @param semanticSearch + * @param advancedSyntax Enables the advanced query syntax. + * @param optionalWords A list of words that should be considered as optional when found in the query. + * @param disableExactOnAttributes List of attributes on which you want to disable the exact ranking criterion. + * @param exactOnSingleWordQuery + * @param alternativesAsExact List of alternatives that should be considered an exact match by the exact ranking criterion. + * @param advancedSyntaxFeatures Allows you to specify which advanced syntax features are active when ‘advancedSyntax' is enabled. + * @param explain Enriches the API’s response with meta-information as to how the query was processed. + * @param distinct + * @param attributeForDistinct Name of the de-duplication attribute to be used with the distinct feature. + * @param synonyms Whether to take into account an index's synonyms for a particular search. + * @param replaceSynonymsInHighlight Whether to highlight and snippet the original word that matches the synonym or the synonym itself. + * @param minProximity Precision of the proximity ranking criterion. + * @param responseFields Choose which fields to return in the API response. This parameters applies to search and browse queries. + * @param maxFacetHits Maximum number of facet hits to return during a search for facet values. For performance reasons, the maximum allowed number of returned values is 100. + * @param attributeCriteriaComputedByMinProximity When attribute is ranked above proximity in your ranking formula, proximity is used to select which searchable attribute is matched in the attribute ranking stage. + * @param renderingContent + */ +@Serializable +public data class SearchParamsObject( + + /** The text to search in the index. */ + @SerialName(value = "query") val query: String? = null, + + /** Overrides the query parameter and performs a more generic search that can be used to find \"similar\" results. */ + @SerialName(value = "similarQuery") val similarQuery: String? = null, + + /** Filter the query with numeric, facet and/or tag filters. */ + @SerialName(value = "filters") val filters: String? = null, + + @SerialName(value = "facetFilters") val facetFilters: FacetFilters? = null, + + @SerialName(value = "optionalFilters") val optionalFilters: OptionalFilters? = null, + + @SerialName(value = "numericFilters") val numericFilters: NumericFilters? = null, + + @SerialName(value = "tagFilters") val tagFilters: TagFilters? = null, + + /** Determines how to calculate the total score for filtering. */ + @SerialName(value = "sumOrFiltersScores") val sumOrFiltersScores: Boolean? = null, + + /** Retrieve facets and their facet values. */ + @SerialName(value = "facets") val facets: List? = null, + + /** Maximum number of facet values to return for each facet during a regular search. */ + @SerialName(value = "maxValuesPerFacet") val maxValuesPerFacet: Int? = null, + + /** Force faceting to be applied after de-duplication (via the Distinct setting). */ + @SerialName(value = "facetingAfterDistinct") val facetingAfterDistinct: Boolean? = null, + + /** Controls how facet values are fetched. */ + @SerialName(value = "sortFacetValuesBy") val sortFacetValuesBy: String? = null, + + /** Specify the page to retrieve. */ + @SerialName(value = "page") val page: Int? = null, + + /** Specify the offset of the first hit to return. */ + @SerialName(value = "offset") val offset: Int? = null, + + /** Set the number of hits to retrieve (used only with offset). */ + @SerialName(value = "length") val length: Int? = null, + + /** Search for entries around a central geolocation, enabling a geo search within a circular area. */ + @SerialName(value = "aroundLatLng") val aroundLatLng: String? = null, + + /** Search for entries around a given location automatically computed from the requester's IP address. */ + @SerialName(value = "aroundLatLngViaIP") val aroundLatLngViaIP: Boolean? = null, + + @SerialName(value = "aroundRadius") val aroundRadius: AroundRadius? = null, + + /** Precision of geo search (in meters), to add grouping by geo location to the ranking formula. */ + @SerialName(value = "aroundPrecision") val aroundPrecision: Int? = null, + + /** Minimum radius (in meters) used for a geo search when aroundRadius is not set. */ + @SerialName(value = "minimumAroundRadius") val minimumAroundRadius: Int? = null, + + /** Search inside a rectangular area (in geo coordinates). */ + @SerialName(value = "insideBoundingBox") val insideBoundingBox: List? = null, + + /** Search inside a polygon (in geo coordinates). */ + @SerialName(value = "insidePolygon") val insidePolygon: List? = null, + + /** This parameter changes the default values of certain parameters and settings that work best for a natural language query, such as ignorePlurals, removeStopWords, removeWordsIfNoResults, analyticsTags and ruleContexts. These parameters and settings work well together when the query is formatted in natural language instead of keywords, for example when your user performs a voice search. */ + @SerialName(value = "naturalLanguages") val naturalLanguages: List? = null, + + /** Enables contextual rules. */ + @SerialName(value = "ruleContexts") val ruleContexts: List? = null, + + /** Define the impact of the Personalization feature. */ + @SerialName(value = "personalizationImpact") val personalizationImpact: Int? = null, + + /** Associates a certain user token with the current search. */ + @SerialName(value = "userToken") val userToken: String? = null, + + /** Retrieve detailed ranking information. */ + @SerialName(value = "getRankingInfo") val getRankingInfo: Boolean? = null, + + /** Enable the Click Analytics feature. */ + @SerialName(value = "clickAnalytics") val clickAnalytics: Boolean? = null, + + /** Whether the current query will be taken into account in the Analytics. */ + @SerialName(value = "analytics") val analytics: Boolean? = null, + + /** List of tags to apply to the query for analytics purposes. */ + @SerialName(value = "analyticsTags") val analyticsTags: List? = null, + + /** Whether to include or exclude a query from the processing-time percentile computation. */ + @SerialName(value = "percentileComputation") val percentileComputation: Boolean? = null, + + /** Whether this search should participate in running AB tests. */ + @SerialName(value = "enableABTest") val enableABTest: Boolean? = null, + + /** Whether this search should use AI Re-Ranking. */ + @SerialName(value = "enableReRanking") val enableReRanking: Boolean? = null, + + @SerialName(value = "reRankingApplyFilter") val reRankingApplyFilter: ReRankingApplyFilter? = null, + + /** The complete list of attributes that will be used for faceting. */ + @SerialName(value = "attributesForFaceting") val attributesForFaceting: List? = null, + + /** This parameter controls which attributes to retrieve and which not to retrieve. */ + @SerialName(value = "attributesToRetrieve") val attributesToRetrieve: List? = null, + + /** Restricts a given query to look in only a subset of your searchable attributes. */ + @SerialName(value = "restrictSearchableAttributes") val restrictSearchableAttributes: List? = null, + + /** Controls how Algolia should sort your results. */ + @SerialName(value = "ranking") val ranking: List? = null, + + /** Specifies the custom ranking criterion. */ + @SerialName(value = "customRanking") val customRanking: List? = null, + + /** Controls the relevancy threshold below which less relevant results aren't included in the results. */ + @SerialName(value = "relevancyStrictness") val relevancyStrictness: Int? = null, + + /** List of attributes to highlight. */ + @SerialName(value = "attributesToHighlight") val attributesToHighlight: List? = null, + + /** List of attributes to snippet, with an optional maximum number of words to snippet. */ + @SerialName(value = "attributesToSnippet") val attributesToSnippet: List? = null, + + /** The HTML string to insert before the highlighted parts in all highlight and snippet results. */ + @SerialName(value = "highlightPreTag") val highlightPreTag: String? = null, + + /** The HTML string to insert after the highlighted parts in all highlight and snippet results. */ + @SerialName(value = "highlightPostTag") val highlightPostTag: String? = null, + + /** String used as an ellipsis indicator when a snippet is truncated. */ + @SerialName(value = "snippetEllipsisText") val snippetEllipsisText: String? = null, + + /** Restrict highlighting and snippeting to items that matched the query. */ + @SerialName(value = "restrictHighlightAndSnippetArrays") val restrictHighlightAndSnippetArrays: Boolean? = null, + + /** Set the number of hits per page. */ + @SerialName(value = "hitsPerPage") val hitsPerPage: Int? = null, + + /** Minimum number of characters a word in the query string must contain to accept matches with 1 typo. */ + @SerialName(value = "minWordSizefor1Typo") val minWordSizefor1Typo: Int? = null, + + /** Minimum number of characters a word in the query string must contain to accept matches with 2 typos. */ + @SerialName(value = "minWordSizefor2Typos") val minWordSizefor2Typos: Int? = null, + + @SerialName(value = "typoTolerance") val typoTolerance: TypoTolerance? = null, + + /** Whether to allow typos on numbers (\"numeric tokens\") in the query string. */ + @SerialName(value = "allowTyposOnNumericTokens") val allowTyposOnNumericTokens: Boolean? = null, + + /** List of attributes on which you want to disable typo tolerance. */ + @SerialName(value = "disableTypoToleranceOnAttributes") val disableTypoToleranceOnAttributes: List? = null, + + @SerialName(value = "ignorePlurals") val ignorePlurals: IgnorePlurals? = null, + + @SerialName(value = "removeStopWords") val removeStopWords: RemoveStopWords? = null, + + /** List of characters that the engine shouldn't automatically normalize. */ + @SerialName(value = "keepDiacriticsOnCharacters") val keepDiacriticsOnCharacters: String? = null, + + /** Sets the languages to be used by language-specific settings and functionalities such as ignorePlurals, removeStopWords, and CJK word-detection. */ + @SerialName(value = "queryLanguages") val queryLanguages: List? = null, + + /** Splits compound words into their composing atoms in the query. */ + @SerialName(value = "decompoundQuery") val decompoundQuery: Boolean? = null, + + /** Whether Rules should be globally enabled. */ + @SerialName(value = "enableRules") val enableRules: Boolean? = null, + + /** Enable the Personalization feature. */ + @SerialName(value = "enablePersonalization") val enablePersonalization: Boolean? = null, + + @SerialName(value = "queryType") val queryType: QueryType? = null, + + @SerialName(value = "removeWordsIfNoResults") val removeWordsIfNoResults: RemoveWordsIfNoResults? = null, + + @SerialName(value = "mode") val mode: Mode? = null, + + @SerialName(value = "semanticSearch") val semanticSearch: IndexSettingsAsSearchParamsSemanticSearch? = null, + + /** Enables the advanced query syntax. */ + @SerialName(value = "advancedSyntax") val advancedSyntax: Boolean? = null, + + /** A list of words that should be considered as optional when found in the query. */ + @SerialName(value = "optionalWords") val optionalWords: List? = null, + + /** List of attributes on which you want to disable the exact ranking criterion. */ + @SerialName(value = "disableExactOnAttributes") val disableExactOnAttributes: List? = null, + + @SerialName(value = "exactOnSingleWordQuery") val exactOnSingleWordQuery: ExactOnSingleWordQuery? = null, + + /** List of alternatives that should be considered an exact match by the exact ranking criterion. */ + @SerialName(value = "alternativesAsExact") val alternativesAsExact: List? = null, + + /** Allows you to specify which advanced syntax features are active when ‘advancedSyntax' is enabled. */ + @SerialName(value = "advancedSyntaxFeatures") val advancedSyntaxFeatures: List? = null, + + /** Enriches the API’s response with meta-information as to how the query was processed. */ + @SerialName(value = "explain") val explain: List? = null, + + @SerialName(value = "distinct") val distinct: Distinct? = null, + + /** Name of the de-duplication attribute to be used with the distinct feature. */ + @SerialName(value = "attributeForDistinct") val attributeForDistinct: String? = null, + + /** Whether to take into account an index's synonyms for a particular search. */ + @SerialName(value = "synonyms") val synonyms: Boolean? = null, + + /** Whether to highlight and snippet the original word that matches the synonym or the synonym itself. */ + @SerialName(value = "replaceSynonymsInHighlight") val replaceSynonymsInHighlight: Boolean? = null, + + /** Precision of the proximity ranking criterion. */ + @SerialName(value = "minProximity") val minProximity: Int? = null, + + /** Choose which fields to return in the API response. This parameters applies to search and browse queries. */ + @SerialName(value = "responseFields") val responseFields: List? = null, + + /** Maximum number of facet hits to return during a search for facet values. For performance reasons, the maximum allowed number of returned values is 100. */ + @SerialName(value = "maxFacetHits") val maxFacetHits: Int? = null, + + /** When attribute is ranked above proximity in your ranking formula, proximity is used to select which searchable attribute is matched in the attribute ranking stage. */ + @SerialName(value = "attributeCriteriaComputedByMinProximity") val attributeCriteriaComputedByMinProximity: Boolean? = null, + + @SerialName(value = "renderingContent") val renderingContent: RenderingContent? = null, +) : SearchParams diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchParamsQuery.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchParamsQuery.kt new file mode 100644 index 0000000000..a55acb9057 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchParamsQuery.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SearchParamsQuery + * + * @param query The text to search in the index. + */ +@Serializable +public data class SearchParamsQuery( + + /** The text to search in the index. */ + @SerialName(value = "query") val query: String? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchParamsString.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchParamsString.kt new file mode 100644 index 0000000000..1b62b1d9c0 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchParamsString.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SearchParamsString + * + * @param params Search parameters as URL-encoded query string. + */ +@Serializable +public data class SearchParamsString( + + /** Search parameters as URL-encoded query string. */ + @SerialName(value = "params") val params: String? = null, +) : SearchParams, BrowseParams diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchQuery.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchQuery.kt new file mode 100644 index 0000000000..59d15f2412 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchQuery.kt @@ -0,0 +1,573 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * SearchQuery + */ +@Serializable(SearchQuerySerializer::class) +public sealed interface SearchQuery { + + public companion object { + + /** + * SearchForFacets + * + * @param facet The `facet` name. + * @param indexName The Algolia index name. + * @param type + * @param params Search parameters as URL-encoded query string. + * @param query The text to search in the index. + * @param similarQuery Overrides the query parameter and performs a more generic search that can be used to find \"similar\" results. + * @param filters Filter the query with numeric, facet and/or tag filters. + * @param facetFilters + * @param optionalFilters + * @param numericFilters + * @param tagFilters + * @param sumOrFiltersScores Determines how to calculate the total score for filtering. + * @param facets Retrieve facets and their facet values. + * @param maxValuesPerFacet Maximum number of facet values to return for each facet during a regular search. + * @param facetingAfterDistinct Force faceting to be applied after de-duplication (via the Distinct setting). + * @param sortFacetValuesBy Controls how facet values are fetched. + * @param page Specify the page to retrieve. + * @param offset Specify the offset of the first hit to return. + * @param length Set the number of hits to retrieve (used only with offset). + * @param aroundLatLng Search for entries around a central geolocation, enabling a geo search within a circular area. + * @param aroundLatLngViaIP Search for entries around a given location automatically computed from the requester's IP address. + * @param aroundRadius + * @param aroundPrecision Precision of geo search (in meters), to add grouping by geo location to the ranking formula. + * @param minimumAroundRadius Minimum radius (in meters) used for a geo search when aroundRadius is not set. + * @param insideBoundingBox Search inside a rectangular area (in geo coordinates). + * @param insidePolygon Search inside a polygon (in geo coordinates). + * @param naturalLanguages This parameter changes the default values of certain parameters and settings that work best for a natural language query, such as ignorePlurals, removeStopWords, removeWordsIfNoResults, analyticsTags and ruleContexts. These parameters and settings work well together when the query is formatted in natural language instead of keywords, for example when your user performs a voice search. + * @param ruleContexts Enables contextual rules. + * @param personalizationImpact Define the impact of the Personalization feature. + * @param userToken Associates a certain user token with the current search. + * @param getRankingInfo Retrieve detailed ranking information. + * @param clickAnalytics Enable the Click Analytics feature. + * @param analytics Whether the current query will be taken into account in the Analytics. + * @param analyticsTags List of tags to apply to the query for analytics purposes. + * @param percentileComputation Whether to include or exclude a query from the processing-time percentile computation. + * @param enableABTest Whether this search should participate in running AB tests. + * @param enableReRanking Whether this search should use AI Re-Ranking. + * @param reRankingApplyFilter + * @param attributesForFaceting The complete list of attributes that will be used for faceting. + * @param attributesToRetrieve This parameter controls which attributes to retrieve and which not to retrieve. + * @param restrictSearchableAttributes Restricts a given query to look in only a subset of your searchable attributes. + * @param ranking Controls how Algolia should sort your results. + * @param customRanking Specifies the custom ranking criterion. + * @param relevancyStrictness Controls the relevancy threshold below which less relevant results aren't included in the results. + * @param attributesToHighlight List of attributes to highlight. + * @param attributesToSnippet List of attributes to snippet, with an optional maximum number of words to snippet. + * @param highlightPreTag The HTML string to insert before the highlighted parts in all highlight and snippet results. + * @param highlightPostTag The HTML string to insert after the highlighted parts in all highlight and snippet results. + * @param snippetEllipsisText String used as an ellipsis indicator when a snippet is truncated. + * @param restrictHighlightAndSnippetArrays Restrict highlighting and snippeting to items that matched the query. + * @param hitsPerPage Set the number of hits per page. + * @param minWordSizefor1Typo Minimum number of characters a word in the query string must contain to accept matches with 1 typo. + * @param minWordSizefor2Typos Minimum number of characters a word in the query string must contain to accept matches with 2 typos. + * @param typoTolerance + * @param allowTyposOnNumericTokens Whether to allow typos on numbers (\"numeric tokens\") in the query string. + * @param disableTypoToleranceOnAttributes List of attributes on which you want to disable typo tolerance. + * @param ignorePlurals + * @param removeStopWords + * @param keepDiacriticsOnCharacters List of characters that the engine shouldn't automatically normalize. + * @param queryLanguages Sets the languages to be used by language-specific settings and functionalities such as ignorePlurals, removeStopWords, and CJK word-detection. + * @param decompoundQuery Splits compound words into their composing atoms in the query. + * @param enableRules Whether Rules should be globally enabled. + * @param enablePersonalization Enable the Personalization feature. + * @param queryType + * @param removeWordsIfNoResults + * @param mode + * @param semanticSearch + * @param advancedSyntax Enables the advanced query syntax. + * @param optionalWords A list of words that should be considered as optional when found in the query. + * @param disableExactOnAttributes List of attributes on which you want to disable the exact ranking criterion. + * @param exactOnSingleWordQuery + * @param alternativesAsExact List of alternatives that should be considered an exact match by the exact ranking criterion. + * @param advancedSyntaxFeatures Allows you to specify which advanced syntax features are active when ‘advancedSyntax' is enabled. + * @param explain Enriches the API’s response with meta-information as to how the query was processed. + * @param distinct + * @param attributeForDistinct Name of the de-duplication attribute to be used with the distinct feature. + * @param synonyms Whether to take into account an index's synonyms for a particular search. + * @param replaceSynonymsInHighlight Whether to highlight and snippet the original word that matches the synonym or the synonym itself. + * @param minProximity Precision of the proximity ranking criterion. + * @param responseFields Choose which fields to return in the API response. This parameters applies to search and browse queries. + * @param maxFacetHits Maximum number of facet hits to return during a search for facet values. For performance reasons, the maximum allowed number of returned values is 100. + * @param attributeCriteriaComputedByMinProximity When attribute is ranked above proximity in your ranking formula, proximity is used to select which searchable attribute is matched in the attribute ranking stage. + * @param renderingContent + * @param facetQuery Text to search inside the facet's values. + */ + public fun SearchForFacets( + facet: String, + indexName: String, + type: SearchTypeFacet, + params: String? = null, + query: String? = null, + similarQuery: String? = null, + filters: String? = null, + facetFilters: FacetFilters? = null, + optionalFilters: OptionalFilters? = null, + numericFilters: NumericFilters? = null, + tagFilters: TagFilters? = null, + sumOrFiltersScores: Boolean? = null, + facets: List? = null, + maxValuesPerFacet: Int? = null, + facetingAfterDistinct: Boolean? = null, + sortFacetValuesBy: String? = null, + page: Int? = null, + offset: Int? = null, + length: Int? = null, + aroundLatLng: String? = null, + aroundLatLngViaIP: Boolean? = null, + aroundRadius: AroundRadius? = null, + aroundPrecision: Int? = null, + minimumAroundRadius: Int? = null, + insideBoundingBox: List? = null, + insidePolygon: List? = null, + naturalLanguages: List? = null, + ruleContexts: List? = null, + personalizationImpact: Int? = null, + userToken: String? = null, + getRankingInfo: Boolean? = null, + clickAnalytics: Boolean? = null, + analytics: Boolean? = null, + analyticsTags: List? = null, + percentileComputation: Boolean? = null, + enableABTest: Boolean? = null, + enableReRanking: Boolean? = null, + reRankingApplyFilter: ReRankingApplyFilter? = null, + attributesForFaceting: List? = null, + attributesToRetrieve: List? = null, + restrictSearchableAttributes: List? = null, + ranking: List? = null, + customRanking: List? = null, + relevancyStrictness: Int? = null, + attributesToHighlight: List? = null, + attributesToSnippet: List? = null, + highlightPreTag: String? = null, + highlightPostTag: String? = null, + snippetEllipsisText: String? = null, + restrictHighlightAndSnippetArrays: Boolean? = null, + hitsPerPage: Int? = null, + minWordSizefor1Typo: Int? = null, + minWordSizefor2Typos: Int? = null, + typoTolerance: TypoTolerance? = null, + allowTyposOnNumericTokens: Boolean? = null, + disableTypoToleranceOnAttributes: List? = null, + ignorePlurals: IgnorePlurals? = null, + removeStopWords: RemoveStopWords? = null, + keepDiacriticsOnCharacters: String? = null, + queryLanguages: List? = null, + decompoundQuery: Boolean? = null, + enableRules: Boolean? = null, + enablePersonalization: Boolean? = null, + queryType: QueryType? = null, + removeWordsIfNoResults: RemoveWordsIfNoResults? = null, + mode: Mode? = null, + semanticSearch: IndexSettingsAsSearchParamsSemanticSearch? = null, + advancedSyntax: Boolean? = null, + optionalWords: List? = null, + disableExactOnAttributes: List? = null, + exactOnSingleWordQuery: ExactOnSingleWordQuery? = null, + alternativesAsExact: List? = null, + advancedSyntaxFeatures: List? = null, + explain: List? = null, + distinct: Distinct? = null, + attributeForDistinct: String? = null, + synonyms: Boolean? = null, + replaceSynonymsInHighlight: Boolean? = null, + minProximity: Int? = null, + responseFields: List? = null, + maxFacetHits: Int? = null, + attributeCriteriaComputedByMinProximity: Boolean? = null, + renderingContent: RenderingContent? = null, + facetQuery: String? = null, + ): SearchForFacets = com.algolia.client.model.search.SearchForFacets( + facet = facet, + indexName = indexName, + type = type, + params = params, + query = query, + similarQuery = similarQuery, + filters = filters, + facetFilters = facetFilters, + optionalFilters = optionalFilters, + numericFilters = numericFilters, + tagFilters = tagFilters, + sumOrFiltersScores = sumOrFiltersScores, + facets = facets, + maxValuesPerFacet = maxValuesPerFacet, + facetingAfterDistinct = facetingAfterDistinct, + sortFacetValuesBy = sortFacetValuesBy, + page = page, + offset = offset, + length = length, + aroundLatLng = aroundLatLng, + aroundLatLngViaIP = aroundLatLngViaIP, + aroundRadius = aroundRadius, + aroundPrecision = aroundPrecision, + minimumAroundRadius = minimumAroundRadius, + insideBoundingBox = insideBoundingBox, + insidePolygon = insidePolygon, + naturalLanguages = naturalLanguages, + ruleContexts = ruleContexts, + personalizationImpact = personalizationImpact, + userToken = userToken, + getRankingInfo = getRankingInfo, + clickAnalytics = clickAnalytics, + analytics = analytics, + analyticsTags = analyticsTags, + percentileComputation = percentileComputation, + enableABTest = enableABTest, + enableReRanking = enableReRanking, + reRankingApplyFilter = reRankingApplyFilter, + attributesForFaceting = attributesForFaceting, + attributesToRetrieve = attributesToRetrieve, + restrictSearchableAttributes = restrictSearchableAttributes, + ranking = ranking, + customRanking = customRanking, + relevancyStrictness = relevancyStrictness, + attributesToHighlight = attributesToHighlight, + attributesToSnippet = attributesToSnippet, + highlightPreTag = highlightPreTag, + highlightPostTag = highlightPostTag, + snippetEllipsisText = snippetEllipsisText, + restrictHighlightAndSnippetArrays = restrictHighlightAndSnippetArrays, + hitsPerPage = hitsPerPage, + minWordSizefor1Typo = minWordSizefor1Typo, + minWordSizefor2Typos = minWordSizefor2Typos, + typoTolerance = typoTolerance, + allowTyposOnNumericTokens = allowTyposOnNumericTokens, + disableTypoToleranceOnAttributes = disableTypoToleranceOnAttributes, + ignorePlurals = ignorePlurals, + removeStopWords = removeStopWords, + keepDiacriticsOnCharacters = keepDiacriticsOnCharacters, + queryLanguages = queryLanguages, + decompoundQuery = decompoundQuery, + enableRules = enableRules, + enablePersonalization = enablePersonalization, + queryType = queryType, + removeWordsIfNoResults = removeWordsIfNoResults, + mode = mode, + semanticSearch = semanticSearch, + advancedSyntax = advancedSyntax, + optionalWords = optionalWords, + disableExactOnAttributes = disableExactOnAttributes, + exactOnSingleWordQuery = exactOnSingleWordQuery, + alternativesAsExact = alternativesAsExact, + advancedSyntaxFeatures = advancedSyntaxFeatures, + explain = explain, + distinct = distinct, + attributeForDistinct = attributeForDistinct, + synonyms = synonyms, + replaceSynonymsInHighlight = replaceSynonymsInHighlight, + minProximity = minProximity, + responseFields = responseFields, + maxFacetHits = maxFacetHits, + attributeCriteriaComputedByMinProximity = attributeCriteriaComputedByMinProximity, + renderingContent = renderingContent, + facetQuery = facetQuery, + ) + + /** + * SearchForHits + * + * @param indexName The Algolia index name. + * @param params Search parameters as URL-encoded query string. + * @param query The text to search in the index. + * @param similarQuery Overrides the query parameter and performs a more generic search that can be used to find \"similar\" results. + * @param filters Filter the query with numeric, facet and/or tag filters. + * @param facetFilters + * @param optionalFilters + * @param numericFilters + * @param tagFilters + * @param sumOrFiltersScores Determines how to calculate the total score for filtering. + * @param facets Retrieve facets and their facet values. + * @param maxValuesPerFacet Maximum number of facet values to return for each facet during a regular search. + * @param facetingAfterDistinct Force faceting to be applied after de-duplication (via the Distinct setting). + * @param sortFacetValuesBy Controls how facet values are fetched. + * @param page Specify the page to retrieve. + * @param offset Specify the offset of the first hit to return. + * @param length Set the number of hits to retrieve (used only with offset). + * @param aroundLatLng Search for entries around a central geolocation, enabling a geo search within a circular area. + * @param aroundLatLngViaIP Search for entries around a given location automatically computed from the requester's IP address. + * @param aroundRadius + * @param aroundPrecision Precision of geo search (in meters), to add grouping by geo location to the ranking formula. + * @param minimumAroundRadius Minimum radius (in meters) used for a geo search when aroundRadius is not set. + * @param insideBoundingBox Search inside a rectangular area (in geo coordinates). + * @param insidePolygon Search inside a polygon (in geo coordinates). + * @param naturalLanguages This parameter changes the default values of certain parameters and settings that work best for a natural language query, such as ignorePlurals, removeStopWords, removeWordsIfNoResults, analyticsTags and ruleContexts. These parameters and settings work well together when the query is formatted in natural language instead of keywords, for example when your user performs a voice search. + * @param ruleContexts Enables contextual rules. + * @param personalizationImpact Define the impact of the Personalization feature. + * @param userToken Associates a certain user token with the current search. + * @param getRankingInfo Retrieve detailed ranking information. + * @param clickAnalytics Enable the Click Analytics feature. + * @param analytics Whether the current query will be taken into account in the Analytics. + * @param analyticsTags List of tags to apply to the query for analytics purposes. + * @param percentileComputation Whether to include or exclude a query from the processing-time percentile computation. + * @param enableABTest Whether this search should participate in running AB tests. + * @param enableReRanking Whether this search should use AI Re-Ranking. + * @param reRankingApplyFilter + * @param attributesForFaceting The complete list of attributes that will be used for faceting. + * @param attributesToRetrieve This parameter controls which attributes to retrieve and which not to retrieve. + * @param restrictSearchableAttributes Restricts a given query to look in only a subset of your searchable attributes. + * @param ranking Controls how Algolia should sort your results. + * @param customRanking Specifies the custom ranking criterion. + * @param relevancyStrictness Controls the relevancy threshold below which less relevant results aren't included in the results. + * @param attributesToHighlight List of attributes to highlight. + * @param attributesToSnippet List of attributes to snippet, with an optional maximum number of words to snippet. + * @param highlightPreTag The HTML string to insert before the highlighted parts in all highlight and snippet results. + * @param highlightPostTag The HTML string to insert after the highlighted parts in all highlight and snippet results. + * @param snippetEllipsisText String used as an ellipsis indicator when a snippet is truncated. + * @param restrictHighlightAndSnippetArrays Restrict highlighting and snippeting to items that matched the query. + * @param hitsPerPage Set the number of hits per page. + * @param minWordSizefor1Typo Minimum number of characters a word in the query string must contain to accept matches with 1 typo. + * @param minWordSizefor2Typos Minimum number of characters a word in the query string must contain to accept matches with 2 typos. + * @param typoTolerance + * @param allowTyposOnNumericTokens Whether to allow typos on numbers (\"numeric tokens\") in the query string. + * @param disableTypoToleranceOnAttributes List of attributes on which you want to disable typo tolerance. + * @param ignorePlurals + * @param removeStopWords + * @param keepDiacriticsOnCharacters List of characters that the engine shouldn't automatically normalize. + * @param queryLanguages Sets the languages to be used by language-specific settings and functionalities such as ignorePlurals, removeStopWords, and CJK word-detection. + * @param decompoundQuery Splits compound words into their composing atoms in the query. + * @param enableRules Whether Rules should be globally enabled. + * @param enablePersonalization Enable the Personalization feature. + * @param queryType + * @param removeWordsIfNoResults + * @param mode + * @param semanticSearch + * @param advancedSyntax Enables the advanced query syntax. + * @param optionalWords A list of words that should be considered as optional when found in the query. + * @param disableExactOnAttributes List of attributes on which you want to disable the exact ranking criterion. + * @param exactOnSingleWordQuery + * @param alternativesAsExact List of alternatives that should be considered an exact match by the exact ranking criterion. + * @param advancedSyntaxFeatures Allows you to specify which advanced syntax features are active when ‘advancedSyntax' is enabled. + * @param explain Enriches the API’s response with meta-information as to how the query was processed. + * @param distinct + * @param attributeForDistinct Name of the de-duplication attribute to be used with the distinct feature. + * @param synonyms Whether to take into account an index's synonyms for a particular search. + * @param replaceSynonymsInHighlight Whether to highlight and snippet the original word that matches the synonym or the synonym itself. + * @param minProximity Precision of the proximity ranking criterion. + * @param responseFields Choose which fields to return in the API response. This parameters applies to search and browse queries. + * @param maxFacetHits Maximum number of facet hits to return during a search for facet values. For performance reasons, the maximum allowed number of returned values is 100. + * @param attributeCriteriaComputedByMinProximity When attribute is ranked above proximity in your ranking formula, proximity is used to select which searchable attribute is matched in the attribute ranking stage. + * @param renderingContent + * @param type + */ + public fun SearchForHits( + indexName: String, + params: String? = null, + query: String? = null, + similarQuery: String? = null, + filters: String? = null, + facetFilters: FacetFilters? = null, + optionalFilters: OptionalFilters? = null, + numericFilters: NumericFilters? = null, + tagFilters: TagFilters? = null, + sumOrFiltersScores: Boolean? = null, + facets: List? = null, + maxValuesPerFacet: Int? = null, + facetingAfterDistinct: Boolean? = null, + sortFacetValuesBy: String? = null, + page: Int? = null, + offset: Int? = null, + length: Int? = null, + aroundLatLng: String? = null, + aroundLatLngViaIP: Boolean? = null, + aroundRadius: AroundRadius? = null, + aroundPrecision: Int? = null, + minimumAroundRadius: Int? = null, + insideBoundingBox: List? = null, + insidePolygon: List? = null, + naturalLanguages: List? = null, + ruleContexts: List? = null, + personalizationImpact: Int? = null, + userToken: String? = null, + getRankingInfo: Boolean? = null, + clickAnalytics: Boolean? = null, + analytics: Boolean? = null, + analyticsTags: List? = null, + percentileComputation: Boolean? = null, + enableABTest: Boolean? = null, + enableReRanking: Boolean? = null, + reRankingApplyFilter: ReRankingApplyFilter? = null, + attributesForFaceting: List? = null, + attributesToRetrieve: List? = null, + restrictSearchableAttributes: List? = null, + ranking: List? = null, + customRanking: List? = null, + relevancyStrictness: Int? = null, + attributesToHighlight: List? = null, + attributesToSnippet: List? = null, + highlightPreTag: String? = null, + highlightPostTag: String? = null, + snippetEllipsisText: String? = null, + restrictHighlightAndSnippetArrays: Boolean? = null, + hitsPerPage: Int? = null, + minWordSizefor1Typo: Int? = null, + minWordSizefor2Typos: Int? = null, + typoTolerance: TypoTolerance? = null, + allowTyposOnNumericTokens: Boolean? = null, + disableTypoToleranceOnAttributes: List? = null, + ignorePlurals: IgnorePlurals? = null, + removeStopWords: RemoveStopWords? = null, + keepDiacriticsOnCharacters: String? = null, + queryLanguages: List? = null, + decompoundQuery: Boolean? = null, + enableRules: Boolean? = null, + enablePersonalization: Boolean? = null, + queryType: QueryType? = null, + removeWordsIfNoResults: RemoveWordsIfNoResults? = null, + mode: Mode? = null, + semanticSearch: IndexSettingsAsSearchParamsSemanticSearch? = null, + advancedSyntax: Boolean? = null, + optionalWords: List? = null, + disableExactOnAttributes: List? = null, + exactOnSingleWordQuery: ExactOnSingleWordQuery? = null, + alternativesAsExact: List? = null, + advancedSyntaxFeatures: List? = null, + explain: List? = null, + distinct: Distinct? = null, + attributeForDistinct: String? = null, + synonyms: Boolean? = null, + replaceSynonymsInHighlight: Boolean? = null, + minProximity: Int? = null, + responseFields: List? = null, + maxFacetHits: Int? = null, + attributeCriteriaComputedByMinProximity: Boolean? = null, + renderingContent: RenderingContent? = null, + type: SearchTypeDefault? = null, + ): SearchForHits = com.algolia.client.model.search.SearchForHits( + indexName = indexName, + params = params, + query = query, + similarQuery = similarQuery, + filters = filters, + facetFilters = facetFilters, + optionalFilters = optionalFilters, + numericFilters = numericFilters, + tagFilters = tagFilters, + sumOrFiltersScores = sumOrFiltersScores, + facets = facets, + maxValuesPerFacet = maxValuesPerFacet, + facetingAfterDistinct = facetingAfterDistinct, + sortFacetValuesBy = sortFacetValuesBy, + page = page, + offset = offset, + length = length, + aroundLatLng = aroundLatLng, + aroundLatLngViaIP = aroundLatLngViaIP, + aroundRadius = aroundRadius, + aroundPrecision = aroundPrecision, + minimumAroundRadius = minimumAroundRadius, + insideBoundingBox = insideBoundingBox, + insidePolygon = insidePolygon, + naturalLanguages = naturalLanguages, + ruleContexts = ruleContexts, + personalizationImpact = personalizationImpact, + userToken = userToken, + getRankingInfo = getRankingInfo, + clickAnalytics = clickAnalytics, + analytics = analytics, + analyticsTags = analyticsTags, + percentileComputation = percentileComputation, + enableABTest = enableABTest, + enableReRanking = enableReRanking, + reRankingApplyFilter = reRankingApplyFilter, + attributesForFaceting = attributesForFaceting, + attributesToRetrieve = attributesToRetrieve, + restrictSearchableAttributes = restrictSearchableAttributes, + ranking = ranking, + customRanking = customRanking, + relevancyStrictness = relevancyStrictness, + attributesToHighlight = attributesToHighlight, + attributesToSnippet = attributesToSnippet, + highlightPreTag = highlightPreTag, + highlightPostTag = highlightPostTag, + snippetEllipsisText = snippetEllipsisText, + restrictHighlightAndSnippetArrays = restrictHighlightAndSnippetArrays, + hitsPerPage = hitsPerPage, + minWordSizefor1Typo = minWordSizefor1Typo, + minWordSizefor2Typos = minWordSizefor2Typos, + typoTolerance = typoTolerance, + allowTyposOnNumericTokens = allowTyposOnNumericTokens, + disableTypoToleranceOnAttributes = disableTypoToleranceOnAttributes, + ignorePlurals = ignorePlurals, + removeStopWords = removeStopWords, + keepDiacriticsOnCharacters = keepDiacriticsOnCharacters, + queryLanguages = queryLanguages, + decompoundQuery = decompoundQuery, + enableRules = enableRules, + enablePersonalization = enablePersonalization, + queryType = queryType, + removeWordsIfNoResults = removeWordsIfNoResults, + mode = mode, + semanticSearch = semanticSearch, + advancedSyntax = advancedSyntax, + optionalWords = optionalWords, + disableExactOnAttributes = disableExactOnAttributes, + exactOnSingleWordQuery = exactOnSingleWordQuery, + alternativesAsExact = alternativesAsExact, + advancedSyntaxFeatures = advancedSyntaxFeatures, + explain = explain, + distinct = distinct, + attributeForDistinct = attributeForDistinct, + synonyms = synonyms, + replaceSynonymsInHighlight = replaceSynonymsInHighlight, + minProximity = minProximity, + responseFields = responseFields, + maxFacetHits = maxFacetHits, + attributeCriteriaComputedByMinProximity = attributeCriteriaComputedByMinProximity, + renderingContent = renderingContent, + type = type, + ) + } +} + +internal class SearchQuerySerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("SearchQuery") + + override fun serialize(encoder: Encoder, value: SearchQuery) { + when (value) { + is SearchForFacets -> SearchForFacets.serializer().serialize(encoder, value) + is SearchForHits -> SearchForHits.serializer().serialize(encoder, value) + } + } + + override fun deserialize(decoder: Decoder): SearchQuery { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize SearchForFacets + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize SearchForFacets (error: ${e.message})") + } + } + + // deserialize SearchForHits + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize SearchForHits (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchResponse.kt new file mode 100644 index 0000000000..dd5a483b02 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchResponse.kt @@ -0,0 +1,118 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SearchResponse + * + * @param exhaustiveNbHits Indicate if the nbHits count was exhaustive or approximate. + * @param hitsPerPage Set the number of hits per page. + * @param nbHits Number of hits that the search query matched. + * @param nbPages Number of pages available for the current query. + * @param page Specify the page to retrieve. + * @param params A url-encoded string of all search parameters. + * @param processingTimeMS Time the server took to process the request, in milliseconds. + * @param query The text to search in the index. + * @param hits + * @param abTestID If a search encounters an index that is being A/B tested, abTestID reports the ongoing A/B test ID. + * @param abTestVariantID If a search encounters an index that is being A/B tested, abTestVariantID reports the variant ID of the index used (starting at 1). + * @param aroundLatLng The computed geo location. + * @param automaticRadius The automatically computed radius. For legacy reasons, this parameter is a string and not an integer. + * @param exhaustiveFacetsCount Whether the facet count is exhaustive or approximate. + * @param exhaustiveTypo Indicate if the typo-tolerance search was exhaustive or approximate (only included when typo-tolerance is enabled). + * @param facets A mapping of each facet name to the corresponding facet counts. + * @param facetsStats Statistics for numerical facets. + * @param index Index name used for the query. + * @param indexUsed Index name used for the query. In the case of an A/B test, the targeted index isn't always the index used by the query. + * @param message Used to return warnings about the query. + * @param nbSortedHits The number of hits selected and sorted by the relevant sort algorithm. + * @param redirect + * @param parsedQuery The query string that will be searched, after normalization. + * @param queryAfterRemoval A markup text indicating which parts of the original query have been removed in order to retrieve a non-empty result set. + * @param serverUsed Actual host name of the server that processed the request. + * @param userData Lets you store custom data in your indices. + * @param renderingContent + */ +@Serializable +public data class SearchResponse( + + /** Indicate if the nbHits count was exhaustive or approximate. */ + @SerialName(value = "exhaustiveNbHits") val exhaustiveNbHits: Boolean, + + /** Set the number of hits per page. */ + @SerialName(value = "hitsPerPage") val hitsPerPage: Int, + + /** Number of hits that the search query matched. */ + @SerialName(value = "nbHits") val nbHits: Int, + + /** Number of pages available for the current query. */ + @SerialName(value = "nbPages") val nbPages: Int, + + /** Specify the page to retrieve. */ + @SerialName(value = "page") val page: Int, + + /** A url-encoded string of all search parameters. */ + @SerialName(value = "params") val params: String, + + /** Time the server took to process the request, in milliseconds. */ + @SerialName(value = "processingTimeMS") val processingTimeMS: Int, + + /** The text to search in the index. */ + @SerialName(value = "query") val query: String, + + @SerialName(value = "hits") val hits: List, + + /** If a search encounters an index that is being A/B tested, abTestID reports the ongoing A/B test ID. */ + @SerialName(value = "abTestID") val abTestID: Int? = null, + + /** If a search encounters an index that is being A/B tested, abTestVariantID reports the variant ID of the index used (starting at 1). */ + @SerialName(value = "abTestVariantID") val abTestVariantID: Int? = null, + + /** The computed geo location. */ + @SerialName(value = "aroundLatLng") val aroundLatLng: String? = null, + + /** The automatically computed radius. For legacy reasons, this parameter is a string and not an integer. */ + @SerialName(value = "automaticRadius") val automaticRadius: String? = null, + + /** Whether the facet count is exhaustive or approximate. */ + @SerialName(value = "exhaustiveFacetsCount") val exhaustiveFacetsCount: Boolean? = null, + + /** Indicate if the typo-tolerance search was exhaustive or approximate (only included when typo-tolerance is enabled). */ + @SerialName(value = "exhaustiveTypo") val exhaustiveTypo: Boolean? = null, + + /** A mapping of each facet name to the corresponding facet counts. */ + @SerialName(value = "facets") val facets: Map>? = null, + + /** Statistics for numerical facets. */ + @SerialName(value = "facets_stats") val facetsStats: Map? = null, + + /** Index name used for the query. */ + @SerialName(value = "index") val index: String? = null, + + /** Index name used for the query. In the case of an A/B test, the targeted index isn't always the index used by the query. */ + @SerialName(value = "indexUsed") val indexUsed: String? = null, + + /** Used to return warnings about the query. */ + @SerialName(value = "message") val message: String? = null, + + /** The number of hits selected and sorted by the relevant sort algorithm. */ + @SerialName(value = "nbSortedHits") val nbSortedHits: Int? = null, + + @SerialName(value = "redirect") val redirect: BaseSearchResponseRedirect? = null, + + /** The query string that will be searched, after normalization. */ + @SerialName(value = "parsedQuery") val parsedQuery: String? = null, + + /** A markup text indicating which parts of the original query have been removed in order to retrieve a non-empty result set. */ + @SerialName(value = "queryAfterRemoval") val queryAfterRemoval: String? = null, + + /** Actual host name of the server that processed the request. */ + @SerialName(value = "serverUsed") val serverUsed: String? = null, + + /** Lets you store custom data in your indices. */ + @SerialName(value = "userData") val userData: JsonObject? = null, + + @SerialName(value = "renderingContent") val renderingContent: RenderingContent? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchResponses.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchResponses.kt new file mode 100644 index 0000000000..c3b7512d0c --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchResponses.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SearchResponses + * + * @param results + */ +@Serializable +public data class SearchResponses( + + @SerialName(value = "results") val results: List, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchRulesParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchRulesParams.kt new file mode 100644 index 0000000000..1e7a18f34f --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchRulesParams.kt @@ -0,0 +1,40 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Parameters for the search. + * + * @param query Full text query. + * @param anchoring + * @param context Restricts matches to contextual rules with a specific context (exact match). + * @param page Requested page (zero-based). + * @param hitsPerPage Maximum number of hits in a page. Minimum is 1, maximum is 1000. + * @param enabled When specified, restricts matches to rules with a specific enabled status. When absent (default), all rules are retrieved, regardless of their enabled status. + * @param requestOptions A mapping of requestOptions to send along with the request. + */ +@Serializable +public data class SearchRulesParams( + + /** Full text query. */ + @SerialName(value = "query") val query: String? = null, + + @SerialName(value = "anchoring") val anchoring: Anchoring? = null, + + /** Restricts matches to contextual rules with a specific context (exact match). */ + @SerialName(value = "context") val context: String? = null, + + /** Requested page (zero-based). */ + @SerialName(value = "page") val page: Int? = null, + + /** Maximum number of hits in a page. Minimum is 1, maximum is 1000. */ + @SerialName(value = "hitsPerPage") val hitsPerPage: Int? = null, + + /** When specified, restricts matches to rules with a specific enabled status. When absent (default), all rules are retrieved, regardless of their enabled status. */ + @SerialName(value = "enabled") val enabled: Boolean? = null, + + /** A mapping of requestOptions to send along with the request. */ + @SerialName(value = "requestOptions") val requestOptions: List? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchRulesResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchRulesResponse.kt new file mode 100644 index 0000000000..b89d229612 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchRulesResponse.kt @@ -0,0 +1,29 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SearchRulesResponse + * + * @param hits Fetched rules. + * @param nbHits Number of fetched rules. + * @param page Current page. + * @param nbPages Number of pages. + */ +@Serializable +public data class SearchRulesResponse( + + /** Fetched rules. */ + @SerialName(value = "hits") val hits: List, + + /** Number of fetched rules. */ + @SerialName(value = "nbHits") val nbHits: Int, + + /** Current page. */ + @SerialName(value = "page") val page: Int, + + /** Number of pages. */ + @SerialName(value = "nbPages") val nbPages: Int, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchStrategy.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchStrategy.kt new file mode 100644 index 0000000000..3352182664 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchStrategy.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* + +@Serializable +public enum class SearchStrategy(public val value: kotlin.String) { + + @SerialName(value = "none") + None("none"), + + @SerialName(value = "stopIfEnoughMatches") + StopIfEnoughMatches("stopIfEnoughMatches"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchSynonymsParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchSynonymsParams.kt new file mode 100644 index 0000000000..86abc6ddc3 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchSynonymsParams.kt @@ -0,0 +1,17 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * SearchSynonymsParams + * + * @param query The text to search in the index. + */ +@Serializable +public data class SearchSynonymsParams( + + /** The text to search in the index. */ + @SerialName(value = "query") val query: String? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchSynonymsResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchSynonymsResponse.kt new file mode 100644 index 0000000000..91de7cd7a8 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchSynonymsResponse.kt @@ -0,0 +1,54 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * SearchSynonymsResponse + * + * @param hits Array of synonym objects. + * @param nbHits Number of hits that the search query matched. + */ +@Serializable(SearchSynonymsResponseSerializer::class) +public data class SearchSynonymsResponse( + + /** Array of synonym objects. */ + val hits: List, + + /** Number of hits that the search query matched. */ + val nbHits: Int, + + val additionalProperties: Map? = null, +) + +internal object SearchSynonymsResponseSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("SearchSynonymsResponse") { + element>("hits") + element("nbHits") + } + + override fun deserialize(decoder: Decoder): SearchSynonymsResponse { + val input = decoder.asJsonDecoder() + val tree = input.decodeJsonObject() + return SearchSynonymsResponse( + hits = tree.getValue("hits").let { input.json.decodeFromJsonElement(it) }, + nbHits = tree.getValue("nbHits").let { input.json.decodeFromJsonElement(it) }, + additionalProperties = tree.filterKeys { it !in descriptor.elementNames }, + ) + } + + override fun serialize(encoder: Encoder, value: SearchSynonymsResponse) { + val output = encoder.asJsonEncoder() + val json = buildJsonObject { + put("hits", output.json.encodeToJsonElement(value.hits)) + put("nbHits", output.json.encodeToJsonElement(value.nbHits)) + value.additionalProperties?.onEach { (key, element) -> put(key, element) } + } + (encoder as JsonEncoder).encodeJsonElement(json) + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchTypeDefault.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchTypeDefault.kt new file mode 100644 index 0000000000..cccfafca23 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchTypeDefault.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* + +/** + * Perform a search query with `default`, will search for facet values if `facet` is given. + */ +@Serializable +public enum class SearchTypeDefault(public val value: kotlin.String) { + + @SerialName(value = "default") + Default("default"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchTypeFacet.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchTypeFacet.kt new file mode 100644 index 0000000000..c38f36d41f --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchTypeFacet.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* + +/** + * Perform a search query with `default`, will search for facet values if `facet` is given. + */ +@Serializable +public enum class SearchTypeFacet(public val value: kotlin.String) { + + @SerialName(value = "facet") + Facet("facet"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchUserIdsParams.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchUserIdsParams.kt new file mode 100644 index 0000000000..bcc9e11376 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchUserIdsParams.kt @@ -0,0 +1,29 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * OK + * + * @param query Query to search. The search is a prefix search with typoTolerance. Use empty query to retrieve all users. + * @param clusterName Name of the cluster. + * @param page Specify the page to retrieve. + * @param hitsPerPage Set the number of hits per page. + */ +@Serializable +public data class SearchUserIdsParams( + + /** Query to search. The search is a prefix search with typoTolerance. Use empty query to retrieve all users. */ + @SerialName(value = "query") val query: String, + + /** Name of the cluster. */ + @SerialName(value = "clusterName") val clusterName: String? = null, + + /** Specify the page to retrieve. */ + @SerialName(value = "page") val page: Int? = null, + + /** Set the number of hits per page. */ + @SerialName(value = "hitsPerPage") val hitsPerPage: Int? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchUserIdsResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchUserIdsResponse.kt new file mode 100644 index 0000000000..ab4b00f656 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SearchUserIdsResponse.kt @@ -0,0 +1,33 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * userIDs data. + * + * @param hits List of user object matching the query. + * @param nbHits Number of hits that the search query matched. + * @param page Specify the page to retrieve. + * @param hitsPerPage Maximum number of hits in a page. Minimum is 1, maximum is 1000. + * @param updatedAt Date of last update (ISO-8601 format). + */ +@Serializable +public data class SearchUserIdsResponse( + + /** List of user object matching the query. */ + @SerialName(value = "hits") val hits: List, + + /** Number of hits that the search query matched. */ + @SerialName(value = "nbHits") val nbHits: Int, + + /** Specify the page to retrieve. */ + @SerialName(value = "page") val page: Int, + + /** Maximum number of hits in a page. Minimum is 1, maximum is 1000. */ + @SerialName(value = "hitsPerPage") val hitsPerPage: Int, + + /** Date of last update (ISO-8601 format). */ + @SerialName(value = "updatedAt") val updatedAt: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SnippetResult.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SnippetResult.kt new file mode 100644 index 0000000000..e3dd14095e --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SnippetResult.kt @@ -0,0 +1,85 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * SnippetResult + */ +@Serializable(SnippetResultSerializer::class) +public sealed interface SnippetResult { + + public data class ListOfSnippetResultOptionWrapper(val value: List) : SnippetResult + + public companion object { + + /** + * SnippetResult as List + * + */ + public fun ListOfSnippetResultOption( + value: List, + ): ListOfSnippetResultOptionWrapper = ListOfSnippetResultOptionWrapper( + value = value, + ) + + /** + * Snippeted attributes show parts of the matched attributes. Only returned when attributesToSnippet is non-empty. + * + * @param `value` Markup text with occurrences highlighted. + * @param matchLevel + */ + public fun SnippetResultOption( + `value`: String, + matchLevel: MatchLevel, + ): SnippetResultOption = com.algolia.client.model.search.SnippetResultOption( + `value` = `value`, + matchLevel = matchLevel, + ) + } +} + +internal class SnippetResultSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("SnippetResult") + + override fun serialize(encoder: Encoder, value: SnippetResult) { + when (value) { + is SnippetResult.ListOfSnippetResultOptionWrapper -> ListSerializer(SnippetResultOption.serializer()).serialize(encoder, value.value) + is SnippetResultOption -> SnippetResultOption.serializer().serialize(encoder, value) + } + } + + override fun deserialize(decoder: Decoder): SnippetResult { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize List + if (tree is JsonArray) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize List (error: ${e.message})") + } + } + + // deserialize SnippetResultOption + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize SnippetResultOption (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SnippetResultOption.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SnippetResultOption.kt new file mode 100644 index 0000000000..6189800021 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SnippetResultOption.kt @@ -0,0 +1,20 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Snippeted attributes show parts of the matched attributes. Only returned when attributesToSnippet is non-empty. + * + * @param `value` Markup text with occurrences highlighted. + * @param matchLevel + */ +@Serializable +public data class SnippetResultOption( + + /** Markup text with occurrences highlighted. */ + @SerialName(value = "value") val `value`: String, + + @SerialName(value = "matchLevel") val matchLevel: MatchLevel, +) : SnippetResult diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SortRemainingBy.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SortRemainingBy.kt new file mode 100644 index 0000000000..71e6994de1 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SortRemainingBy.kt @@ -0,0 +1,22 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* + +/** + * How to display the remaining items. - `count`: facet count (descending). - `alpha`: alphabetical (ascending). - `hidden`: show only pinned values. + */ +@Serializable +public enum class SortRemainingBy(public val value: kotlin.String) { + + @SerialName(value = "count") + Count("count"), + + @SerialName(value = "alpha") + Alpha("alpha"), + + @SerialName(value = "hidden") + Hidden("hidden"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Source.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Source.kt new file mode 100644 index 0000000000..6bc223f747 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Source.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The source. + * + * @param source The IP range of the source. + * @param description The description of the source. + */ +@Serializable +public data class Source( + + /** The IP range of the source. */ + @SerialName(value = "source") val source: String, + + /** The description of the source. */ + @SerialName(value = "description") val description: String? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/StandardEntries.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/StandardEntries.kt new file mode 100644 index 0000000000..337cf76b47 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/StandardEntries.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Map of language ISO code supported by the dictionary (e.g., \"en\" for English) to a boolean value. + * + * @param plurals Language ISO code. + * @param stopwords Language ISO code. + * @param compounds Language ISO code. + */ +@Serializable +public data class StandardEntries( + + /** Language ISO code. */ + @SerialName(value = "plurals") val plurals: Map? = null, + + /** Language ISO code. */ + @SerialName(value = "stopwords") val stopwords: Map? = null, + + /** Language ISO code. */ + @SerialName(value = "compounds") val compounds: Map? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SynonymHit.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SynonymHit.kt new file mode 100644 index 0000000000..76701cf5ca --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SynonymHit.kt @@ -0,0 +1,44 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Synonym object. + * + * @param objectID Unique identifier of the synonym object to be created or updated. + * @param type + * @param synonyms Words or phrases to be considered equivalent. + * @param input Word or phrase to appear in query strings (for onewaysynonym). + * @param word Word or phrase to appear in query strings (for altcorrection1 and altcorrection2). + * @param corrections Words to be matched in records. + * @param placeholder Token to be put inside records. + * @param replacements List of query words that will match the token. + */ +@Serializable +public data class SynonymHit( + + /** Unique identifier of the synonym object to be created or updated. */ + @SerialName(value = "objectID") val objectID: String, + + @SerialName(value = "type") val type: SynonymType, + + /** Words or phrases to be considered equivalent. */ + @SerialName(value = "synonyms") val synonyms: List? = null, + + /** Word or phrase to appear in query strings (for onewaysynonym). */ + @SerialName(value = "input") val input: String? = null, + + /** Word or phrase to appear in query strings (for altcorrection1 and altcorrection2). */ + @SerialName(value = "word") val word: String? = null, + + /** Words to be matched in records. */ + @SerialName(value = "corrections") val corrections: List? = null, + + /** Token to be put inside records. */ + @SerialName(value = "placeholder") val placeholder: String? = null, + + /** List of query words that will match the token. */ + @SerialName(value = "replacements") val replacements: List? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SynonymType.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SynonymType.kt new file mode 100644 index 0000000000..9fe8161b74 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/SynonymType.kt @@ -0,0 +1,28 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* + +/** + * Type of the synonym object. + */ +@Serializable +public enum class SynonymType(public val value: kotlin.String) { + + @SerialName(value = "synonym") + Synonym("synonym"), + + @SerialName(value = "onewaysynonym") + Onewaysynonym("onewaysynonym"), + + @SerialName(value = "altcorrection1") + Altcorrection1("altcorrection1"), + + @SerialName(value = "altcorrection2") + Altcorrection2("altcorrection2"), + + @SerialName(value = "placeholder") + Placeholder("placeholder"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/TagFilters.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/TagFilters.kt new file mode 100644 index 0000000000..b27cd5fce9 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/TagFilters.kt @@ -0,0 +1,83 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Filter hits by tags. + */ +@Serializable(TagFiltersSerializer::class) +public sealed interface TagFilters { + + public data class ListOfMixedSearchFiltersWrapper(val value: List) : TagFilters + + public data class StringWrapper(val value: String) : TagFilters + + public companion object { + + /** + * TagFilters as List + * + */ + public fun ListOfMixedSearchFilters( + value: List, + ): ListOfMixedSearchFiltersWrapper = ListOfMixedSearchFiltersWrapper( + value = value, + ) + + /** + * TagFilters as String + * + */ + public fun String( + value: String, + ): StringWrapper = StringWrapper( + value = value, + ) + } +} + +internal class TagFiltersSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("TagFilters") + + override fun serialize(encoder: Encoder, value: TagFilters) { + when (value) { + is TagFilters.ListOfMixedSearchFiltersWrapper -> ListSerializer(MixedSearchFilters.serializer()).serialize(encoder, value.value) + is TagFilters.StringWrapper -> String.serializer().serialize(encoder, value.value) + } + } + + override fun deserialize(decoder: Decoder): TagFilters { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize List + if (tree is JsonArray) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize List (error: ${e.message})") + } + } + + // deserialize String + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize String (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/TaskStatus.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/TaskStatus.kt new file mode 100644 index 0000000000..366a4f4e7d --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/TaskStatus.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* + +@Serializable +public enum class TaskStatus(public val value: kotlin.String) { + + @SerialName(value = "published") + Published("published"), + + @SerialName(value = "notPublished") + NotPublished("notPublished"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/TimeRange.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/TimeRange.kt new file mode 100644 index 0000000000..8411357173 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/TimeRange.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * TimeRange + * + * @param from Lower bound of the time range (Unix timestamp). + * @param until Upper bound of the time range (Unix timestamp). + */ +@Serializable +public data class TimeRange( + + /** Lower bound of the time range (Unix timestamp). */ + @SerialName(value = "from") val from: Int, + + /** Upper bound of the time range (Unix timestamp). */ + @SerialName(value = "until") val until: Int, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/TypoTolerance.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/TypoTolerance.kt new file mode 100644 index 0000000000..a61a128ae2 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/TypoTolerance.kt @@ -0,0 +1,76 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import com.algolia.client.exception.AlgoliaClientException +import com.algolia.client.extensions.internal.* +import kotlinx.serialization.* +import kotlinx.serialization.builtins.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* +import kotlinx.serialization.json.* + +/** + * Controls whether typo tolerance is enabled and how it is applied. + */ +@Serializable(TypoToleranceSerializer::class) +public sealed interface TypoTolerance { + + public data class BooleanWrapper(val value: Boolean) : TypoTolerance + + public companion object { + + /** + * TypoTolerance as Boolean + * + */ + public fun Boolean( + value: Boolean, + ): BooleanWrapper = BooleanWrapper( + value = value, + ) + + /** + * TypoToleranceEnum + */ + public fun of(value: TypoToleranceEnum): TypoToleranceEnum = value + } +} + +internal class TypoToleranceSerializer : KSerializer { + + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("TypoTolerance") + + override fun serialize(encoder: Encoder, value: TypoTolerance) { + when (value) { + is TypoTolerance.BooleanWrapper -> Boolean.serializer().serialize(encoder, value.value) + is TypoToleranceEnum -> TypoToleranceEnum.serializer().serialize(encoder, value) + } + } + + override fun deserialize(decoder: Decoder): TypoTolerance { + val codec = decoder.asJsonDecoder() + val tree = codec.decodeJsonElement() + + // deserialize Boolean + if (tree is JsonPrimitive) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize Boolean (error: ${e.message})") + } + } + + // deserialize TypoToleranceEnum + if (tree is JsonObject) { + try { + return codec.json.decodeFromJsonElement(tree) + } catch (e: Exception) { + // deserialization failed, continue + println("Failed to deserialize TypoToleranceEnum (error: ${e.message})") + } + } + + throw AlgoliaClientException("Failed to deserialize json element: $tree") + } +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/TypoToleranceEnum.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/TypoToleranceEnum.kt new file mode 100644 index 0000000000..c3b802f921 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/TypoToleranceEnum.kt @@ -0,0 +1,16 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* + +@Serializable +public enum class TypoToleranceEnum(public val value: kotlin.String) : TypoTolerance { + + @SerialName(value = "min") + Min("min"), + + @SerialName(value = "strict") + Strict("strict"); + + override fun toString(): kotlin.String = value +} diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/UpdateApiKeyResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/UpdateApiKeyResponse.kt new file mode 100644 index 0000000000..d6f0004b2b --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/UpdateApiKeyResponse.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * UpdateApiKeyResponse + * + * @param key The API key. + * @param updatedAt Date of last update (ISO-8601 format). + */ +@Serializable +public data class UpdateApiKeyResponse( + + /** The API key. */ + @SerialName(value = "key") val key: String, + + /** Date of last update (ISO-8601 format). */ + @SerialName(value = "updatedAt") val updatedAt: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/UpdatedAtResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/UpdatedAtResponse.kt new file mode 100644 index 0000000000..a864d309ec --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/UpdatedAtResponse.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The response with a taskID and an updatedAt timestamp. + * + * @param taskID taskID of the task to wait for. + * @param updatedAt Date of last update (ISO-8601 format). + */ +@Serializable +public data class UpdatedAtResponse( + + /** taskID of the task to wait for. */ + @SerialName(value = "taskID") val taskID: Long, + + /** Date of last update (ISO-8601 format). */ + @SerialName(value = "updatedAt") val updatedAt: String, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/UpdatedAtWithObjectIdResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/UpdatedAtWithObjectIdResponse.kt new file mode 100644 index 0000000000..acaa5411d4 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/UpdatedAtWithObjectIdResponse.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * The response with a taskID, an objectID and an updatedAt timestamp. + * + * @param taskID taskID of the task to wait for. + * @param updatedAt Date of last update (ISO-8601 format). + * @param objectID Unique identifier of the object. + */ +@Serializable +public data class UpdatedAtWithObjectIdResponse( + + /** taskID of the task to wait for. */ + @SerialName(value = "taskID") val taskID: Long? = null, + + /** Date of last update (ISO-8601 format). */ + @SerialName(value = "updatedAt") val updatedAt: String? = null, + + /** Unique identifier of the object. */ + @SerialName(value = "objectID") val objectID: String? = null, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/UpdatedRuleResponse.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/UpdatedRuleResponse.kt new file mode 100644 index 0000000000..d18e4fcbab --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/UpdatedRuleResponse.kt @@ -0,0 +1,25 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * UpdatedRuleResponse + * + * @param objectID Unique identifier of the object. + * @param updatedAt Date of last update (ISO-8601 format). + * @param taskID taskID of the task to wait for. + */ +@Serializable +public data class UpdatedRuleResponse( + + /** Unique identifier of the object. */ + @SerialName(value = "objectID") val objectID: String, + + /** Date of last update (ISO-8601 format). */ + @SerialName(value = "updatedAt") val updatedAt: String, + + /** taskID of the task to wait for. */ + @SerialName(value = "taskID") val taskID: Long, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/UserHighlightResult.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/UserHighlightResult.kt new file mode 100644 index 0000000000..14d727ee32 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/UserHighlightResult.kt @@ -0,0 +1,21 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * UserHighlightResult + * + * @param userID Show highlighted section and words matched on a query. + * @param clusterName Show highlighted section and words matched on a query. + */ +@Serializable +public data class UserHighlightResult( + + /** Show highlighted section and words matched on a query. */ + @SerialName(value = "userID") val userID: Map, + + /** Show highlighted section and words matched on a query. */ + @SerialName(value = "clusterName") val clusterName: Map, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/UserHit.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/UserHit.kt new file mode 100644 index 0000000000..7e17ad27a7 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/UserHit.kt @@ -0,0 +1,36 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * UserHit + * + * @param userID userID of the user. + * @param clusterName Name of the cluster. + * @param nbRecords Number of records in the cluster. + * @param dataSize Data size taken by all the users assigned to the cluster. + * @param objectID userID of the requested user. Same as userID. + * @param highlightResult + */ +@Serializable +public data class UserHit( + + /** userID of the user. */ + @SerialName(value = "userID") val userID: String, + + /** Name of the cluster. */ + @SerialName(value = "clusterName") val clusterName: String, + + /** Number of records in the cluster. */ + @SerialName(value = "nbRecords") val nbRecords: Int, + + /** Data size taken by all the users assigned to the cluster. */ + @SerialName(value = "dataSize") val dataSize: Int, + + /** userID of the requested user. Same as userID. */ + @SerialName(value = "objectID") val objectID: String, + + @SerialName(value = "_highlightResult") val highlightResult: UserHighlightResult, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/UserId.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/UserId.kt new file mode 100644 index 0000000000..be2b0eb12e --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/UserId.kt @@ -0,0 +1,29 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * A userID. + * + * @param userID userID of the user. + * @param clusterName Cluster on which the user is assigned. + * @param nbRecords Number of records belonging to the user. + * @param dataSize Data size used by the user. + */ +@Serializable +public data class UserId( + + /** userID of the user. */ + @SerialName(value = "userID") val userID: String, + + /** Cluster on which the user is assigned. */ + @SerialName(value = "clusterName") val clusterName: String, + + /** Number of records belonging to the user. */ + @SerialName(value = "nbRecords") val nbRecords: Int, + + /** Data size used by the user. */ + @SerialName(value = "dataSize") val dataSize: Int, +) diff --git a/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Value.kt b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Value.kt new file mode 100644 index 0000000000..9f501cb9b8 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/search/Value.kt @@ -0,0 +1,20 @@ +/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ +package com.algolia.client.model.search + +import kotlinx.serialization.* +import kotlinx.serialization.json.* + +/** + * Value + * + * @param order Pinned order of facet lists. + * @param sortRemainingBy + */ +@Serializable +public data class Value( + + /** Pinned order of facet lists. */ + @SerialName(value = "order") val order: List? = null, + + @SerialName(value = "sortRemainingBy") val sortRemainingBy: SortRemainingBy? = null, +) diff --git a/clients/algoliasearch-client-kotlin/gradle.properties b/clients/algoliasearch-client-kotlin/gradle.properties new file mode 100644 index 0000000000..f4abf76fd8 --- /dev/null +++ b/clients/algoliasearch-client-kotlin/gradle.properties @@ -0,0 +1,28 @@ +# Kotlin MPP +kotlin.code.style=official +kotlin.mpp.stability.nowarn=true + +# Lib +GROUP=com.algolia +VERSION_NAME=3.0.0-SNAPSHOT + +# OSS +SONATYPE_HOST=DEFAULT +RELEASE_SIGNING_ENABLED=true + +# POM +POM_DESCRIPTION="Algolia is a powerful search-as-a-service solution, made easy to use with API clients, UI libraries, \ + and pre-built integrations. Algolia API Client for Kotlin lets you easily use the Algolia Search \ + REST API from your JVM project, such as Android or backend implementations." +POM_URL=https://github.com/algolia/algoliasearch-client-kotlin +POM_SCM_URL=https://github.com/algolia/algoliasearch-client-kotlin +POM_SCM_CONNECTION=scm:git:git://github.com/algolia/algoliasearch-client-kotlin.git +POM_SCM_DEV_CONNECTION=scm:git:ssh://github.com/algolia/algoliasearch-client-kotlin.git +POM_LICENCE_NAME=MIT +POM_LICENCE_URL=https://www.opensource.org/licenses/mit-license.php +POM_LICENCE_DIST=repo +POM_DEVELOPER_ID=algolia +POM_DEVELOPER_NAME=The Algolia Team +POM_DEVELOPER_EMAIL=hey@algolia.com +POM_ISSUE_SYSTEM=github +POM_ISSUE_URL=https://github.com/algolia/algoliasearch-client-kotlin/issues diff --git a/tests/output/go/tests/methods/requests/analytics_test.go b/tests/output/go/tests/methods/requests/analytics_test.go new file mode 100644 index 0000000000..9a4ebda7cd --- /dev/null +++ b/tests/output/go/tests/methods/requests/analytics_test.go @@ -0,0 +1,1562 @@ +package tests + +import ( + "encoding/json" + "net/url" + "testing" + + "github.com/kinbiko/jsonassert" + "github.com/stretchr/testify/require" + + "github.com/algolia/algoliasearch-client-go/v4/algolia/analytics" +) + +func createAnalyticsClient() (*analytics.APIClient, *echoRequester) { + echo := &echoRequester{} + cfg := analytics.Configuration{ + AppID: "appID", + ApiKey: "apiKey", + Region: analytics.US, + Requester: echo, + } + client := analytics.NewClientWithConfig(cfg) + + return client, echo +} + +func TestAnalytics_Del(t *testing.T) { + client, echo := createAnalyticsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow del method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := analytics.ApiDelRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Del(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + }, + }, + { + name: "allow del method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"}}` + req := analytics.ApiDelRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Del(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestAnalytics_Get(t *testing.T) { + client, echo := createAnalyticsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow get method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := analytics.ApiGetRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Get(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + { + name: "allow get method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"}}` + req := analytics.ApiGetRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Get(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestAnalytics_GetAverageClickPosition(t *testing.T) { + client, echo := createAnalyticsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "get getAverageClickPosition with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index"}` + req := analytics.ApiGetAverageClickPositionRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetAverageClickPosition(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/clicks/averageClickPosition") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "get getAverageClickPosition with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","tags":"tag"}` + req := analytics.ApiGetAverageClickPositionRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetAverageClickPosition(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/clicks/averageClickPosition") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","tags":"tag"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestAnalytics_GetClickPositions(t *testing.T) { + client, echo := createAnalyticsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "get getClickPositions with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index"}` + req := analytics.ApiGetClickPositionsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetClickPositions(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/clicks/positions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "get getClickPositions with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","tags":"tag"}` + req := analytics.ApiGetClickPositionsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetClickPositions(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/clicks/positions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","tags":"tag"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestAnalytics_GetClickThroughRate(t *testing.T) { + client, echo := createAnalyticsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "get getClickThroughRate with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index"}` + req := analytics.ApiGetClickThroughRateRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetClickThroughRate(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/clicks/clickThroughRate") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "get getClickThroughRate with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","tags":"tag"}` + req := analytics.ApiGetClickThroughRateRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetClickThroughRate(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/clicks/clickThroughRate") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","tags":"tag"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestAnalytics_GetConversationRate(t *testing.T) { + client, echo := createAnalyticsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "get getConversationRate with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index"}` + req := analytics.ApiGetConversationRateRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetConversationRate(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/conversions/conversionRate") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "get getConversationRate with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","tags":"tag"}` + req := analytics.ApiGetConversationRateRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetConversationRate(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/conversions/conversionRate") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","tags":"tag"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestAnalytics_GetNoClickRate(t *testing.T) { + client, echo := createAnalyticsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "get getNoClickRate with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index"}` + req := analytics.ApiGetNoClickRateRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetNoClickRate(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/searches/noClickRate") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "get getNoClickRate with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","tags":"tag"}` + req := analytics.ApiGetNoClickRateRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetNoClickRate(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/searches/noClickRate") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","tags":"tag"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestAnalytics_GetNoResultsRate(t *testing.T) { + client, echo := createAnalyticsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "get getNoResultsRate with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index"}` + req := analytics.ApiGetNoResultsRateRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetNoResultsRate(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/searches/noResultRate") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "get getNoResultsRate with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","tags":"tag"}` + req := analytics.ApiGetNoResultsRateRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetNoResultsRate(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/searches/noResultRate") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","tags":"tag"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestAnalytics_GetSearchesCount(t *testing.T) { + client, echo := createAnalyticsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "get getSearchesCount with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index"}` + req := analytics.ApiGetSearchesCountRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetSearchesCount(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/searches/count") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "get getSearchesCount with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","tags":"tag"}` + req := analytics.ApiGetSearchesCountRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetSearchesCount(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/searches/count") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","tags":"tag"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestAnalytics_GetSearchesNoClicks(t *testing.T) { + client, echo := createAnalyticsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "get getSearchesNoClicks with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index"}` + req := analytics.ApiGetSearchesNoClicksRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetSearchesNoClicks(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/searches/noClicks") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "get getSearchesNoClicks with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","limit":21,"offset":42,"tags":"tag"}` + req := analytics.ApiGetSearchesNoClicksRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetSearchesNoClicks(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/searches/noClicks") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","limit":"21","offset":"42","tags":"tag"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestAnalytics_GetSearchesNoResults(t *testing.T) { + client, echo := createAnalyticsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "get getSearchesNoResults with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index"}` + req := analytics.ApiGetSearchesNoResultsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetSearchesNoResults(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/searches/noResults") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "get getSearchesNoResults with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","limit":21,"offset":42,"tags":"tag"}` + req := analytics.ApiGetSearchesNoResultsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetSearchesNoResults(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/searches/noResults") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","limit":"21","offset":"42","tags":"tag"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestAnalytics_GetStatus(t *testing.T) { + client, echo := createAnalyticsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "get getStatus with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index"}` + req := analytics.ApiGetStatusRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetStatus(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/status") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestAnalytics_GetTopCountries(t *testing.T) { + client, echo := createAnalyticsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "get getTopCountries with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index"}` + req := analytics.ApiGetTopCountriesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetTopCountries(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/countries") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "get getTopCountries with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","limit":21,"offset":42,"tags":"tag"}` + req := analytics.ApiGetTopCountriesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetTopCountries(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/countries") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","limit":"21","offset":"42","tags":"tag"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestAnalytics_GetTopFilterAttributes(t *testing.T) { + client, echo := createAnalyticsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "get getTopFilterAttributes with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index"}` + req := analytics.ApiGetTopFilterAttributesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetTopFilterAttributes(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/filters") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "get getTopFilterAttributes with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index","search":"mySearch","startDate":"1999-09-19","endDate":"2001-01-01","limit":21,"offset":42,"tags":"tag"}` + req := analytics.ApiGetTopFilterAttributesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetTopFilterAttributes(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/filters") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index","search":"mySearch","startDate":"1999-09-19","endDate":"2001-01-01","limit":"21","offset":"42","tags":"tag"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestAnalytics_GetTopFilterForAttribute(t *testing.T) { + client, echo := createAnalyticsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "get getTopFilterForAttribute with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"attribute":"myAttribute","index":"index"}` + req := analytics.ApiGetTopFilterForAttributeRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetTopFilterForAttribute(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/filters/myAttribute") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "get getTopFilterForAttribute with minimal parameters and multiple attributes", + testFunc: func(t *testing.T) { + parametersStr := `{"attribute":"myAttribute1,myAttribute2","index":"index"}` + req := analytics.ApiGetTopFilterForAttributeRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetTopFilterForAttribute(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/filters/myAttribute1%2CmyAttribute2") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "get getTopFilterForAttribute with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"attribute":"myAttribute","index":"index","search":"mySearch","startDate":"1999-09-19","endDate":"2001-01-01","limit":21,"offset":42,"tags":"tag"}` + req := analytics.ApiGetTopFilterForAttributeRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetTopFilterForAttribute(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/filters/myAttribute") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index","search":"mySearch","startDate":"1999-09-19","endDate":"2001-01-01","limit":"21","offset":"42","tags":"tag"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "get getTopFilterForAttribute with all parameters and multiple attributes", + testFunc: func(t *testing.T) { + parametersStr := `{"attribute":"myAttribute1,myAttribute2","index":"index","search":"mySearch","startDate":"1999-09-19","endDate":"2001-01-01","limit":21,"offset":42,"tags":"tag"}` + req := analytics.ApiGetTopFilterForAttributeRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetTopFilterForAttribute(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/filters/myAttribute1%2CmyAttribute2") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index","search":"mySearch","startDate":"1999-09-19","endDate":"2001-01-01","limit":"21","offset":"42","tags":"tag"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestAnalytics_GetTopFiltersNoResults(t *testing.T) { + client, echo := createAnalyticsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "get getTopFiltersNoResults with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index"}` + req := analytics.ApiGetTopFiltersNoResultsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetTopFiltersNoResults(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/filters/noResults") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "get getTopFiltersNoResults with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index","search":"mySearch","startDate":"1999-09-19","endDate":"2001-01-01","limit":21,"offset":42,"tags":"tag"}` + req := analytics.ApiGetTopFiltersNoResultsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetTopFiltersNoResults(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/filters/noResults") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index","search":"mySearch","startDate":"1999-09-19","endDate":"2001-01-01","limit":"21","offset":"42","tags":"tag"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestAnalytics_GetTopHits(t *testing.T) { + client, echo := createAnalyticsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "get getTopHits with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index"}` + req := analytics.ApiGetTopHitsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetTopHits(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/hits") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "get getTopHits with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index","search":"mySearch","clickAnalytics":true,"startDate":"1999-09-19","endDate":"2001-01-01","limit":21,"offset":42,"tags":"tag"}` + req := analytics.ApiGetTopHitsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetTopHits(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/hits") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index","search":"mySearch","clickAnalytics":"true","startDate":"1999-09-19","endDate":"2001-01-01","limit":"21","offset":"42","tags":"tag"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestAnalytics_GetTopSearches(t *testing.T) { + client, echo := createAnalyticsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "get getTopSearches with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index"}` + req := analytics.ApiGetTopSearchesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetTopSearches(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/searches") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "get getTopSearches with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index","clickAnalytics":true,"startDate":"1999-09-19","endDate":"2001-01-01","orderBy":"searchCount","direction":"asc","limit":21,"offset":42,"tags":"tag"}` + req := analytics.ApiGetTopSearchesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetTopSearches(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/searches") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index","clickAnalytics":"true","startDate":"1999-09-19","endDate":"2001-01-01","orderBy":"searchCount","direction":"asc","limit":"21","offset":"42","tags":"tag"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestAnalytics_GetUsersCount(t *testing.T) { + client, echo := createAnalyticsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "get getUsersCount with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index"}` + req := analytics.ApiGetUsersCountRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetUsersCount(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/users/count") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "get getUsersCount with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","tags":"tag"}` + req := analytics.ApiGetUsersCountRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetUsersCount(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/2/users/count") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","tags":"tag"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestAnalytics_Post(t *testing.T) { + client, echo := createAnalyticsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow post method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := analytics.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Post(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{}`) + }, + }, + { + name: "allow post method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"},"body":{"body":"parameters"}}` + req := analytics.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Post(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"body":"parameters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions can override default query parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := analytics.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []analytics.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"myQueryParameter"}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, analytics.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"myQueryParameter"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions merges query parameters with default ones", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := analytics.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []analytics.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"query2":"myQueryParameter"}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, analytics.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","query2":"myQueryParameter"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions can override default headers", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := analytics.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []analytics.Option + requestOptionHeaders := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &requestOptionHeaders)) + for k, v := range requestOptionHeaders { + opts = append(opts, analytics.HeaderParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + headers := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &headers)) + for k, v := range headers { + require.Equal(t, v, echo.header.Get(k)) + } + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions merges headers with default ones", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := analytics.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []analytics.Option + requestOptionHeaders := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &requestOptionHeaders)) + for k, v := range requestOptionHeaders { + opts = append(opts, analytics.HeaderParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + headers := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &headers)) + for k, v := range headers { + require.Equal(t, v, echo.header.Get(k)) + } + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts booleans", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := analytics.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []analytics.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"isItWorking":true}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, analytics.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","isItWorking":"true"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts integers", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := analytics.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []analytics.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":2}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, analytics.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"2"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts list of string", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := analytics.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []analytics.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":["c","d"]}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, analytics.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"c,d"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts list of booleans", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := analytics.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []analytics.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":[true,true,false]}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, analytics.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"true,true,false"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts list of integers", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := analytics.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []analytics.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":[1,2]}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, analytics.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"1,2"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestAnalytics_Put(t *testing.T) { + client, echo := createAnalyticsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow put method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := analytics.ApiPutRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Put(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{}`) + }, + }, + { + name: "allow put method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"},"body":{"body":"parameters"}}` + req := analytics.ApiPutRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Put(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"body":"parameters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} diff --git a/tests/output/go/tests/methods/requests/common.go b/tests/output/go/tests/methods/requests/common.go new file mode 100644 index 0000000000..48c4da57d8 --- /dev/null +++ b/tests/output/go/tests/methods/requests/common.go @@ -0,0 +1,35 @@ +package tests + +import ( + "bytes" + "io" + "net/http" + "net/url" +) + +type echoRequester struct { + path string + method string + body *string + header http.Header + query url.Values +} + +func (e *echoRequester) Request(req *http.Request) (*http.Response, error) { + e.path = req.URL.Path + e.method = req.Method + e.header = req.Header + e.query = req.URL.Query() + if req.Body != nil { + body, _ := io.ReadAll(req.Body) + strBody := string(body) + e.body = &strBody + } else { + e.body = nil + } + + return &http.Response{ + StatusCode: 200, + Body: io.NopCloser(bytes.NewBufferString("")), + }, nil +} diff --git a/tests/output/go/tests/methods/requests/ingestion_test.go b/tests/output/go/tests/methods/requests/ingestion_test.go new file mode 100644 index 0000000000..96e2602ae4 --- /dev/null +++ b/tests/output/go/tests/methods/requests/ingestion_test.go @@ -0,0 +1,1609 @@ +package tests + +import ( + "encoding/json" + "net/url" + "testing" + + "github.com/kinbiko/jsonassert" + "github.com/stretchr/testify/require" + + "github.com/algolia/algoliasearch-client-go/v4/algolia/ingestion" +) + +func createIngestionClient() (*ingestion.APIClient, *echoRequester) { + echo := &echoRequester{} + cfg := ingestion.Configuration{ + AppID: "appID", + ApiKey: "apiKey", + Region: ingestion.US, + Requester: echo, + } + client := ingestion.NewClientWithConfig(cfg) + + return client, echo +} + +func TestIngestion_CreateAuthentication(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "createAuthenticationOAuth", + testFunc: func(t *testing.T) { + parametersStr := `{"type":"oauth","name":"authName","input":{"url":"http://test.oauth","client_id":"myID","client_secret":"mySecret"}}` + req := ingestion.ApiCreateAuthenticationRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.CreateAuthentication(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/authentications") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"type":"oauth","name":"authName","input":{"url":"http://test.oauth","client_id":"myID","client_secret":"mySecret"}}`) + }, + }, + { + name: "createAuthenticationAlgolia", + testFunc: func(t *testing.T) { + parametersStr := `{"type":"algolia","name":"authName","input":{"appID":"myappID","apiKey":"randomApiKey"}}` + req := ingestion.ApiCreateAuthenticationRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.CreateAuthentication(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/authentications") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"type":"algolia","name":"authName","input":{"appID":"myappID","apiKey":"randomApiKey"}}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_CreateDestination(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "createDestination", + testFunc: func(t *testing.T) { + parametersStr := `{"type":"search","name":"destinationName","input":{"indexPrefix":"prefix_"},"authenticationID":"6c02aeb1-775e-418e-870b-1faccd4b2c0f"}` + req := ingestion.ApiCreateDestinationRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.CreateDestination(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/destinations") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"type":"search","name":"destinationName","input":{"indexPrefix":"prefix_"},"authenticationID":"6c02aeb1-775e-418e-870b-1faccd4b2c0f"}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_CreateSource(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "createSource", + testFunc: func(t *testing.T) { + parametersStr := `{"type":"commercetools","name":"sourceName","input":{"storeKeys":["myStore"],"locales":["de"],"url":"http://commercetools.com","projectKey":"keyID"},"authenticationID":"6c02aeb1-775e-418e-870b-1faccd4b2c0f"}` + req := ingestion.ApiCreateSourceRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.CreateSource(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/sources") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"type":"commercetools","name":"sourceName","input":{"storeKeys":["myStore"],"locales":["de"],"url":"http://commercetools.com","projectKey":"keyID"},"authenticationID":"6c02aeb1-775e-418e-870b-1faccd4b2c0f"}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_CreateTask(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "createTaskOnDemand", + testFunc: func(t *testing.T) { + parametersStr := `{"sourceID":"search","destinationID":"destinationName","trigger":{"type":"onDemand"},"action":"replace"}` + req := ingestion.ApiCreateTaskRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.CreateTask(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/tasks") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"sourceID":"search","destinationID":"destinationName","trigger":{"type":"onDemand"},"action":"replace"}`) + }, + }, + { + name: "createTaskSchedule", + testFunc: func(t *testing.T) { + parametersStr := `{"sourceID":"search","destinationID":"destinationName","trigger":{"type":"schedule","cron":"* * * * *"},"action":"replace"}` + req := ingestion.ApiCreateTaskRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.CreateTask(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/tasks") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"sourceID":"search","destinationID":"destinationName","trigger":{"type":"schedule","cron":"* * * * *"},"action":"replace"}`) + }, + }, + { + name: "createTaskSubscription", + testFunc: func(t *testing.T) { + parametersStr := `{"sourceID":"search","destinationID":"destinationName","trigger":{"type":"onDemand"},"action":"replace"}` + req := ingestion.ApiCreateTaskRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.CreateTask(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/tasks") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"sourceID":"search","destinationID":"destinationName","trigger":{"type":"onDemand"},"action":"replace"}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_Del(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow del method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := ingestion.ApiDelRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Del(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + }, + }, + { + name: "allow del method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"}}` + req := ingestion.ApiDelRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Del(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_DeleteAuthentication(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "deleteAuthentication", + testFunc: func(t *testing.T) { + parametersStr := `{"authenticationID":"6c02aeb1-775e-418e-870b-1faccd4b2c0f"}` + req := ingestion.ApiDeleteAuthenticationRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.DeleteAuthentication(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/authentications/6c02aeb1-775e-418e-870b-1faccd4b2c0f") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_DeleteDestination(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "deleteDestination", + testFunc: func(t *testing.T) { + parametersStr := `{"destinationID":"6c02aeb1-775e-418e-870b-1faccd4b2c0f"}` + req := ingestion.ApiDeleteDestinationRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.DeleteDestination(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/destinations/6c02aeb1-775e-418e-870b-1faccd4b2c0f") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_DeleteSource(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "deleteSource", + testFunc: func(t *testing.T) { + parametersStr := `{"sourceID":"6c02aeb1-775e-418e-870b-1faccd4b2c0f"}` + req := ingestion.ApiDeleteSourceRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.DeleteSource(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/sources/6c02aeb1-775e-418e-870b-1faccd4b2c0f") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_DeleteTask(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "deleteTask", + testFunc: func(t *testing.T) { + parametersStr := `{"taskID":"6c02aeb1-775e-418e-870b-1faccd4b2c0f"}` + req := ingestion.ApiDeleteTaskRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.DeleteTask(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/tasks/6c02aeb1-775e-418e-870b-1faccd4b2c0f") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_DisableTask(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "disableTask", + testFunc: func(t *testing.T) { + parametersStr := `{"taskID":"6c02aeb1-775e-418e-870b-1faccd4b2c0f"}` + req := ingestion.ApiDisableTaskRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.DisableTask(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/tasks/6c02aeb1-775e-418e-870b-1faccd4b2c0f/disable") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + require.Empty(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_EnableTask(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "enableTask", + testFunc: func(t *testing.T) { + parametersStr := `{"taskID":"6c02aeb1-775e-418e-870b-1faccd4b2c0f"}` + req := ingestion.ApiEnableTaskRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.EnableTask(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/tasks/6c02aeb1-775e-418e-870b-1faccd4b2c0f/enable") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + require.Empty(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_Get(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow get method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := ingestion.ApiGetRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Get(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + { + name: "allow get method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"}}` + req := ingestion.ApiGetRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Get(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_GetAuthentication(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "getAuthentication", + testFunc: func(t *testing.T) { + parametersStr := `{"authenticationID":"6c02aeb1-775e-418e-870b-1faccd4b2c0f"}` + req := ingestion.ApiGetAuthenticationRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetAuthentication(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/authentications/6c02aeb1-775e-418e-870b-1faccd4b2c0f") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_GetAuthentications(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "getAuthentications", + testFunc: func(t *testing.T) { + parametersStr := `{}` + req := ingestion.ApiGetAuthenticationsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetAuthentications(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/authentications") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_GetDestination(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "getDestination", + testFunc: func(t *testing.T) { + parametersStr := `{"destinationID":"6c02aeb1-775e-418e-870b-1faccd4b2c0f"}` + req := ingestion.ApiGetDestinationRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetDestination(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/destinations/6c02aeb1-775e-418e-870b-1faccd4b2c0f") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_GetDestinations(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "getDestinations", + testFunc: func(t *testing.T) { + parametersStr := `{}` + req := ingestion.ApiGetDestinationsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetDestinations(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/destinations") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_GetEvent(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "getEvent", + testFunc: func(t *testing.T) { + parametersStr := `{"runID":"6c02aeb1-775e-418e-870b-1faccd4b2c0f","eventID":"6c02aeb1-775e-418e-870b-1faccd4b2c0c"}` + req := ingestion.ApiGetEventRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetEvent(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/runs/6c02aeb1-775e-418e-870b-1faccd4b2c0f/events/6c02aeb1-775e-418e-870b-1faccd4b2c0c") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_GetEvents(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "getEvents", + testFunc: func(t *testing.T) { + parametersStr := `{"runID":"6c02aeb1-775e-418e-870b-1faccd4b2c0f"}` + req := ingestion.ApiGetEventsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetEvents(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/runs/6c02aeb1-775e-418e-870b-1faccd4b2c0f/events") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_GetRun(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "getRun", + testFunc: func(t *testing.T) { + parametersStr := `{"runID":"6c02aeb1-775e-418e-870b-1faccd4b2c0f"}` + req := ingestion.ApiGetRunRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetRun(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/runs/6c02aeb1-775e-418e-870b-1faccd4b2c0f") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_GetRuns(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "getRuns", + testFunc: func(t *testing.T) { + parametersStr := `{}` + req := ingestion.ApiGetRunsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetRuns(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/runs") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_GetSource(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "getSource", + testFunc: func(t *testing.T) { + parametersStr := `{"sourceID":"6c02aeb1-775e-418e-870b-1faccd4b2c0f"}` + req := ingestion.ApiGetSourceRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetSource(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/sources/6c02aeb1-775e-418e-870b-1faccd4b2c0f") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_GetSources(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "getSources", + testFunc: func(t *testing.T) { + parametersStr := `{}` + req := ingestion.ApiGetSourcesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetSources(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/sources") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_GetTask(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "getTask", + testFunc: func(t *testing.T) { + parametersStr := `{"taskID":"6c02aeb1-775e-418e-870b-1faccd4b2c0f"}` + req := ingestion.ApiGetTaskRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetTask(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/tasks/6c02aeb1-775e-418e-870b-1faccd4b2c0f") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_GetTasks(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "getTasks", + testFunc: func(t *testing.T) { + parametersStr := `{}` + req := ingestion.ApiGetTasksRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetTasks(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/tasks") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_Post(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow post method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := ingestion.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Post(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{}`) + }, + }, + { + name: "allow post method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"},"body":{"body":"parameters"}}` + req := ingestion.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Post(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"body":"parameters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions can override default query parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := ingestion.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []ingestion.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"myQueryParameter"}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, ingestion.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"myQueryParameter"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions merges query parameters with default ones", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := ingestion.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []ingestion.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"query2":"myQueryParameter"}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, ingestion.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","query2":"myQueryParameter"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions can override default headers", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := ingestion.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []ingestion.Option + requestOptionHeaders := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &requestOptionHeaders)) + for k, v := range requestOptionHeaders { + opts = append(opts, ingestion.HeaderParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + headers := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &headers)) + for k, v := range headers { + require.Equal(t, v, echo.header.Get(k)) + } + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions merges headers with default ones", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := ingestion.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []ingestion.Option + requestOptionHeaders := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &requestOptionHeaders)) + for k, v := range requestOptionHeaders { + opts = append(opts, ingestion.HeaderParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + headers := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &headers)) + for k, v := range headers { + require.Equal(t, v, echo.header.Get(k)) + } + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts booleans", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := ingestion.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []ingestion.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"isItWorking":true}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, ingestion.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","isItWorking":"true"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts integers", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := ingestion.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []ingestion.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":2}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, ingestion.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"2"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts list of string", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := ingestion.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []ingestion.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":["c","d"]}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, ingestion.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"c,d"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts list of booleans", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := ingestion.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []ingestion.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":[true,true,false]}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, ingestion.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"true,true,false"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts list of integers", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := ingestion.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []ingestion.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":[1,2]}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, ingestion.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"1,2"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_Put(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow put method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := ingestion.ApiPutRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Put(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{}`) + }, + }, + { + name: "allow put method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"},"body":{"body":"parameters"}}` + req := ingestion.ApiPutRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Put(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"body":"parameters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_RunTask(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "runTask", + testFunc: func(t *testing.T) { + parametersStr := `{"taskID":"6c02aeb1-775e-418e-870b-1faccd4b2c0f"}` + req := ingestion.ApiRunTaskRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.RunTask(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/tasks/6c02aeb1-775e-418e-870b-1faccd4b2c0f/run") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + require.Empty(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_SearchAuthentications(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "searchAuthentications", + testFunc: func(t *testing.T) { + parametersStr := `{"authenticationIDs":["6c02aeb1-775e-418e-870b-1faccd4b2c0f","947ac9c4-7e58-4c87-b1e7-14a68e99699a"]}` + req := ingestion.ApiSearchAuthenticationsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SearchAuthentications(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/authentications/search") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"authenticationIDs":["6c02aeb1-775e-418e-870b-1faccd4b2c0f","947ac9c4-7e58-4c87-b1e7-14a68e99699a"]}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_SearchDestinations(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "searchDestinations", + testFunc: func(t *testing.T) { + parametersStr := `{"destinationIDs":["6c02aeb1-775e-418e-870b-1faccd4b2c0f","947ac9c4-7e58-4c87-b1e7-14a68e99699a"]}` + req := ingestion.ApiSearchDestinationsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SearchDestinations(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/destinations/search") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"destinationIDs":["6c02aeb1-775e-418e-870b-1faccd4b2c0f","947ac9c4-7e58-4c87-b1e7-14a68e99699a"]}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_SearchSources(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "searchSources", + testFunc: func(t *testing.T) { + parametersStr := `{"sourceIDs":["6c02aeb1-775e-418e-870b-1faccd4b2c0f","947ac9c4-7e58-4c87-b1e7-14a68e99699a"]}` + req := ingestion.ApiSearchSourcesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SearchSources(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/sources/search") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"sourceIDs":["6c02aeb1-775e-418e-870b-1faccd4b2c0f","947ac9c4-7e58-4c87-b1e7-14a68e99699a"]}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_SearchTasks(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "searchTasks", + testFunc: func(t *testing.T) { + parametersStr := `{"taskIDs":["6c02aeb1-775e-418e-870b-1faccd4b2c0f","947ac9c4-7e58-4c87-b1e7-14a68e99699a"]}` + req := ingestion.ApiSearchTasksRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SearchTasks(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/tasks/search") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"taskIDs":["6c02aeb1-775e-418e-870b-1faccd4b2c0f","947ac9c4-7e58-4c87-b1e7-14a68e99699a"]}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_UpdateAuthentication(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "updateAuthentication", + testFunc: func(t *testing.T) { + parametersStr := `{"authenticationID":"6c02aeb1-775e-418e-870b-1faccd4b2c0f","authenticationUpdate":{"name":"newName"}}` + req := ingestion.ApiUpdateAuthenticationRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.UpdateAuthentication(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/authentications/6c02aeb1-775e-418e-870b-1faccd4b2c0f") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"name":"newName"}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_UpdateDestination(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "updateDestination", + testFunc: func(t *testing.T) { + parametersStr := `{"destinationID":"6c02aeb1-775e-418e-870b-1faccd4b2c0f","destinationUpdate":{"name":"newName"}}` + req := ingestion.ApiUpdateDestinationRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.UpdateDestination(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/destinations/6c02aeb1-775e-418e-870b-1faccd4b2c0f") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"name":"newName"}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_UpdateSource(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "updateSource", + testFunc: func(t *testing.T) { + parametersStr := `{"sourceID":"6c02aeb1-775e-418e-870b-1faccd4b2c0f","sourceUpdate":{"name":"newName"}}` + req := ingestion.ApiUpdateSourceRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.UpdateSource(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/sources/6c02aeb1-775e-418e-870b-1faccd4b2c0f") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"name":"newName"}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestIngestion_UpdateTask(t *testing.T) { + client, echo := createIngestionClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "updateTask", + testFunc: func(t *testing.T) { + parametersStr := `{"taskID":"6c02aeb1-775e-418e-870b-1faccd4b2c0f","taskUpdate":{"enabled":false}}` + req := ingestion.ApiUpdateTaskRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.UpdateTask(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/tasks/6c02aeb1-775e-418e-870b-1faccd4b2c0f") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"enabled":false}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} diff --git a/tests/output/go/tests/methods/requests/insights_test.go b/tests/output/go/tests/methods/requests/insights_test.go new file mode 100644 index 0000000000..3a98826bfa --- /dev/null +++ b/tests/output/go/tests/methods/requests/insights_test.go @@ -0,0 +1,554 @@ +package tests + +import ( + "encoding/json" + "net/url" + "testing" + + "github.com/kinbiko/jsonassert" + "github.com/stretchr/testify/require" + + "github.com/algolia/algoliasearch-client-go/v4/algolia/insights" +) + +func createInsightsClient() (*insights.APIClient, *echoRequester) { + echo := &echoRequester{} + cfg := insights.Configuration{ + AppID: "appID", + ApiKey: "apiKey", + Region: insights.US, + Requester: echo, + } + client := insights.NewClientWithConfig(cfg) + + return client, echo +} + +func TestInsights_Del(t *testing.T) { + client, echo := createInsightsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow del method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := insights.ApiDelRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Del(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + }, + }, + { + name: "allow del method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"}}` + req := insights.ApiDelRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Del(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestInsights_Get(t *testing.T) { + client, echo := createInsightsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow get method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := insights.ApiGetRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Get(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + { + name: "allow get method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"}}` + req := insights.ApiGetRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Get(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestInsights_Post(t *testing.T) { + client, echo := createInsightsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow post method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := insights.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Post(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{}`) + }, + }, + { + name: "allow post method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"},"body":{"body":"parameters"}}` + req := insights.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Post(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"body":"parameters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions can override default query parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := insights.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []insights.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"myQueryParameter"}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, insights.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"myQueryParameter"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions merges query parameters with default ones", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := insights.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []insights.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"query2":"myQueryParameter"}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, insights.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","query2":"myQueryParameter"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions can override default headers", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := insights.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []insights.Option + requestOptionHeaders := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &requestOptionHeaders)) + for k, v := range requestOptionHeaders { + opts = append(opts, insights.HeaderParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + headers := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &headers)) + for k, v := range headers { + require.Equal(t, v, echo.header.Get(k)) + } + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions merges headers with default ones", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := insights.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []insights.Option + requestOptionHeaders := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &requestOptionHeaders)) + for k, v := range requestOptionHeaders { + opts = append(opts, insights.HeaderParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + headers := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &headers)) + for k, v := range headers { + require.Equal(t, v, echo.header.Get(k)) + } + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts booleans", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := insights.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []insights.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"isItWorking":true}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, insights.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","isItWorking":"true"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts integers", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := insights.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []insights.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":2}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, insights.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"2"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts list of string", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := insights.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []insights.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":["c","d"]}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, insights.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"c,d"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts list of booleans", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := insights.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []insights.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":[true,true,false]}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, insights.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"true,true,false"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts list of integers", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := insights.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []insights.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":[1,2]}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, insights.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"1,2"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestInsights_PushEvents(t *testing.T) { + client, echo := createInsightsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "pushEvents", + testFunc: func(t *testing.T) { + parametersStr := `{"events":[{"eventType":"click","eventName":"Product Clicked","index":"products","userToken":"user-123456","timestamp":1641290601962,"objectIDs":["9780545139700","9780439784542"],"queryID":"43b15df305339e827f0ac0bdc5ebcaa7","positions":[7,6]},{"eventType":"view","eventName":"Product Detail Page Viewed","index":"products","userToken":"user-123456","timestamp":1641290601962,"objectIDs":["9780545139700","9780439784542"]},{"eventType":"conversion","eventName":"Product Purchased","index":"products","userToken":"user-123456","timestamp":1641290601962,"objectIDs":["9780545139700","9780439784542"],"queryID":"43b15df305339e827f0ac0bdc5ebcaa7"}]}` + req := insights.ApiPushEventsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.PushEvents(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/events") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"events":[{"eventType":"click","eventName":"Product Clicked","index":"products","userToken":"user-123456","timestamp":1641290601962,"objectIDs":["9780545139700","9780439784542"],"queryID":"43b15df305339e827f0ac0bdc5ebcaa7","positions":[7,6]},{"eventType":"view","eventName":"Product Detail Page Viewed","index":"products","userToken":"user-123456","timestamp":1641290601962,"objectIDs":["9780545139700","9780439784542"]},{"eventType":"conversion","eventName":"Product Purchased","index":"products","userToken":"user-123456","timestamp":1641290601962,"objectIDs":["9780545139700","9780439784542"],"queryID":"43b15df305339e827f0ac0bdc5ebcaa7"}]}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestInsights_Put(t *testing.T) { + client, echo := createInsightsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow put method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := insights.ApiPutRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Put(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{}`) + }, + }, + { + name: "allow put method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"},"body":{"body":"parameters"}}` + req := insights.ApiPutRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Put(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"body":"parameters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} diff --git a/tests/output/go/tests/methods/requests/personalization_test.go b/tests/output/go/tests/methods/requests/personalization_test.go new file mode 100644 index 0000000000..6bf9226dc2 --- /dev/null +++ b/tests/output/go/tests/methods/requests/personalization_test.go @@ -0,0 +1,653 @@ +package tests + +import ( + "encoding/json" + "net/url" + "testing" + + "github.com/kinbiko/jsonassert" + "github.com/stretchr/testify/require" + + "github.com/algolia/algoliasearch-client-go/v4/algolia/personalization" +) + +func createPersonalizationClient() (*personalization.APIClient, *echoRequester) { + echo := &echoRequester{} + cfg := personalization.Configuration{ + AppID: "appID", + ApiKey: "apiKey", + Region: personalization.US, + Requester: echo, + } + client := personalization.NewClientWithConfig(cfg) + + return client, echo +} + +func TestPersonalization_Del(t *testing.T) { + client, echo := createPersonalizationClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow del method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := personalization.ApiDelRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Del(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + }, + }, + { + name: "allow del method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"}}` + req := personalization.ApiDelRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Del(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestPersonalization_DeleteUserProfile(t *testing.T) { + client, echo := createPersonalizationClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "delete deleteUserProfile", + testFunc: func(t *testing.T) { + parametersStr := `{"userToken":"UserToken"}` + req := personalization.ApiDeleteUserProfileRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.DeleteUserProfile(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/profiles/UserToken") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestPersonalization_Get(t *testing.T) { + client, echo := createPersonalizationClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow get method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := personalization.ApiGetRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Get(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + { + name: "allow get method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"}}` + req := personalization.ApiGetRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Get(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestPersonalization_GetPersonalizationStrategy(t *testing.T) { + client, echo := createPersonalizationClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "get getPersonalizationStrategy", + testFunc: func(t *testing.T) { + parametersStr := `{}` + req := personalization.ApiGetPersonalizationStrategyRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetPersonalizationStrategy(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/strategies/personalization") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestPersonalization_GetUserTokenProfile(t *testing.T) { + client, echo := createPersonalizationClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "get getUserTokenProfile", + testFunc: func(t *testing.T) { + parametersStr := `{"userToken":"UserToken"}` + req := personalization.ApiGetUserTokenProfileRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetUserTokenProfile(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/profiles/personalization/UserToken") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestPersonalization_Post(t *testing.T) { + client, echo := createPersonalizationClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow post method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := personalization.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Post(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{}`) + }, + }, + { + name: "allow post method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"},"body":{"body":"parameters"}}` + req := personalization.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Post(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"body":"parameters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions can override default query parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := personalization.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []personalization.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"myQueryParameter"}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, personalization.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"myQueryParameter"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions merges query parameters with default ones", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := personalization.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []personalization.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"query2":"myQueryParameter"}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, personalization.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","query2":"myQueryParameter"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions can override default headers", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := personalization.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []personalization.Option + requestOptionHeaders := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &requestOptionHeaders)) + for k, v := range requestOptionHeaders { + opts = append(opts, personalization.HeaderParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + headers := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &headers)) + for k, v := range headers { + require.Equal(t, v, echo.header.Get(k)) + } + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions merges headers with default ones", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := personalization.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []personalization.Option + requestOptionHeaders := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &requestOptionHeaders)) + for k, v := range requestOptionHeaders { + opts = append(opts, personalization.HeaderParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + headers := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &headers)) + for k, v := range headers { + require.Equal(t, v, echo.header.Get(k)) + } + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts booleans", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := personalization.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []personalization.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"isItWorking":true}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, personalization.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","isItWorking":"true"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts integers", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := personalization.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []personalization.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":2}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, personalization.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"2"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts list of string", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := personalization.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []personalization.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":["c","d"]}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, personalization.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"c,d"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts list of booleans", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := personalization.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []personalization.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":[true,true,false]}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, personalization.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"true,true,false"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts list of integers", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := personalization.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []personalization.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":[1,2]}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, personalization.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"1,2"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestPersonalization_Put(t *testing.T) { + client, echo := createPersonalizationClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow put method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := personalization.ApiPutRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Put(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{}`) + }, + }, + { + name: "allow put method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"},"body":{"body":"parameters"}}` + req := personalization.ApiPutRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Put(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"body":"parameters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestPersonalization_SetPersonalizationStrategy(t *testing.T) { + client, echo := createPersonalizationClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "set setPersonalizationStrategy", + testFunc: func(t *testing.T) { + parametersStr := `{"eventScoring":[{"score":42,"eventName":"Algolia","eventType":"Event"}],"facetScoring":[{"score":42,"facetName":"Event"}],"personalizationImpact":42}` + req := personalization.ApiSetPersonalizationStrategyRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SetPersonalizationStrategy(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/strategies/personalization") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"eventScoring":[{"score":42,"eventName":"Algolia","eventType":"Event"}],"facetScoring":[{"score":42,"facetName":"Event"}],"personalizationImpact":42}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} diff --git a/tests/output/go/tests/methods/requests/predict_test.go b/tests/output/go/tests/methods/requests/predict_test.go new file mode 100644 index 0000000000..88b29b4a68 --- /dev/null +++ b/tests/output/go/tests/methods/requests/predict_test.go @@ -0,0 +1,1354 @@ +package tests + +import ( + "encoding/json" + "net/url" + "testing" + + "github.com/kinbiko/jsonassert" + "github.com/stretchr/testify/require" + + "github.com/algolia/algoliasearch-client-go/v4/algolia/predict" +) + +func createPredictClient() (*predict.APIClient, *echoRequester) { + echo := &echoRequester{} + cfg := predict.Configuration{ + AppID: "appID", + ApiKey: "apiKey", + Region: predict.EU, + Requester: echo, + } + client := predict.NewClientWithConfig(cfg) + + return client, echo +} + +func TestPredict_ActivateModelInstance(t *testing.T) { + client, echo := createPredictClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "activate a model instance", + testFunc: func(t *testing.T) { + parametersStr := `{"type":"funnel_stage","name":"Shopping stage for EU users","sourceID":"0200030-129930","index":"Products Production","modelAttributes":[]}` + req := predict.ApiActivateModelInstanceRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.ActivateModelInstance(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/predict/models") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"type":"funnel_stage","name":"Shopping stage for EU users","sourceID":"0200030-129930","index":"Products Production","modelAttributes":[]}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestPredict_CreateSegment(t *testing.T) { + client, echo := createPredictClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "create segment with required params", + testFunc: func(t *testing.T) { + t.Skip("skipping test for go client") + parametersStr := `{"name":"segment1","conditions":{"operator":"AND","operands":[{"name":"predictions.order_value","filters":[{"operator":"GT","value":200}]}]}}` + req := predict.ApiCreateSegmentRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.CreateSegment(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/segments") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"name":"segment1","conditions":{"operator":"AND","operands":[{"name":"predictions.order_value","filters":[{"operator":"GT","value":200}]}]}}`) + }, + }, + { + name: "create segment with filter probability", + testFunc: func(t *testing.T) { + parametersStr := `{"name":"segment1","conditions":{"operator":"AND","operands":[{"name":"predictions.affinities.color","filters":[{"operator":"EQ","value":"red","probability":{"GTE":0.5,"LTE":1}}]}]}}` + req := predict.ApiCreateSegmentRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.CreateSegment(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/segments") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"name":"segment1","conditions":{"operator":"AND","operands":[{"name":"predictions.affinities.color","filters":[{"operator":"EQ","value":"red","probability":{"GTE":0.5,"LTE":1}}]}]}}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestPredict_Del(t *testing.T) { + client, echo := createPredictClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow del method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := predict.ApiDelRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Del(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + }, + }, + { + name: "allow del method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"}}` + req := predict.ApiDelRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Del(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestPredict_DeleteModelInstance(t *testing.T) { + client, echo := createPredictClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "delete a model instance", + testFunc: func(t *testing.T) { + parametersStr := `{"modelID":"model1"}` + req := predict.ApiDeleteModelInstanceRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.DeleteModelInstance(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/predict/models/model1") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestPredict_DeleteSegment(t *testing.T) { + client, echo := createPredictClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "delete a segments configuration", + testFunc: func(t *testing.T) { + parametersStr := `{"segmentID":"segment1"}` + req := predict.ApiDeleteSegmentRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.DeleteSegment(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/segments/segment1") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestPredict_DeleteUserProfile(t *testing.T) { + client, echo := createPredictClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "deleteUserProfile", + testFunc: func(t *testing.T) { + parametersStr := `{"userID":"user1"}` + req := predict.ApiDeleteUserProfileRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.DeleteUserProfile(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/users/user1") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestPredict_FetchAllSegments(t *testing.T) { + client, echo := createPredictClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "fetchAllSegments with no segmentType", + testFunc: func(t *testing.T) { + parametersStr := `{}` + req := predict.ApiFetchAllSegmentsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.FetchAllSegments(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/segments") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + { + name: "fetchAllSegments with segmentType custom", + testFunc: func(t *testing.T) { + parametersStr := `{"type":"custom"}` + req := predict.ApiFetchAllSegmentsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.FetchAllSegments(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/segments") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"type":"custom"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "fetchAllSegments with segmentType computed", + testFunc: func(t *testing.T) { + parametersStr := `{"type":"computed"}` + req := predict.ApiFetchAllSegmentsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.FetchAllSegments(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/segments") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"type":"computed"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestPredict_FetchAllUserProfiles(t *testing.T) { + client, echo := createPredictClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "fetchAllUserProfiles with minimal parameters for modelsToRetrieve", + testFunc: func(t *testing.T) { + parametersStr := `{"modelsToRetrieve":["funnel_stage","order_value","affinities"]}` + req := predict.ApiFetchAllUserProfilesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.FetchAllUserProfiles(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/users") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"modelsToRetrieve":["funnel_stage","order_value","affinities"]}`) + }, + }, + { + name: "fetchAllUserProfiles with minimal parameters for typesToRetrieve", + testFunc: func(t *testing.T) { + parametersStr := `{"typesToRetrieve":["properties","segments"]}` + req := predict.ApiFetchAllUserProfilesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.FetchAllUserProfiles(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/users") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"typesToRetrieve":["properties","segments"]}`) + }, + }, + { + name: "fetchAllUserProfiles with a limit", + testFunc: func(t *testing.T) { + parametersStr := `{"limit":10}` + req := predict.ApiFetchAllUserProfilesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.FetchAllUserProfiles(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/users") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"limit":10}`) + }, + }, + { + name: "fetchAllUserProfiles with a nextPageToken", + testFunc: func(t *testing.T) { + parametersStr := `{"nextPageToken":"nextPageTokenExample123"}` + req := predict.ApiFetchAllUserProfilesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.FetchAllUserProfiles(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/users") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"nextPageToken":"nextPageTokenExample123"}`) + }, + }, + { + name: "fetchAllUserProfiles with a previousPageToken", + testFunc: func(t *testing.T) { + parametersStr := `{"previousPageToken":"previousPageTokenExample123"}` + req := predict.ApiFetchAllUserProfilesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.FetchAllUserProfiles(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/users") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"previousPageToken":"previousPageTokenExample123"}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestPredict_FetchSegment(t *testing.T) { + client, echo := createPredictClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "fetchSegment with user ID", + testFunc: func(t *testing.T) { + parametersStr := `{"segmentID":"segment1"}` + req := predict.ApiFetchSegmentRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.FetchSegment(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/segments/segment1") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestPredict_FetchUserProfile(t *testing.T) { + client, echo := createPredictClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "fetchUserProfile with minimal parameters for modelsToRetrieve", + testFunc: func(t *testing.T) { + parametersStr := `{"userID":"user1","params":{"modelsToRetrieve":["funnel_stage","order_value","affinities"]}}` + req := predict.ApiFetchUserProfileRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.FetchUserProfile(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/users/user1/fetch") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"modelsToRetrieve":["funnel_stage","order_value","affinities"]}`) + }, + }, + { + name: "fetchUserProfile with minimal parameters for typesToRetrieve", + testFunc: func(t *testing.T) { + parametersStr := `{"userID":"user1","params":{"typesToRetrieve":["properties","segments"]}}` + req := predict.ApiFetchUserProfileRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.FetchUserProfile(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/users/user1/fetch") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"typesToRetrieve":["properties","segments"]}`) + }, + }, + { + name: "fetchUserProfile with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"userID":"user1","params":{"modelsToRetrieve":["funnel_stage","order_value","affinities"],"typesToRetrieve":["properties","segments"]}}` + req := predict.ApiFetchUserProfileRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.FetchUserProfile(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/users/user1/fetch") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"modelsToRetrieve":["funnel_stage","order_value","affinities"],"typesToRetrieve":["properties","segments"]}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestPredict_Get(t *testing.T) { + client, echo := createPredictClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow get method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := predict.ApiGetRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Get(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + { + name: "allow get method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"}}` + req := predict.ApiGetRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Get(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestPredict_GetAvailableModelTypes(t *testing.T) { + client, echo := createPredictClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "get available model types", + testFunc: func(t *testing.T) { + parametersStr := `{}` + req := predict.ApiGetAvailableModelTypesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetAvailableModelTypes(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/predict/modeltypes") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestPredict_GetModelInstanceConfig(t *testing.T) { + client, echo := createPredictClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "get configurations for a model instance", + testFunc: func(t *testing.T) { + parametersStr := `{"modelID":"model1"}` + req := predict.ApiGetModelInstanceConfigRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetModelInstanceConfig(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/predict/models/model1") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestPredict_GetModelInstances(t *testing.T) { + client, echo := createPredictClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "get a list of model instances", + testFunc: func(t *testing.T) { + parametersStr := `{}` + req := predict.ApiGetModelInstancesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetModelInstances(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/predict/models") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestPredict_GetModelMetrics(t *testing.T) { + client, echo := createPredictClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "get metrics for a model instance", + testFunc: func(t *testing.T) { + parametersStr := `{"modelID":"model1"}` + req := predict.ApiGetModelMetricsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetModelMetrics(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/predict/models/model1/metrics") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestPredict_GetSegmentUsers(t *testing.T) { + client, echo := createPredictClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "getSegmentUsers with minimal parameters for modelsToRetrieve", + testFunc: func(t *testing.T) { + parametersStr := `{"segmentID":"segmentID1","fetchAllUserProfilesParams":{"modelsToRetrieve":["funnel_stage"]}}` + req := predict.ApiGetSegmentUsersRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetSegmentUsers(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/segments/segmentID1/users") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"modelsToRetrieve":["funnel_stage"]}`) + }, + }, + { + name: "getSegmentUsers with minimal parameters for typesToRetrieve", + testFunc: func(t *testing.T) { + parametersStr := `{"segmentID":"segmentID1","fetchAllUserProfilesParams":{"typesToRetrieve":["properties"]}}` + req := predict.ApiGetSegmentUsersRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetSegmentUsers(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/segments/segmentID1/users") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"typesToRetrieve":["properties"]}`) + }, + }, + { + name: "getSegmentUsers with a limit", + testFunc: func(t *testing.T) { + parametersStr := `{"segmentID":"segmentID1","fetchAllUserProfilesParams":{"limit":10}}` + req := predict.ApiGetSegmentUsersRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetSegmentUsers(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/segments/segmentID1/users") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"limit":10}`) + }, + }, + { + name: "getSegmentUsers with a nextPageToken", + testFunc: func(t *testing.T) { + parametersStr := `{"segmentID":"segmentID1","fetchAllUserProfilesParams":{"nextPageToken":"nextPageTokenExample123"}}` + req := predict.ApiGetSegmentUsersRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetSegmentUsers(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/segments/segmentID1/users") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"nextPageToken":"nextPageTokenExample123"}`) + }, + }, + { + name: "getSegmentUsers with a previousPageToken", + testFunc: func(t *testing.T) { + parametersStr := `{"segmentID":"segmentID1","fetchAllUserProfilesParams":{"previousPageToken":"previousPageTokenExample123"}}` + req := predict.ApiGetSegmentUsersRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetSegmentUsers(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/segments/segmentID1/users") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"previousPageToken":"previousPageTokenExample123"}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestPredict_Post(t *testing.T) { + client, echo := createPredictClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow post method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := predict.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Post(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{}`) + }, + }, + { + name: "allow post method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"},"body":{"body":"parameters"}}` + req := predict.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Post(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"body":"parameters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions can override default query parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := predict.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []predict.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"myQueryParameter"}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, predict.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"myQueryParameter"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions merges query parameters with default ones", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := predict.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []predict.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"query2":"myQueryParameter"}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, predict.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","query2":"myQueryParameter"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions can override default headers", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := predict.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []predict.Option + requestOptionHeaders := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &requestOptionHeaders)) + for k, v := range requestOptionHeaders { + opts = append(opts, predict.HeaderParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + headers := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &headers)) + for k, v := range headers { + require.Equal(t, v, echo.header.Get(k)) + } + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions merges headers with default ones", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := predict.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []predict.Option + requestOptionHeaders := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &requestOptionHeaders)) + for k, v := range requestOptionHeaders { + opts = append(opts, predict.HeaderParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + headers := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &headers)) + for k, v := range headers { + require.Equal(t, v, echo.header.Get(k)) + } + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts booleans", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := predict.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []predict.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"isItWorking":true}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, predict.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","isItWorking":"true"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts integers", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := predict.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []predict.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":2}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, predict.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"2"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts list of string", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := predict.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []predict.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":["c","d"]}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, predict.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"c,d"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts list of booleans", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := predict.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []predict.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":[true,true,false]}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, predict.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"true,true,false"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts list of integers", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := predict.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []predict.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":[1,2]}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, predict.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"1,2"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestPredict_Put(t *testing.T) { + client, echo := createPredictClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow put method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := predict.ApiPutRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Put(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{}`) + }, + }, + { + name: "allow put method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"},"body":{"body":"parameters"}}` + req := predict.ApiPutRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Put(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"body":"parameters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestPredict_UpdateModelInstance(t *testing.T) { + client, echo := createPredictClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "update a model instance", + testFunc: func(t *testing.T) { + parametersStr := `{"modelID":"model1","updateModelParams":{"name":"Shopping stage for EU users","modelAttributes":["brand","color","category_level0","category_level1"],"modelStatus":"inactive"}}` + req := predict.ApiUpdateModelInstanceRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.UpdateModelInstance(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/predict/models/model1") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"name":"Shopping stage for EU users","modelAttributes":["brand","color","category_level0","category_level1"],"modelStatus":"inactive"}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestPredict_UpdateSegment(t *testing.T) { + client, echo := createPredictClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "updateSegment with name", + testFunc: func(t *testing.T) { + parametersStr := `{"segmentID":"segment1","updateSegmentParams":{"name":"example segment name"}}` + req := predict.ApiUpdateSegmentRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.UpdateSegment(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/segments/segment1") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"name":"example segment name"}`) + }, + }, + { + name: "updateSegment with conditions", + testFunc: func(t *testing.T) { + t.Skip("skipping test for go client") + parametersStr := `{"segmentID":"segment1","updateSegmentParams":{"conditions":{"operator":"AND","operands":[{"name":"predictions.order_value","filters":[{"operator":"GT","value":200}]}]}}}` + req := predict.ApiUpdateSegmentRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.UpdateSegment(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/segments/segment1") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"conditions":{"operator":"AND","operands":[{"name":"predictions.order_value","filters":[{"operator":"GT","value":200}]}]}}`) + }, + }, + { + name: "updateSegment with name and conditions", + testFunc: func(t *testing.T) { + t.Skip("skipping test for go client") + parametersStr := `{"segmentID":"segment1","updateSegmentParams":{"name":"example segment name","conditions":{"operator":"AND","operands":[{"name":"predictions.order_value","filters":[{"operator":"GT","value":200}]}]}}}` + req := predict.ApiUpdateSegmentRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.UpdateSegment(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/segments/segment1") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"name":"example segment name","conditions":{"operator":"AND","operands":[{"name":"predictions.order_value","filters":[{"operator":"GT","value":200}]}]}}`) + }, + }, + { + name: "updateSegment with filter probability", + testFunc: func(t *testing.T) { + parametersStr := `{"segmentID":"segment1","updateSegmentParams":{"conditions":{"operator":"AND","operands":[{"name":"predictions.affinities.color","filters":[{"operator":"EQ","value":"red","probability":{"GTE":0.5,"LTE":1}}]}]}}}` + req := predict.ApiUpdateSegmentRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.UpdateSegment(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/segments/segment1") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"conditions":{"operator":"AND","operands":[{"name":"predictions.affinities.color","filters":[{"operator":"EQ","value":"red","probability":{"GTE":0.5,"LTE":1}}]}]}}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} diff --git a/tests/output/go/tests/methods/requests/query-suggestions_test.go b/tests/output/go/tests/methods/requests/query-suggestions_test.go new file mode 100644 index 0000000000..31148b27d2 --- /dev/null +++ b/tests/output/go/tests/methods/requests/query-suggestions_test.go @@ -0,0 +1,753 @@ +package tests + +import ( + "encoding/json" + "net/url" + "testing" + + "github.com/kinbiko/jsonassert" + "github.com/stretchr/testify/require" + + "github.com/algolia/algoliasearch-client-go/v4/algolia/query-suggestions" +) + +func createSuggestionsClient() (*suggestions.APIClient, *echoRequester) { + echo := &echoRequester{} + cfg := suggestions.Configuration{ + AppID: "appID", + ApiKey: "apiKey", + Region: suggestions.US, + Requester: echo, + } + client := suggestions.NewClientWithConfig(cfg) + + return client, echo +} + +func TestSuggestions_CreateConfig(t *testing.T) { + client, echo := createSuggestionsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "createConfig", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName","sourceIndices":[{"indexName":"testIndex","facets":[{"attributes":"test"}],"generate":[["facetA","facetB"],["facetC"]]}],"languages":["french"],"exclude":["test"]}` + req := suggestions.ApiCreateConfigRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.CreateConfig(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/configs") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"indexName":"theIndexName","sourceIndices":[{"indexName":"testIndex","facets":[{"attributes":"test"}],"generate":[["facetA","facetB"],["facetC"]]}],"languages":["french"],"exclude":["test"]}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSuggestions_Del(t *testing.T) { + client, echo := createSuggestionsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow del method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := suggestions.ApiDelRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Del(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + }, + }, + { + name: "allow del method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"}}` + req := suggestions.ApiDelRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Del(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSuggestions_DeleteConfig(t *testing.T) { + client, echo := createSuggestionsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "deleteConfig", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName"}` + req := suggestions.ApiDeleteConfigRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.DeleteConfig(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/configs/theIndexName") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSuggestions_Get(t *testing.T) { + client, echo := createSuggestionsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow get method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := suggestions.ApiGetRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Get(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + { + name: "allow get method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"}}` + req := suggestions.ApiGetRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Get(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSuggestions_GetAllConfigs(t *testing.T) { + client, echo := createSuggestionsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "getAllConfigs", + testFunc: func(t *testing.T) { + parametersStr := `{}` + req := suggestions.ApiGetAllConfigsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetAllConfigs(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/configs") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSuggestions_GetConfig(t *testing.T) { + client, echo := createSuggestionsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "getConfig", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName"}` + req := suggestions.ApiGetConfigRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetConfig(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/configs/theIndexName") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSuggestions_GetConfigStatus(t *testing.T) { + client, echo := createSuggestionsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "getConfigStatus", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName"}` + req := suggestions.ApiGetConfigStatusRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetConfigStatus(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/configs/theIndexName/status") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSuggestions_GetLogFile(t *testing.T) { + client, echo := createSuggestionsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "getLogFile", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName"}` + req := suggestions.ApiGetLogFileRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetLogFile(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/logs/theIndexName") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSuggestions_Post(t *testing.T) { + client, echo := createSuggestionsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow post method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := suggestions.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Post(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{}`) + }, + }, + { + name: "allow post method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"},"body":{"body":"parameters"}}` + req := suggestions.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Post(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"body":"parameters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions can override default query parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := suggestions.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []suggestions.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"myQueryParameter"}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, suggestions.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"myQueryParameter"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions merges query parameters with default ones", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := suggestions.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []suggestions.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"query2":"myQueryParameter"}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, suggestions.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","query2":"myQueryParameter"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions can override default headers", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := suggestions.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []suggestions.Option + requestOptionHeaders := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &requestOptionHeaders)) + for k, v := range requestOptionHeaders { + opts = append(opts, suggestions.HeaderParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + headers := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &headers)) + for k, v := range headers { + require.Equal(t, v, echo.header.Get(k)) + } + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions merges headers with default ones", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := suggestions.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []suggestions.Option + requestOptionHeaders := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &requestOptionHeaders)) + for k, v := range requestOptionHeaders { + opts = append(opts, suggestions.HeaderParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + headers := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &headers)) + for k, v := range headers { + require.Equal(t, v, echo.header.Get(k)) + } + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts booleans", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := suggestions.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []suggestions.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"isItWorking":true}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, suggestions.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","isItWorking":"true"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts integers", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := suggestions.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []suggestions.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":2}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, suggestions.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"2"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts list of string", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := suggestions.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []suggestions.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":["c","d"]}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, suggestions.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"c,d"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts list of booleans", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := suggestions.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []suggestions.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":[true,true,false]}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, suggestions.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"true,true,false"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts list of integers", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := suggestions.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []suggestions.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":[1,2]}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, suggestions.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"1,2"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSuggestions_Put(t *testing.T) { + client, echo := createSuggestionsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow put method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := suggestions.ApiPutRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Put(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{}`) + }, + }, + { + name: "allow put method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"},"body":{"body":"parameters"}}` + req := suggestions.ApiPutRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Put(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"body":"parameters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSuggestions_UpdateConfig(t *testing.T) { + client, echo := createSuggestionsClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "updateConfig", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName","querySuggestionsIndexParam":{"sourceIndices":[{"indexName":"testIndex","facets":[{"attributes":"test"}],"generate":[["facetA","facetB"],["facetC"]]}],"languages":["french"],"exclude":["test"]}}` + req := suggestions.ApiUpdateConfigRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.UpdateConfig(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/configs/theIndexName") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"sourceIndices":[{"indexName":"testIndex","facets":[{"attributes":"test"}],"generate":[["facetA","facetB"],["facetC"]]}],"languages":["french"],"exclude":["test"]}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} diff --git a/tests/output/go/tests/methods/requests/recommend_test.go b/tests/output/go/tests/methods/requests/recommend_test.go new file mode 100644 index 0000000000..107a803762 --- /dev/null +++ b/tests/output/go/tests/methods/requests/recommend_test.go @@ -0,0 +1,661 @@ +package tests + +import ( + "encoding/json" + "net/url" + "testing" + + "github.com/kinbiko/jsonassert" + "github.com/stretchr/testify/require" + + "github.com/algolia/algoliasearch-client-go/v4/algolia/recommend" +) + +func createRecommendClient() (*recommend.APIClient, *echoRequester) { + echo := &echoRequester{} + cfg := recommend.Configuration{ + AppID: "appID", + ApiKey: "apiKey", + Requester: echo, + } + client := recommend.NewClientWithConfig(cfg) + + return client, echo +} + +func TestRecommend_Del(t *testing.T) { + client, echo := createRecommendClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow del method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := recommend.ApiDelRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Del(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + }, + }, + { + name: "allow del method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"}}` + req := recommend.ApiDelRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Del(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestRecommend_Get(t *testing.T) { + client, echo := createRecommendClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow get method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := recommend.ApiGetRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Get(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + { + name: "allow get method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"}}` + req := recommend.ApiGetRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Get(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestRecommend_GetRecommendations(t *testing.T) { + client, echo := createRecommendClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "get recommendations for recommend model with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"requests":[{"indexName":"indexName","objectID":"objectID","model":"related-products","threshold":42}]}` + req := recommend.ApiGetRecommendationsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetRecommendations(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/*/recommendations") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"requests":[{"indexName":"indexName","objectID":"objectID","model":"related-products","threshold":42}]}`) + }, + }, + { + name: "get recommendations for recommend model with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"requests":[{"indexName":"indexName","objectID":"objectID","model":"related-products","threshold":42,"maxRecommendations":10,"queryParameters":{"query":"myQuery","facetFilters":["query"]},"fallbackParameters":{"query":"myQuery","facetFilters":["fallback"]}}]}` + req := recommend.ApiGetRecommendationsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetRecommendations(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/*/recommendations") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"requests":[{"indexName":"indexName","objectID":"objectID","model":"related-products","threshold":42,"maxRecommendations":10,"queryParameters":{"query":"myQuery","facetFilters":["query"]},"fallbackParameters":{"query":"myQuery","facetFilters":["fallback"]}}]}`) + }, + }, + { + name: "get recommendations for trending model with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"requests":[{"indexName":"indexName","model":"trending-items","threshold":42}]}` + req := recommend.ApiGetRecommendationsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetRecommendations(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/*/recommendations") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"requests":[{"indexName":"indexName","model":"trending-items","threshold":42}]}`) + }, + }, + { + name: "get recommendations for trending model with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"requests":[{"indexName":"indexName","model":"trending-items","threshold":42,"maxRecommendations":10,"facetName":"myFacetName","facetValue":"myFacetValue","queryParameters":{"query":"myQuery","facetFilters":["query"]},"fallbackParameters":{"query":"myQuery","facetFilters":["fallback"]}}]}` + req := recommend.ApiGetRecommendationsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetRecommendations(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/*/recommendations") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"requests":[{"indexName":"indexName","model":"trending-items","threshold":42,"maxRecommendations":10,"facetName":"myFacetName","facetValue":"myFacetValue","queryParameters":{"query":"myQuery","facetFilters":["query"]},"fallbackParameters":{"query":"myQuery","facetFilters":["fallback"]}}]}`) + }, + }, + { + name: "get multiple recommendations with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"requests":[{"indexName":"indexName1","objectID":"objectID1","model":"related-products","threshold":21},{"indexName":"indexName2","objectID":"objectID2","model":"related-products","threshold":21}]}` + req := recommend.ApiGetRecommendationsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetRecommendations(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/*/recommendations") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"requests":[{"indexName":"indexName1","objectID":"objectID1","model":"related-products","threshold":21},{"indexName":"indexName2","objectID":"objectID2","model":"related-products","threshold":21}]}`) + }, + }, + { + name: "get multiple recommendations with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"requests":[{"indexName":"indexName1","objectID":"objectID1","model":"related-products","threshold":21,"maxRecommendations":10,"queryParameters":{"query":"myQuery","facetFilters":["query1"]},"fallbackParameters":{"query":"myQuery","facetFilters":["fallback1"]}},{"indexName":"indexName2","objectID":"objectID2","model":"related-products","threshold":21,"maxRecommendations":10,"queryParameters":{"query":"myQuery","facetFilters":["query2"]},"fallbackParameters":{"query":"myQuery","facetFilters":["fallback2"]}}]}` + req := recommend.ApiGetRecommendationsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetRecommendations(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/*/recommendations") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"requests":[{"indexName":"indexName1","objectID":"objectID1","model":"related-products","threshold":21,"maxRecommendations":10,"queryParameters":{"query":"myQuery","facetFilters":["query1"]},"fallbackParameters":{"query":"myQuery","facetFilters":["fallback1"]}},{"indexName":"indexName2","objectID":"objectID2","model":"related-products","threshold":21,"maxRecommendations":10,"queryParameters":{"query":"myQuery","facetFilters":["query2"]},"fallbackParameters":{"query":"myQuery","facetFilters":["fallback2"]}}]}`) + }, + }, + { + name: "get frequently bought together recommendations", + testFunc: func(t *testing.T) { + parametersStr := `{"requests":[{"indexName":"indexName1","objectID":"objectID1","model":"bought-together","threshold":42}]}` + req := recommend.ApiGetRecommendationsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetRecommendations(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/*/recommendations") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"requests":[{"indexName":"indexName1","objectID":"objectID1","model":"bought-together","threshold":42}]}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestRecommend_Post(t *testing.T) { + client, echo := createRecommendClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow post method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := recommend.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Post(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{}`) + }, + }, + { + name: "allow post method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"},"body":{"body":"parameters"}}` + req := recommend.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Post(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"body":"parameters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions can override default query parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := recommend.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []recommend.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"myQueryParameter"}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, recommend.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"myQueryParameter"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions merges query parameters with default ones", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := recommend.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []recommend.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"query2":"myQueryParameter"}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, recommend.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","query2":"myQueryParameter"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions can override default headers", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := recommend.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []recommend.Option + requestOptionHeaders := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &requestOptionHeaders)) + for k, v := range requestOptionHeaders { + opts = append(opts, recommend.HeaderParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + headers := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &headers)) + for k, v := range headers { + require.Equal(t, v, echo.header.Get(k)) + } + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions merges headers with default ones", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := recommend.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []recommend.Option + requestOptionHeaders := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &requestOptionHeaders)) + for k, v := range requestOptionHeaders { + opts = append(opts, recommend.HeaderParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + headers := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &headers)) + for k, v := range headers { + require.Equal(t, v, echo.header.Get(k)) + } + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts booleans", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := recommend.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []recommend.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"isItWorking":true}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, recommend.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","isItWorking":"true"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts integers", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := recommend.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []recommend.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":2}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, recommend.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"2"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts list of string", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := recommend.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []recommend.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":["c","d"]}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, recommend.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"c,d"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts list of booleans", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := recommend.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []recommend.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":[true,true,false]}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, recommend.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"true,true,false"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts list of integers", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := recommend.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []recommend.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":[1,2]}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, recommend.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"1,2"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestRecommend_Put(t *testing.T) { + client, echo := createRecommendClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow put method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := recommend.ApiPutRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Put(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{}`) + }, + }, + { + name: "allow put method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"},"body":{"body":"parameters"}}` + req := recommend.ApiPutRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Put(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"body":"parameters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} diff --git a/tests/output/go/tests/methods/requests/search_test.go b/tests/output/go/tests/methods/requests/search_test.go new file mode 100644 index 0000000000..afd03bd889 --- /dev/null +++ b/tests/output/go/tests/methods/requests/search_test.go @@ -0,0 +1,3201 @@ +package tests + +import ( + "encoding/json" + "net/url" + "testing" + + "github.com/kinbiko/jsonassert" + "github.com/stretchr/testify/require" + + "github.com/algolia/algoliasearch-client-go/v4/algolia/search" +) + +func createSearchClient() (*search.APIClient, *echoRequester) { + echo := &echoRequester{} + cfg := search.Configuration{ + AppID: "appID", + ApiKey: "apiKey", + Requester: echo, + } + client := search.NewClientWithConfig(cfg) + + return client, echo +} + +func TestSearch_AddApiKey(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "addApiKey", + testFunc: func(t *testing.T) { + parametersStr := `{"acl":["search","addObject"],"description":"my new api key","validity":300,"maxQueriesPerIPPerHour":100,"maxHitsPerQuery":20}` + req := search.ApiAddApiKeyRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.AddApiKey(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/keys") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"acl":["search","addObject"],"description":"my new api key","validity":300,"maxQueriesPerIPPerHour":100,"maxHitsPerQuery":20}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_AddOrUpdateObject(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "addOrUpdateObject", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"indexName","objectID":"uniqueID","body":{"key":"value"}}` + req := search.ApiAddOrUpdateObjectRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.AddOrUpdateObject(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/indexName/uniqueID") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"key":"value"}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_AppendSource(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "appendSource", + testFunc: func(t *testing.T) { + parametersStr := `{"source":"theSource","description":"theDescription"}` + req := search.ApiAppendSourceRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.AppendSource(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/security/sources/append") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"source":"theSource","description":"theDescription"}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_AssignUserId(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "assignUserId", + testFunc: func(t *testing.T) { + parametersStr := `{"xAlgoliaUserID":"userID","assignUserIdParams":{"cluster":"theCluster"}}` + req := search.ApiAssignUserIdRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.AssignUserId(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/clusters/mapping") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"cluster":"theCluster"}`) + headers := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-user-id":"userID"}`), &headers)) + for k, v := range headers { + require.Equal(t, v, echo.header.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_Batch(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allows batch method with `addObject` action", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName","batchWriteParams":{"requests":[{"action":"addObject","body":{"key":"value"}}]}}` + req := search.ApiBatchRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Batch(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/theIndexName/batch") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"requests":[{"action":"addObject","body":{"key":"value"}}]}`) + }, + }, + { + name: "allows batch method with `clear` action", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName","batchWriteParams":{"requests":[{"action":"clear","body":{"key":"value"}}]}}` + req := search.ApiBatchRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Batch(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/theIndexName/batch") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"requests":[{"action":"clear","body":{"key":"value"}}]}`) + }, + }, + { + name: "allows batch method with `delete` action", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName","batchWriteParams":{"requests":[{"action":"delete","body":{"key":"value"}}]}}` + req := search.ApiBatchRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Batch(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/theIndexName/batch") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"requests":[{"action":"delete","body":{"key":"value"}}]}`) + }, + }, + { + name: "allows batch method with `deleteObject` action", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName","batchWriteParams":{"requests":[{"action":"deleteObject","body":{"key":"value"}}]}}` + req := search.ApiBatchRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Batch(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/theIndexName/batch") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"requests":[{"action":"deleteObject","body":{"key":"value"}}]}`) + }, + }, + { + name: "allows batch method with `partialUpdateObject` action", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName","batchWriteParams":{"requests":[{"action":"partialUpdateObject","body":{"key":"value"}}]}}` + req := search.ApiBatchRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Batch(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/theIndexName/batch") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"requests":[{"action":"partialUpdateObject","body":{"key":"value"}}]}`) + }, + }, + { + name: "allows batch method with `partialUpdateObjectNoCreate` action", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName","batchWriteParams":{"requests":[{"action":"partialUpdateObjectNoCreate","body":{"key":"value"}}]}}` + req := search.ApiBatchRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Batch(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/theIndexName/batch") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"requests":[{"action":"partialUpdateObjectNoCreate","body":{"key":"value"}}]}`) + }, + }, + { + name: "allows batch method with `updateObject` action", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName","batchWriteParams":{"requests":[{"action":"updateObject","body":{"key":"value"}}]}}` + req := search.ApiBatchRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Batch(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/theIndexName/batch") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"requests":[{"action":"updateObject","body":{"key":"value"}}]}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_BatchAssignUserIds(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "batchAssignUserIds", + testFunc: func(t *testing.T) { + parametersStr := `{"xAlgoliaUserID":"userID","batchAssignUserIdsParams":{"cluster":"theCluster","users":["user1","user2"]}}` + req := search.ApiBatchAssignUserIdsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.BatchAssignUserIds(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/clusters/mapping/batch") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"cluster":"theCluster","users":["user1","user2"]}`) + headers := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-user-id":"userID"}`), &headers)) + for k, v := range headers { + require.Equal(t, v, echo.header.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_BatchDictionaryEntries(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "get batchDictionaryEntries results with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"dictionaryName":"compounds","batchDictionaryEntriesParams":{"requests":[{"action":"addEntry","body":{"objectID":"1","language":"en"}},{"action":"deleteEntry","body":{"objectID":"2","language":"fr"}}]}}` + req := search.ApiBatchDictionaryEntriesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.BatchDictionaryEntries(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/dictionaries/compounds/batch") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"requests":[{"action":"addEntry","body":{"objectID":"1","language":"en"}},{"action":"deleteEntry","body":{"objectID":"2","language":"fr"}}]}`) + }, + }, + { + name: "get batchDictionaryEntries results with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"dictionaryName":"compounds","batchDictionaryEntriesParams":{"clearExistingDictionaryEntries":false,"requests":[{"action":"addEntry","body":{"objectID":"1","language":"en","word":"fancy","words":["believe","algolia"],"decomposition":["trust","algolia"],"state":"enabled"}},{"action":"deleteEntry","body":{"objectID":"2","language":"fr","word":"humility","words":["candor","algolia"],"decomposition":["grit","algolia"],"state":"enabled"}}]}}` + req := search.ApiBatchDictionaryEntriesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.BatchDictionaryEntries(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/dictionaries/compounds/batch") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"clearExistingDictionaryEntries":false,"requests":[{"action":"addEntry","body":{"objectID":"1","language":"en","word":"fancy","words":["believe","algolia"],"decomposition":["trust","algolia"],"state":"enabled"}},{"action":"deleteEntry","body":{"objectID":"2","language":"fr","word":"humility","words":["candor","algolia"],"decomposition":["grit","algolia"],"state":"enabled"}}]}`) + }, + }, + { + name: "get batchDictionaryEntries results additional properties", + testFunc: func(t *testing.T) { + parametersStr := `{"dictionaryName":"compounds","batchDictionaryEntriesParams":{"requests":[{"action":"addEntry","body":{"objectID":"1","language":"en","additional":"try me"}}]}}` + req := search.ApiBatchDictionaryEntriesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.BatchDictionaryEntries(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/dictionaries/compounds/batch") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"requests":[{"action":"addEntry","body":{"objectID":"1","language":"en","additional":"try me"}}]}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_Browse(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "browse with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"indexName"}` + req := search.ApiBrowseRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Browse(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/indexName/browse") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{}`) + }, + }, + { + name: "browse with search parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"indexName","browseParams":{"query":"myQuery","facetFilters":["tags:algolia"]}}` + req := search.ApiBrowseRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Browse(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/indexName/browse") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"query":"myQuery","facetFilters":["tags:algolia"]}`) + }, + }, + { + name: "browse allow a cursor in parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"indexName","browseParams":{"cursor":"test"}}` + req := search.ApiBrowseRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Browse(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/indexName/browse") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"cursor":"test"}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_ClearAllSynonyms(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "clearAllSynonyms", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"indexName"}` + req := search.ApiClearAllSynonymsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.ClearAllSynonyms(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/indexName/synonyms/clear") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + require.Empty(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_ClearObjects(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "clearObjects", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName"}` + req := search.ApiClearObjectsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.ClearObjects(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/theIndexName/clear") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + require.Empty(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_ClearRules(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "clearRules", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"indexName"}` + req := search.ApiClearRulesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.ClearRules(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/indexName/rules/clear") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + require.Empty(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_Del(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow del method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := search.ApiDelRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Del(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + }, + }, + { + name: "allow del method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"}}` + req := search.ApiDelRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Del(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_DeleteApiKey(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "deleteApiKey", + testFunc: func(t *testing.T) { + parametersStr := `{"key":"myTestApiKey"}` + req := search.ApiDeleteApiKeyRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.DeleteApiKey(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/keys/myTestApiKey") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_DeleteBy(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "deleteBy", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName","deleteByParams":{"filters":"brand:brandName"}}` + req := search.ApiDeleteByRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.DeleteBy(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/theIndexName/deleteByQuery") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"filters":"brand:brandName"}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_DeleteIndex(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "deleteIndex", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName"}` + req := search.ApiDeleteIndexRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.DeleteIndex(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/theIndexName") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_DeleteObject(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "deleteObject", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName","objectID":"uniqueID"}` + req := search.ApiDeleteObjectRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.DeleteObject(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/theIndexName/uniqueID") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_DeleteRule(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "deleteRule", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"indexName","objectID":"id1"}` + req := search.ApiDeleteRuleRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.DeleteRule(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/indexName/rules/id1") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_DeleteSource(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "deleteSource", + testFunc: func(t *testing.T) { + parametersStr := `{"source":"theSource"}` + req := search.ApiDeleteSourceRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.DeleteSource(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/security/sources/theSource") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_DeleteSynonym(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "deleteSynonym", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"indexName","objectID":"id1"}` + req := search.ApiDeleteSynonymRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.DeleteSynonym(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/indexName/synonyms/id1") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_Get(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow get method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := search.ApiGetRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Get(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + { + name: "allow get method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"}}` + req := search.ApiGetRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Get(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_GetApiKey(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "getApiKey", + testFunc: func(t *testing.T) { + parametersStr := `{"key":"myTestApiKey"}` + req := search.ApiGetApiKeyRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetApiKey(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/keys/myTestApiKey") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_GetDictionaryLanguages(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "get getDictionaryLanguages", + testFunc: func(t *testing.T) { + parametersStr := `{}` + req := search.ApiGetDictionaryLanguagesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetDictionaryLanguages(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/dictionaries/*/languages") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_GetDictionarySettings(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "get getDictionarySettings results", + testFunc: func(t *testing.T) { + parametersStr := `{}` + req := search.ApiGetDictionarySettingsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetDictionarySettings(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/dictionaries/*/settings") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_GetLogs(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "getLogs with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{}` + req := search.ApiGetLogsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetLogs(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/logs") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + { + name: "getLogs with parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"offset":5,"length":10,"indexName":"theIndexName","type":"all"}` + req := search.ApiGetLogsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetLogs(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/logs") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"offset":"5","length":"10","indexName":"theIndexName","type":"all"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_GetObject(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "getObject", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName","objectID":"uniqueID","attributesToRetrieve":["attr1","attr2"]}` + req := search.ApiGetObjectRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetObject(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/theIndexName/uniqueID") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"attributesToRetrieve":"attr1,attr2"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_GetObjects(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "getObjects", + testFunc: func(t *testing.T) { + parametersStr := `{"requests":[{"attributesToRetrieve":["attr1","attr2"],"objectID":"uniqueID","indexName":"theIndexName"}]}` + req := search.ApiGetObjectsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetObjects(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/*/objects") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"requests":[{"attributesToRetrieve":["attr1","attr2"],"objectID":"uniqueID","indexName":"theIndexName"}]}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_GetRule(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "getRule", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"indexName","objectID":"id1"}` + req := search.ApiGetRuleRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetRule(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/indexName/rules/id1") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_GetSettings(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "getSettings", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName"}` + req := search.ApiGetSettingsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetSettings(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/theIndexName/settings") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_GetSources(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "getSources", + testFunc: func(t *testing.T) { + parametersStr := `{}` + req := search.ApiGetSourcesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetSources(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/security/sources") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_GetSynonym(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "getSynonym", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"indexName","objectID":"id1"}` + req := search.ApiGetSynonymRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetSynonym(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/indexName/synonyms/id1") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_GetTask(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "getTask", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName","taskID":123}` + req := search.ApiGetTaskRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetTask(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/theIndexName/task/123") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_GetTopUserIds(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "getTopUserIds", + testFunc: func(t *testing.T) { + parametersStr := `{}` + req := search.ApiGetTopUserIdsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetTopUserIds(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/clusters/mapping/top") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_GetUserId(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "getUserId", + testFunc: func(t *testing.T) { + parametersStr := `{"userID":"uniqueID"}` + req := search.ApiGetUserIdRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.GetUserId(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/clusters/mapping/uniqueID") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_HasPendingMappings(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "hasPendingMappings with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{}` + req := search.ApiHasPendingMappingsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.HasPendingMappings(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/clusters/mapping/pending") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + { + name: "hasPendingMappings with parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"getClusters":true}` + req := search.ApiHasPendingMappingsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.HasPendingMappings(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/clusters/mapping/pending") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"getClusters":"true"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_ListApiKeys(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "listApiKeys", + testFunc: func(t *testing.T) { + parametersStr := `{}` + req := search.ApiListApiKeysRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.ListApiKeys(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/keys") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_ListClusters(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "listClusters", + testFunc: func(t *testing.T) { + parametersStr := `{}` + req := search.ApiListClustersRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.ListClusters(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/clusters") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_ListIndices(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "listIndices with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{}` + req := search.ApiListIndicesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.ListIndices(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + { + name: "listIndices with parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"page":8}` + req := search.ApiListIndicesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.ListIndices(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"page":"8"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_ListUserIds(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "listUserIds with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{}` + req := search.ApiListUserIdsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.ListUserIds(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/clusters/mapping") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + }, + }, + { + name: "listUserIds with parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"page":8,"hitsPerPage":100}` + req := search.ApiListUserIdsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.ListUserIds(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/clusters/mapping") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "GET", echo.method) + + require.Nil(t, echo.body) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"page":"8","hitsPerPage":"100"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_MultipleBatch(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "multipleBatch", + testFunc: func(t *testing.T) { + parametersStr := `{"requests":[{"action":"addObject","body":{"key":"value"},"indexName":"theIndexName"}]}` + req := search.ApiMultipleBatchRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.MultipleBatch(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/*/batch") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"requests":[{"action":"addObject","body":{"key":"value"},"indexName":"theIndexName"}]}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_OperationIndex(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "operationIndex", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName","operationIndexParams":{"operation":"copy","destination":"dest","scope":["rules","settings"]}}` + req := search.ApiOperationIndexRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.OperationIndex(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/theIndexName/operation") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"operation":"copy","destination":"dest","scope":["rules","settings"]}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_PartialUpdateObject(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "partialUpdateObject", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName","objectID":"uniqueID","attributesToUpdate":{"id1":"test","id2":{"_operation":"AddUnique","value":"test2"}},"createIfNotExists":true}` + req := search.ApiPartialUpdateObjectRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.PartialUpdateObject(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/theIndexName/uniqueID/partial") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"id1":"test","id2":{"_operation":"AddUnique","value":"test2"}}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"createIfNotExists":"true"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_Post(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow post method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := search.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Post(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{}`) + }, + }, + { + name: "allow post method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"},"body":{"body":"parameters"}}` + req := search.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Post(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"body":"parameters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions can override default query parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := search.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []search.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"myQueryParameter"}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, search.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"myQueryParameter"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions merges query parameters with default ones", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := search.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []search.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"query2":"myQueryParameter"}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, search.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","query2":"myQueryParameter"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions can override default headers", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := search.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []search.Option + requestOptionHeaders := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &requestOptionHeaders)) + for k, v := range requestOptionHeaders { + opts = append(opts, search.HeaderParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + headers := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &headers)) + for k, v := range headers { + require.Equal(t, v, echo.header.Get(k)) + } + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions merges headers with default ones", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := search.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []search.Option + requestOptionHeaders := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &requestOptionHeaders)) + for k, v := range requestOptionHeaders { + opts = append(opts, search.HeaderParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + headers := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"x-algolia-api-key":"myApiKey"}`), &headers)) + for k, v := range headers { + require.Equal(t, v, echo.header.Get(k)) + } + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts booleans", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := search.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []search.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"isItWorking":true}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, search.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","isItWorking":"true"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts integers", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := search.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []search.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":2}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, search.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"2"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts list of string", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := search.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []search.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":["c","d"]}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, search.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"c,d"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts list of booleans", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := search.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []search.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":[true,true,false]}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, search.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"true,true,false"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "requestOptions queryParameters accepts list of integers", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/requestOptions","parameters":{"query":"parameters"},"body":{"facet":"filters"}}` + req := search.ApiPostRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + var opts []search.Option + requestOptionParameters := map[string]any{} + require.NoError(t, json.Unmarshal([]byte(`{"myParam":[1,2]}`), &requestOptionParameters)) + for k, v := range requestOptionParameters { + opts = append(opts, search.QueryParamOption(k, v)) + } + _, err := client.Post(req, opts...) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/requestOptions") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"facet":"filters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters","myParam":"1,2"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_Put(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "allow put method for a custom path with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/minimal"}` + req := search.ApiPutRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Put(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/minimal") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{}`) + }, + }, + { + name: "allow put method for a custom path with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"path":"/test/all","parameters":{"query":"parameters"},"body":{"body":"parameters"}}` + req := search.ApiPutRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Put(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/test/all") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"body":"parameters"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"query":"parameters"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_RemoveUserId(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "removeUserId", + testFunc: func(t *testing.T) { + parametersStr := `{"userID":"uniqueID"}` + req := search.ApiRemoveUserIdRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.RemoveUserId(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/clusters/mapping/uniqueID") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "DELETE", echo.method) + + require.Nil(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_ReplaceSources(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "replaceSources", + testFunc: func(t *testing.T) { + parametersStr := `{"source":[{"source":"theSource","description":"theDescription"}]}` + req := search.ApiReplaceSourcesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.ReplaceSources(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/security/sources") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `[{"source":"theSource","description":"theDescription"}]`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_RestoreApiKey(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "restoreApiKey", + testFunc: func(t *testing.T) { + parametersStr := `{"key":"myApiKey"}` + req := search.ApiRestoreApiKeyRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.RestoreApiKey(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/keys/myApiKey/restore") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + require.Empty(t, echo.body) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_SaveObject(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "saveObject", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName","body":{"objectID":"id","test":"val"}}` + req := search.ApiSaveObjectRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SaveObject(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/theIndexName") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"objectID":"id","test":"val"}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_SaveRule(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "saveRule with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"indexName","objectID":"id1","rule":{"objectID":"id1","conditions":[{"pattern":"apple","anchoring":"contains"}]}}` + req := search.ApiSaveRuleRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SaveRule(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/indexName/rules/id1") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"objectID":"id1","conditions":[{"pattern":"apple","anchoring":"contains"}]}`) + }, + }, + { + name: "saveRule with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"indexName","objectID":"id1","rule":{"objectID":"id1","conditions":[{"pattern":"apple","anchoring":"contains","alternatives":false,"context":"search"}],"consequence":{"params":{"filters":"brand:apple","query":{"remove":["algolia"],"edits":[{"type":"remove","delete":"abc","insert":"cde"},{"type":"replace","delete":"abc","insert":"cde"}]}},"hide":[{"objectID":"321"}],"filterPromotes":false,"userData":{"algolia":"aloglia"},"promote":[{"objectID":"abc","position":3},{"objectIDs":["abc","def"],"position":1}]},"description":"test","enabled":true,"validity":[{"from":1656670273,"until":1656670277}]},"forwardToReplicas":true}` + req := search.ApiSaveRuleRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SaveRule(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/indexName/rules/id1") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"objectID":"id1","conditions":[{"pattern":"apple","anchoring":"contains","alternatives":false,"context":"search"}],"consequence":{"params":{"filters":"brand:apple","query":{"remove":["algolia"],"edits":[{"type":"remove","delete":"abc","insert":"cde"},{"type":"replace","delete":"abc","insert":"cde"}]}},"hide":[{"objectID":"321"}],"filterPromotes":false,"userData":{"algolia":"aloglia"},"promote":[{"objectID":"abc","position":3},{"objectIDs":["abc","def"],"position":1}]},"description":"test","enabled":true,"validity":[{"from":1656670273,"until":1656670277}]}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"forwardToReplicas":"true"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_SaveRules(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "saveRules with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"indexName","rules":[{"objectID":"a-rule-id","conditions":[{"pattern":"smartphone","anchoring":"contains"}]},{"objectID":"a-second-rule-id","conditions":[{"pattern":"apple","anchoring":"contains"}]}]}` + req := search.ApiSaveRulesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SaveRules(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/indexName/rules/batch") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `[{"objectID":"a-rule-id","conditions":[{"pattern":"smartphone","anchoring":"contains"}]},{"objectID":"a-second-rule-id","conditions":[{"pattern":"apple","anchoring":"contains"}]}]`) + }, + }, + { + name: "saveRules with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"indexName","rules":[{"objectID":"id1","conditions":[{"pattern":"apple","anchoring":"contains","alternatives":false,"context":"search"}],"consequence":{"params":{"filters":"brand:apple","query":{"remove":["algolia"],"edits":[{"type":"remove","delete":"abc","insert":"cde"},{"type":"replace","delete":"abc","insert":"cde"}]}},"hide":[{"objectID":"321"}],"filterPromotes":false,"userData":{"algolia":"aloglia"},"promote":[{"objectID":"abc","position":3},{"objectIDs":["abc","def"],"position":1}]},"description":"test","enabled":true,"validity":[{"from":1656670273,"until":1656670277}]}],"forwardToReplicas":true,"clearExistingRules":true}` + req := search.ApiSaveRulesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SaveRules(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/indexName/rules/batch") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `[{"objectID":"id1","conditions":[{"pattern":"apple","anchoring":"contains","alternatives":false,"context":"search"}],"consequence":{"params":{"filters":"brand:apple","query":{"remove":["algolia"],"edits":[{"type":"remove","delete":"abc","insert":"cde"},{"type":"replace","delete":"abc","insert":"cde"}]}},"hide":[{"objectID":"321"}],"filterPromotes":false,"userData":{"algolia":"aloglia"},"promote":[{"objectID":"abc","position":3},{"objectIDs":["abc","def"],"position":1}]},"description":"test","enabled":true,"validity":[{"from":1656670273,"until":1656670277}]}]`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"forwardToReplicas":"true","clearExistingRules":"true"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_SaveSynonym(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "saveSynonym", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"indexName","objectID":"id1","synonymHit":{"objectID":"id1","type":"synonym","synonyms":["car","vehicule","auto"]},"forwardToReplicas":true}` + req := search.ApiSaveSynonymRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SaveSynonym(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/indexName/synonyms/id1") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"objectID":"id1","type":"synonym","synonyms":["car","vehicule","auto"]}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"forwardToReplicas":"true"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_SaveSynonyms(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "saveSynonyms", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"indexName","synonymHit":[{"objectID":"id1","type":"synonym","synonyms":["car","vehicule","auto"]},{"objectID":"id2","type":"onewaysynonym","input":"iphone","synonyms":["ephone","aphone","yphone"]}],"forwardToReplicas":true,"replaceExistingSynonyms":false}` + req := search.ApiSaveSynonymsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SaveSynonyms(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/indexName/synonyms/batch") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `[{"objectID":"id1","type":"synonym","synonyms":["car","vehicule","auto"]},{"objectID":"id2","type":"onewaysynonym","input":"iphone","synonyms":["ephone","aphone","yphone"]}]`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"forwardToReplicas":"true","replaceExistingSynonyms":"false"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_Search(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "search for a single hits request with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"requests":[{"indexName":"theIndexName"}]}` + req := search.ApiSearchRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Search(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/*/queries") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"requests":[{"indexName":"theIndexName"}]}`) + }, + }, + { + name: "search for a single facet request with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"requests":[{"indexName":"theIndexName","type":"facet","facet":"theFacet"}],"strategy":"stopIfEnoughMatches"}` + req := search.ApiSearchRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Search(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/*/queries") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"requests":[{"indexName":"theIndexName","type":"facet","facet":"theFacet"}],"strategy":"stopIfEnoughMatches"}`) + }, + }, + { + name: "search for a single hits request with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"requests":[{"indexName":"theIndexName","query":"myQuery","hitsPerPage":50,"type":"default"}]}` + req := search.ApiSearchRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Search(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/*/queries") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"requests":[{"indexName":"theIndexName","query":"myQuery","hitsPerPage":50,"type":"default"}]}`) + }, + }, + { + name: "search for a single facet request with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"requests":[{"indexName":"theIndexName","type":"facet","facet":"theFacet","facetQuery":"theFacetQuery","query":"theQuery","maxFacetHits":50}],"strategy":"stopIfEnoughMatches"}` + req := search.ApiSearchRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Search(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/*/queries") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"requests":[{"indexName":"theIndexName","type":"facet","facet":"theFacet","facetQuery":"theFacetQuery","query":"theQuery","maxFacetHits":50}],"strategy":"stopIfEnoughMatches"}`) + }, + }, + { + name: "search for multiple mixed requests in multiple indices with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"requests":[{"indexName":"theIndexName"},{"indexName":"theIndexName2","type":"facet","facet":"theFacet"},{"indexName":"theIndexName","type":"default"}],"strategy":"stopIfEnoughMatches"}` + req := search.ApiSearchRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Search(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/*/queries") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"requests":[{"indexName":"theIndexName"},{"indexName":"theIndexName2","type":"facet","facet":"theFacet"},{"indexName":"theIndexName","type":"default"}],"strategy":"stopIfEnoughMatches"}`) + }, + }, + { + name: "search for multiple mixed requests in multiple indices with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"requests":[{"indexName":"theIndexName","type":"facet","facet":"theFacet","facetQuery":"theFacetQuery","query":"theQuery","maxFacetHits":50},{"indexName":"theIndexName","query":"myQuery","hitsPerPage":50,"type":"default"}],"strategy":"stopIfEnoughMatches"}` + req := search.ApiSearchRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Search(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/*/queries") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"requests":[{"indexName":"theIndexName","type":"facet","facet":"theFacet","facetQuery":"theFacetQuery","query":"theQuery","maxFacetHits":50},{"indexName":"theIndexName","query":"myQuery","hitsPerPage":50,"type":"default"}],"strategy":"stopIfEnoughMatches"}`) + }, + }, + { + name: "search filters accept all of the possible shapes", + testFunc: func(t *testing.T) { + parametersStr := `{"requests":[{"indexName":"theIndexName","facetFilters":"mySearch:filters","reRankingApplyFilter":"mySearch:filters","tagFilters":"mySearch:filters","numericFilters":"mySearch:filters","optionalFilters":"mySearch:filters"},{"indexName":"theIndexName","facetFilters":["mySearch:filters",["mySearch:filters"]],"reRankingApplyFilter":["mySearch:filters",["mySearch:filters"]],"tagFilters":["mySearch:filters",["mySearch:filters"]],"numericFilters":["mySearch:filters",["mySearch:filters"]],"optionalFilters":["mySearch:filters",["mySearch:filters"]]}]}` + req := search.ApiSearchRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Search(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/*/queries") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"requests":[{"indexName":"theIndexName","facetFilters":"mySearch:filters","reRankingApplyFilter":"mySearch:filters","tagFilters":"mySearch:filters","numericFilters":"mySearch:filters","optionalFilters":"mySearch:filters"},{"indexName":"theIndexName","facetFilters":["mySearch:filters",["mySearch:filters"]],"reRankingApplyFilter":["mySearch:filters",["mySearch:filters"]],"tagFilters":["mySearch:filters",["mySearch:filters"]],"numericFilters":["mySearch:filters",["mySearch:filters"]],"optionalFilters":["mySearch:filters",["mySearch:filters"]]}]}`) + }, + }, + { + name: "search with all search parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"requests":[{"indexName":"theIndexName","query":"","similarQuery":"","filters":"","facetFilters":[""],"optionalFilters":[""],"numericFilters":[""],"tagFilters":[""],"sumOrFiltersScores":true,"facets":[""],"maxValuesPerFacet":0,"facetingAfterDistinct":true,"sortFacetValuesBy":"","page":0,"offset":0,"length":0,"aroundLatLng":"","aroundLatLngViaIP":true,"aroundRadius":"all","aroundPrecision":0,"minimumAroundRadius":0,"insideBoundingBox":[47.3165,4.9665],"insidePolygon":[47.3165,4.9665],"naturalLanguages":[""],"ruleContexts":[""],"personalizationImpact":0,"userToken":"","getRankingInfo":true,"clickAnalytics":true,"analytics":true,"analyticsTags":[""],"percentileComputation":true,"enableABTest":true,"enableReRanking":true,"reRankingApplyFilter":[""],"attributesForFaceting":[""],"attributesToRetrieve":[""],"restrictSearchableAttributes":[""],"ranking":[""],"customRanking":[""],"relevancyStrictness":0,"attributesToHighlight":[""],"attributesToSnippet":[""],"highlightPreTag":"","highlightPostTag":"","snippetEllipsisText":"","restrictHighlightAndSnippetArrays":true,"hitsPerPage":0,"minWordSizefor1Typo":0,"minWordSizefor2Typos":0,"typoTolerance":"min","allowTyposOnNumericTokens":true,"disableTypoToleranceOnAttributes":[""],"ignorePlurals":false,"removeStopWords":true,"keepDiacriticsOnCharacters":"","queryLanguages":[""],"decompoundQuery":true,"enableRules":true,"enablePersonalization":true,"queryType":"prefixAll","removeWordsIfNoResults":"allOptional","advancedSyntax":true,"optionalWords":[""],"disableExactOnAttributes":[""],"exactOnSingleWordQuery":"attribute","alternativesAsExact":["multiWordsSynonym"],"advancedSyntaxFeatures":["exactPhrase"],"distinct":0,"synonyms":true,"replaceSynonymsInHighlight":true,"minProximity":0,"responseFields":[""],"attributeCriteriaComputedByMinProximity":true,"renderingContent":{"facetOrdering":{"facets":{"order":["a","b"]},"values":{"a":{"order":["b"],"sortRemainingBy":"count"}}}},"type":"default"}]}` + req := search.ApiSearchRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.Search(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/*/queries") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"requests":[{"indexName":"theIndexName","query":"","similarQuery":"","filters":"","facetFilters":[""],"optionalFilters":[""],"numericFilters":[""],"tagFilters":[""],"sumOrFiltersScores":true,"facets":[""],"maxValuesPerFacet":0,"facetingAfterDistinct":true,"sortFacetValuesBy":"","page":0,"offset":0,"length":0,"aroundLatLng":"","aroundLatLngViaIP":true,"aroundRadius":"all","aroundPrecision":0,"minimumAroundRadius":0,"insideBoundingBox":[47.3165,4.9665],"insidePolygon":[47.3165,4.9665],"naturalLanguages":[""],"ruleContexts":[""],"personalizationImpact":0,"userToken":"","getRankingInfo":true,"clickAnalytics":true,"analytics":true,"analyticsTags":[""],"percentileComputation":true,"enableABTest":true,"enableReRanking":true,"reRankingApplyFilter":[""],"attributesForFaceting":[""],"attributesToRetrieve":[""],"restrictSearchableAttributes":[""],"ranking":[""],"customRanking":[""],"relevancyStrictness":0,"attributesToHighlight":[""],"attributesToSnippet":[""],"highlightPreTag":"","highlightPostTag":"","snippetEllipsisText":"","restrictHighlightAndSnippetArrays":true,"hitsPerPage":0,"minWordSizefor1Typo":0,"minWordSizefor2Typos":0,"typoTolerance":"min","allowTyposOnNumericTokens":true,"disableTypoToleranceOnAttributes":[""],"ignorePlurals":false,"removeStopWords":true,"keepDiacriticsOnCharacters":"","queryLanguages":[""],"decompoundQuery":true,"enableRules":true,"enablePersonalization":true,"queryType":"prefixAll","removeWordsIfNoResults":"allOptional","advancedSyntax":true,"optionalWords":[""],"disableExactOnAttributes":[""],"exactOnSingleWordQuery":"attribute","alternativesAsExact":["multiWordsSynonym"],"advancedSyntaxFeatures":["exactPhrase"],"distinct":0,"synonyms":true,"replaceSynonymsInHighlight":true,"minProximity":0,"responseFields":[""],"attributeCriteriaComputedByMinProximity":true,"renderingContent":{"facetOrdering":{"facets":{"order":["a","b"]},"values":{"a":{"order":["b"],"sortRemainingBy":"count"}}}},"type":"default"}]}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_SearchDictionaryEntries(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "get searchDictionaryEntries results with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"dictionaryName":"compounds","searchDictionaryEntriesParams":{"query":"foo"}}` + req := search.ApiSearchDictionaryEntriesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SearchDictionaryEntries(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/dictionaries/compounds/search") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"query":"foo"}`) + }, + }, + { + name: "get searchDictionaryEntries results with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"dictionaryName":"compounds","searchDictionaryEntriesParams":{"query":"foo","page":4,"hitsPerPage":2,"language":"fr"}}` + req := search.ApiSearchDictionaryEntriesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SearchDictionaryEntries(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/dictionaries/compounds/search") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"query":"foo","page":4,"hitsPerPage":2,"language":"fr"}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_SearchForFacetValues(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "get searchForFacetValues results with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"indexName","facetName":"facetName"}` + req := search.ApiSearchForFacetValuesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SearchForFacetValues(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/indexName/facets/facetName/query") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{}`) + }, + }, + { + name: "get searchForFacetValues results with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"indexName","facetName":"facetName","searchForFacetValuesRequest":{"params":"query=foo&facetFilters=['bar']","facetQuery":"foo","maxFacetHits":42}}` + req := search.ApiSearchForFacetValuesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SearchForFacetValues(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/indexName/facets/facetName/query") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"params":"query=foo&facetFilters=['bar']","facetQuery":"foo","maxFacetHits":42}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_SearchRules(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "searchRules", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"indexName","searchRulesParams":{"query":"something"}}` + req := search.ApiSearchRulesRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SearchRules(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/indexName/rules/search") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"query":"something"}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_SearchSingleIndex(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "search with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"indexName"}` + req := search.ApiSearchSingleIndexRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SearchSingleIndex(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/indexName/query") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{}`) + }, + }, + { + name: "search with searchParams", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"indexName","searchParams":{"query":"myQuery","facetFilters":["tags:algolia"]}}` + req := search.ApiSearchSingleIndexRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SearchSingleIndex(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/indexName/query") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"query":"myQuery","facetFilters":["tags:algolia"]}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_SearchSynonyms(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "searchSynonyms with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"indexName"}` + req := search.ApiSearchSynonymsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SearchSynonyms(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/indexName/synonyms/search") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{}`) + }, + }, + { + name: "searchSynonyms with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"indexName","type":"altcorrection1","page":10,"hitsPerPage":10,"searchSynonymsParams":{"query":"myQuery"}}` + req := search.ApiSearchSynonymsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SearchSynonyms(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/indexName/synonyms/search") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"query":"myQuery"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"type":"altcorrection1","page":"10","hitsPerPage":"10"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_SearchUserIds(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "searchUserIds", + testFunc: func(t *testing.T) { + parametersStr := `{"query":"test","clusterName":"theClusterName","page":5,"hitsPerPage":10}` + req := search.ApiSearchUserIdsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SearchUserIds(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/clusters/mapping/search") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "POST", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"query":"test","clusterName":"theClusterName","page":5,"hitsPerPage":10}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_SetDictionarySettings(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "get setDictionarySettings results with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"disableStandardEntries":{"plurals":{"fr":false,"en":false,"ru":true}}}` + req := search.ApiSetDictionarySettingsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SetDictionarySettings(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/dictionaries/*/settings") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"disableStandardEntries":{"plurals":{"fr":false,"en":false,"ru":true}}}`) + }, + }, + { + name: "get setDictionarySettings results with all parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"disableStandardEntries":{"plurals":{"fr":false,"en":false,"ru":true},"stopwords":{"fr":false},"compounds":{"ru":true}}}` + req := search.ApiSetDictionarySettingsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SetDictionarySettings(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/dictionaries/*/settings") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"disableStandardEntries":{"plurals":{"fr":false,"en":false,"ru":true},"stopwords":{"fr":false},"compounds":{"ru":true}}}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_SetSettings(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "setSettings with minimal parameters", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName","indexSettings":{"paginationLimitedTo":10},"forwardToReplicas":true}` + req := search.ApiSetSettingsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SetSettings(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/theIndexName/settings") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"paginationLimitedTo":10}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"forwardToReplicas":"true"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "setSettings allow boolean `typoTolerance`", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName","indexSettings":{"typoTolerance":true},"forwardToReplicas":true}` + req := search.ApiSetSettingsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SetSettings(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/theIndexName/settings") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"typoTolerance":true}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"forwardToReplicas":"true"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "setSettings allow enum `typoTolerance`", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName","indexSettings":{"typoTolerance":"min"},"forwardToReplicas":true}` + req := search.ApiSetSettingsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SetSettings(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/theIndexName/settings") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"typoTolerance":"min"}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"forwardToReplicas":"true"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "setSettings allow boolean `ignorePlurals`", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName","indexSettings":{"ignorePlurals":true},"forwardToReplicas":true}` + req := search.ApiSetSettingsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SetSettings(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/theIndexName/settings") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"ignorePlurals":true}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"forwardToReplicas":"true"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "setSettings allow list of string `ignorePlurals`", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName","indexSettings":{"ignorePlurals":["algolia"]},"forwardToReplicas":true}` + req := search.ApiSetSettingsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SetSettings(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/theIndexName/settings") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"ignorePlurals":["algolia"]}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"forwardToReplicas":"true"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "setSettings allow boolean `removeStopWords`", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName","indexSettings":{"removeStopWords":true},"forwardToReplicas":true}` + req := search.ApiSetSettingsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SetSettings(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/theIndexName/settings") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"removeStopWords":true}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"forwardToReplicas":"true"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "setSettings allow list of string `removeStopWords`", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName","indexSettings":{"removeStopWords":["algolia"]},"forwardToReplicas":true}` + req := search.ApiSetSettingsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SetSettings(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/theIndexName/settings") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"removeStopWords":["algolia"]}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"forwardToReplicas":"true"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "setSettings allow boolean `distinct`", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName","indexSettings":{"distinct":true},"forwardToReplicas":true}` + req := search.ApiSetSettingsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SetSettings(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/theIndexName/settings") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"distinct":true}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"forwardToReplicas":"true"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "setSettings allow integers for `distinct`", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName","indexSettings":{"distinct":1},"forwardToReplicas":true}` + req := search.ApiSetSettingsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SetSettings(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/theIndexName/settings") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"distinct":1}`) + queryParams := map[string]string{} + require.NoError(t, json.Unmarshal([]byte(`{"forwardToReplicas":"true"}`), &queryParams)) + for k, v := range queryParams { + require.Equal(t, v, echo.query.Get(k)) + } + }, + }, + { + name: "setSettings allow all `indexSettings`", + testFunc: func(t *testing.T) { + parametersStr := `{"indexName":"theIndexName","indexSettings":{"replicas":[""],"paginationLimitedTo":0,"disableTypoToleranceOnWords":["algolia"],"attributesToTransliterate":["algolia"],"camelCaseAttributes":["algolia"],"decompoundedAttributes":{"algolia":"aloglia"},"indexLanguages":["algolia"],"disablePrefixOnAttributes":["algolia"],"allowCompressionOfIntegerArray":true,"numericAttributesForFiltering":["algolia"],"separatorsToIndex":"algolia","searchableAttributes":["algolia"],"userData":{"user":"data"},"customNormalization":{"algolia":{"aloglia":"aglolia"}},"attributesForFaceting":["algolia"],"unretrievableAttributes":["algolia"],"attributesToRetrieve":["algolia"],"restrictSearchableAttributes":["algolia"],"ranking":["geo"],"customRanking":["algolia"],"relevancyStrictness":10,"attributesToHighlight":["algolia"],"attributesToSnippet":["algolia"],"highlightPreTag":"","highlightPostTag":"","snippetEllipsisText":"---","restrictHighlightAndSnippetArrays":true,"hitsPerPage":10,"minWordSizefor1Typo":5,"minWordSizefor2Typos":11,"typoTolerance":false,"allowTyposOnNumericTokens":true,"disableTypoToleranceOnAttributes":["algolia"],"ignorePlurals":false,"removeStopWords":false,"keepDiacriticsOnCharacters":"abc","queryLanguages":["algolia"],"decompoundQuery":false,"enableRules":false,"enablePersonalization":true,"queryType":"prefixLast","removeWordsIfNoResults":"lastWords","advancedSyntax":true,"optionalWords":["algolia"],"disableExactOnAttributes":["algolia"],"exactOnSingleWordQuery":"attribute","alternativesAsExact":["singleWordSynonym"],"advancedSyntaxFeatures":["exactPhrase"],"distinct":3,"attributeForDistinct":"test","synonyms":false,"replaceSynonymsInHighlight":true,"minProximity":6,"responseFields":["algolia"],"maxFacetHits":50,"attributeCriteriaComputedByMinProximity":true,"renderingContent":{"facetOrdering":{"facets":{"order":["a","b"]},"values":{"a":{"order":["b"],"sortRemainingBy":"count"}}}}}}` + req := search.ApiSetSettingsRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.SetSettings(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/indexes/theIndexName/settings") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"replicas":[""],"paginationLimitedTo":0,"disableTypoToleranceOnWords":["algolia"],"attributesToTransliterate":["algolia"],"camelCaseAttributes":["algolia"],"decompoundedAttributes":{"algolia":"aloglia"},"indexLanguages":["algolia"],"disablePrefixOnAttributes":["algolia"],"allowCompressionOfIntegerArray":true,"numericAttributesForFiltering":["algolia"],"separatorsToIndex":"algolia","searchableAttributes":["algolia"],"userData":{"user":"data"},"customNormalization":{"algolia":{"aloglia":"aglolia"}},"attributesForFaceting":["algolia"],"unretrievableAttributes":["algolia"],"attributesToRetrieve":["algolia"],"restrictSearchableAttributes":["algolia"],"ranking":["geo"],"customRanking":["algolia"],"relevancyStrictness":10,"attributesToHighlight":["algolia"],"attributesToSnippet":["algolia"],"highlightPreTag":"","highlightPostTag":"","snippetEllipsisText":"---","restrictHighlightAndSnippetArrays":true,"hitsPerPage":10,"minWordSizefor1Typo":5,"minWordSizefor2Typos":11,"typoTolerance":false,"allowTyposOnNumericTokens":true,"disableTypoToleranceOnAttributes":["algolia"],"ignorePlurals":false,"removeStopWords":false,"keepDiacriticsOnCharacters":"abc","queryLanguages":["algolia"],"decompoundQuery":false,"enableRules":false,"enablePersonalization":true,"queryType":"prefixLast","removeWordsIfNoResults":"lastWords","advancedSyntax":true,"optionalWords":["algolia"],"disableExactOnAttributes":["algolia"],"exactOnSingleWordQuery":"attribute","alternativesAsExact":["singleWordSynonym"],"advancedSyntaxFeatures":["exactPhrase"],"distinct":3,"attributeForDistinct":"test","synonyms":false,"replaceSynonymsInHighlight":true,"minProximity":6,"responseFields":["algolia"],"maxFacetHits":50,"attributeCriteriaComputedByMinProximity":true,"renderingContent":{"facetOrdering":{"facets":{"order":["a","b"]},"values":{"a":{"order":["b"],"sortRemainingBy":"count"}}}}}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} + +func TestSearch_UpdateApiKey(t *testing.T) { + client, echo := createSearchClient() + + tests := []struct { + name string + testFunc func(t *testing.T) + }{ + { + name: "updateApiKey", + testFunc: func(t *testing.T) { + parametersStr := `{"key":"myApiKey","apiKey":{"acl":["search","addObject"],"validity":300,"maxQueriesPerIPPerHour":100,"maxHitsPerQuery":20}}` + req := search.ApiUpdateApiKeyRequest{} + require.NoError(t, json.Unmarshal([]byte(parametersStr), &req)) + _, err := client.UpdateApiKey(req) + require.NoError(t, err) + + expectedPath, err := url.QueryUnescape("/1/keys/myApiKey") + require.NoError(t, err) + require.Equal(t, expectedPath, echo.path) + require.Equal(t, "PUT", echo.method) + + ja := jsonassert.New(t) + ja.Assertf(*echo.body, `{"acl":["search","addObject"],"validity":300,"maxQueriesPerIPPerHour":100,"maxHitsPerQuery":20}`) + }, + }, + } + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + test.testFunc(t) + }) + } +} diff --git a/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/AbtestingTest.kt b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/AbtestingTest.kt new file mode 100644 index 0000000000..ff6f6ee9fa --- /dev/null +++ b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/AbtestingTest.kt @@ -0,0 +1,101 @@ +package com.algolia.client + +import com.algolia.client.api.AbtestingClient +import com.algolia.client.configuration.* +import com.algolia.client.model.abtesting.* +import com.algolia.client.transport.* +import com.algolia.extension.* +import com.algolia.utils.* +import io.ktor.http.* +import kotlinx.coroutines.test.* +import kotlinx.serialization.json.* +import kotlin.test.* + +class AbtestingTest { + + @Test + fun `calls api with correct user agent`() = runTest { + val client = AbtestingClient(appId = "appId", apiKey = "apiKey", region = "us") + client.runTest( + call = { + post( + path = "/test", + ) + }, + intercept = { + val regexp = "^Algolia for Kotlin \\(\\d+\\.\\d+\\.\\d+(-.*)?\\)(; [a-zA-Z. ]+ (\\(\\d+((\\.\\d+)?\\.\\d+)?(-.*)?\\))?)*(; Abtesting (\\(\\d+\\.\\d+\\.\\d+(-.*)?\\)))(; [a-zA-Z. ]+ (\\(\\d+((\\.\\d+)?\\.\\d+)?(-.*)?\\))?)*$".toRegex() + val header = it.url.parameters["X-Algolia-Agent"]?.decodeURLPart().orEmpty() + assertTrue(actual = header.matches(regexp), message = "Expected $header to match the following regex: $regexp") + }, + ) + } + + @Test + fun `calls api with default read timeouts`() = runTest { + val client = AbtestingClient(appId = "appId", apiKey = "apiKey", region = "us") + client.runTest( + call = { + get( + path = "/test", + ) + }, + intercept = { + assertEquals(2000, it.connectTimeout) + assertEquals(5000, it.socketTimeout) + }, + ) + } + + @Test + fun `calls api with default write timeouts`() = runTest { + val client = AbtestingClient(appId = "appId", apiKey = "apiKey", region = "us") + client.runTest( + call = { + post( + path = "/test", + ) + }, + intercept = { + assertEquals(2000, it.connectTimeout) + assertEquals(30000, it.socketTimeout) + }, + ) + } + + @Test + fun `fallbacks to the alias when region is not given`() = runTest { + val client = AbtestingClient(appId = "my-app-id", apiKey = "my-api-key") + client.runTest( + call = { + getABTest( + id = 123, + ) + }, + intercept = { + assertEquals("analytics.algolia.com", it.url.host) + }, + ) + } + + @Test + fun `uses the correct region`() = runTest { + val client = AbtestingClient(appId = "my-app-id", apiKey = "my-api-key", "us") + client.runTest( + call = { + getABTest( + id = 123, + ) + }, + intercept = { + assertEquals("analytics.us.algolia.com", it.url.host) + }, + ) + } + + @Test + fun `throws when incorrect region is given`() = runTest { + assertFails { + val client = AbtestingClient(appId = "my-app-id", apiKey = "my-api-key", "not_a_region") + }.let { error -> assertError(error, "`region` must be one of the following: de, us") } + } +} diff --git a/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/AnalyticsTest.kt b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/AnalyticsTest.kt new file mode 100644 index 0000000000..a974d79c39 --- /dev/null +++ b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/AnalyticsTest.kt @@ -0,0 +1,111 @@ +package com.algolia.client + +import com.algolia.client.api.AnalyticsClient +import com.algolia.client.configuration.* +import com.algolia.client.model.analytics.* +import com.algolia.client.transport.* +import com.algolia.extension.* +import com.algolia.utils.* +import io.ktor.http.* +import kotlinx.coroutines.test.* +import kotlinx.serialization.json.* +import kotlin.test.* + +class AnalyticsTest { + + @Test + fun `calls api with correct user agent`() = runTest { + val client = AnalyticsClient(appId = "appId", apiKey = "apiKey", region = "us") + client.runTest( + call = { + post( + path = "/test", + ) + }, + intercept = { + val regexp = "^Algolia for Kotlin \\(\\d+\\.\\d+\\.\\d+(-.*)?\\)(; [a-zA-Z. ]+ (\\(\\d+((\\.\\d+)?\\.\\d+)?(-.*)?\\))?)*(; Analytics (\\(\\d+\\.\\d+\\.\\d+(-.*)?\\)))(; [a-zA-Z. ]+ (\\(\\d+((\\.\\d+)?\\.\\d+)?(-.*)?\\))?)*$".toRegex() + val header = it.url.parameters["X-Algolia-Agent"]?.decodeURLPart().orEmpty() + assertTrue(actual = header.matches(regexp), message = "Expected $header to match the following regex: $regexp") + }, + ) + } + + @Test + fun `calls api with default read timeouts`() = runTest { + val client = AnalyticsClient(appId = "appId", apiKey = "apiKey", region = "us") + client.runTest( + call = { + get( + path = "/test", + ) + }, + intercept = { + assertEquals(2000, it.connectTimeout) + assertEquals(5000, it.socketTimeout) + }, + ) + } + + @Test + fun `calls api with default write timeouts`() = runTest { + val client = AnalyticsClient(appId = "appId", apiKey = "apiKey", region = "us") + client.runTest( + call = { + post( + path = "/test", + ) + }, + intercept = { + assertEquals(2000, it.connectTimeout) + assertEquals(30000, it.socketTimeout) + }, + ) + } + + @Test + fun `fallbacks to the alias when region is not given`() = runTest { + val client = AnalyticsClient(appId = "my-app-id", apiKey = "my-api-key") + client.runTest( + call = { + getAverageClickPosition( + index = "my-index", + ) + }, + intercept = { + assertEquals("analytics.algolia.com", it.url.host) + }, + ) + } + + @Test + fun `uses the correct region`() = runTest { + val client = AnalyticsClient(appId = "my-app-id", apiKey = "my-api-key", "de") + client.runTest( + call = { + post( + path = "/test", + ) + }, + intercept = { + assertEquals("analytics.de.algolia.com", it.url.host) + }, + ) + } + + @Test + fun `throws when incorrect region is given`() = runTest { + assertFails { + val client = AnalyticsClient(appId = "my-app-id", apiKey = "my-api-key", "not_a_region") + }.let { error -> assertError(error, "`region` must be one of the following: de, us") } + } + + @Test + fun `getAverageClickPosition throws without index`() = runTest { + val client = AnalyticsClient(appId = "appId", apiKey = "apiKey", region = "us") + assertFails { + client.getClickPositions( + index = empty(), + ) + }.let { error -> assertError(error, "Parameter `index` is required when calling `getClickPositions`.") } + } +} diff --git a/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/IngestionTest.kt b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/IngestionTest.kt new file mode 100644 index 0000000000..5cdd6d2780 --- /dev/null +++ b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/IngestionTest.kt @@ -0,0 +1,86 @@ +package com.algolia.client + +import com.algolia.client.api.IngestionClient +import com.algolia.client.configuration.* +import com.algolia.client.model.ingestion.* +import com.algolia.client.transport.* +import com.algolia.extension.* +import com.algolia.utils.* +import io.ktor.http.* +import kotlinx.coroutines.test.* +import kotlinx.serialization.json.* +import kotlin.test.* + +class IngestionTest { + + @Test + fun `calls api with correct user agent`() = runTest { + val client = IngestionClient(appId = "appId", apiKey = "apiKey", region = "us") + client.runTest( + call = { + post( + path = "/test", + ) + }, + intercept = { + val regexp = "^Algolia for Kotlin \\(\\d+\\.\\d+\\.\\d+(-.*)?\\)(; [a-zA-Z. ]+ (\\(\\d+((\\.\\d+)?\\.\\d+)?(-.*)?\\))?)*(; Ingestion (\\(\\d+\\.\\d+\\.\\d+(-.*)?\\)))(; [a-zA-Z. ]+ (\\(\\d+((\\.\\d+)?\\.\\d+)?(-.*)?\\))?)*$".toRegex() + val header = it.url.parameters["X-Algolia-Agent"]?.decodeURLPart().orEmpty() + assertTrue(actual = header.matches(regexp), message = "Expected $header to match the following regex: $regexp") + }, + ) + } + + @Test + fun `calls api with default read timeouts`() = runTest { + val client = IngestionClient(appId = "appId", apiKey = "apiKey", region = "us") + client.runTest( + call = { + get( + path = "/test", + ) + }, + intercept = { + assertEquals(2000, it.connectTimeout) + assertEquals(5000, it.socketTimeout) + }, + ) + } + + @Test + fun `calls api with default write timeouts`() = runTest { + val client = IngestionClient(appId = "appId", apiKey = "apiKey", region = "us") + client.runTest( + call = { + post( + path = "/test", + ) + }, + intercept = { + assertEquals(2000, it.connectTimeout) + assertEquals(30000, it.socketTimeout) + }, + ) + } + + @Test + fun `uses the correct region`() = runTest { + val client = IngestionClient(appId = "my-app-id", apiKey = "my-api-key", "us") + client.runTest( + call = { + getSource( + sourceID = "6c02aeb1-775e-418e-870b-1faccd4b2c0f", + ) + }, + intercept = { + assertEquals("data.us.algolia.com", it.url.host) + }, + ) + } + + @Test + fun `throws when incorrect region is given`() = runTest { + assertFails { + val client = IngestionClient(appId = "my-app-id", apiKey = "my-api-key", "not_a_region") + }.let { error -> assertError(error, "`region` is required and must be one of the following: eu, us") } + } +} diff --git a/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/InsightsTest.kt b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/InsightsTest.kt new file mode 100644 index 0000000000..be19ec2f28 --- /dev/null +++ b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/InsightsTest.kt @@ -0,0 +1,103 @@ +package com.algolia.client + +import com.algolia.client.api.InsightsClient +import com.algolia.client.configuration.* +import com.algolia.client.model.insights.* +import com.algolia.client.transport.* +import com.algolia.extension.* +import com.algolia.utils.* +import io.ktor.http.* +import kotlinx.coroutines.test.* +import kotlinx.serialization.json.* +import kotlin.test.* + +class InsightsTest { + + @Test + fun `calls api with correct user agent`() = runTest { + val client = InsightsClient(appId = "appId", apiKey = "apiKey", region = "us") + client.runTest( + call = { + post( + path = "/test", + ) + }, + intercept = { + val regexp = "^Algolia for Kotlin \\(\\d+\\.\\d+\\.\\d+(-.*)?\\)(; [a-zA-Z. ]+ (\\(\\d+((\\.\\d+)?\\.\\d+)?(-.*)?\\))?)*(; Insights (\\(\\d+\\.\\d+\\.\\d+(-.*)?\\)))(; [a-zA-Z. ]+ (\\(\\d+((\\.\\d+)?\\.\\d+)?(-.*)?\\))?)*$".toRegex() + val header = it.url.parameters["X-Algolia-Agent"]?.decodeURLPart().orEmpty() + assertTrue(actual = header.matches(regexp), message = "Expected $header to match the following regex: $regexp") + }, + ) + } + + @Test + fun `calls api with default read timeouts`() = runTest { + val client = InsightsClient(appId = "appId", apiKey = "apiKey", region = "us") + client.runTest( + call = { + get( + path = "/test", + ) + }, + intercept = { + assertEquals(2000, it.connectTimeout) + assertEquals(5000, it.socketTimeout) + }, + ) + } + + @Test + fun `calls api with default write timeouts`() = runTest { + val client = InsightsClient(appId = "appId", apiKey = "apiKey", region = "us") + client.runTest( + call = { + post( + path = "/test", + ) + }, + intercept = { + assertEquals(2000, it.connectTimeout) + assertEquals(30000, it.socketTimeout) + }, + ) + } + + @Test + fun `fallbacks to the alias when region is not given`() = runTest { + val client = InsightsClient(appId = "my-app-id", apiKey = "my-api-key") + client.runTest( + call = { + pushEvents( + insightEvents = InsightEvents( + events = listOf(), + ), + ) + }, + intercept = { + assertEquals("insights.algolia.io", it.url.host) + }, + ) + } + + @Test + fun `uses the correct region`() = runTest { + val client = InsightsClient(appId = "my-app-id", apiKey = "my-api-key", "us") + client.runTest( + call = { + del( + path = "/test", + ) + }, + intercept = { + assertEquals("insights.us.algolia.io", it.url.host) + }, + ) + } + + @Test + fun `throws when incorrect region is given`() = runTest { + assertFails { + val client = InsightsClient(appId = "my-app-id", apiKey = "my-api-key", "not_a_region") + }.let { error -> assertError(error, "`region` must be one of the following: de, us") } + } +} diff --git a/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/PersonalizationTest.kt b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/PersonalizationTest.kt new file mode 100644 index 0000000000..ef1e82f196 --- /dev/null +++ b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/PersonalizationTest.kt @@ -0,0 +1,83 @@ +package com.algolia.client + +import com.algolia.client.api.PersonalizationClient +import com.algolia.client.configuration.* +import com.algolia.client.model.personalization.* +import com.algolia.client.transport.* +import com.algolia.extension.* +import com.algolia.utils.* +import io.ktor.http.* +import kotlinx.coroutines.test.* +import kotlinx.serialization.json.* +import kotlin.test.* + +class PersonalizationTest { + + @Test + fun `calls api with correct user agent`() = runTest { + val client = PersonalizationClient(appId = "appId", apiKey = "apiKey", region = "us") + client.runTest( + call = { + post( + path = "/test", + ) + }, + intercept = { + val regexp = "^Algolia for Kotlin \\(\\d+\\.\\d+\\.\\d+(-.*)?\\)(; [a-zA-Z. ]+ (\\(\\d+((\\.\\d+)?\\.\\d+)?(-.*)?\\))?)*(; Personalization (\\(\\d+\\.\\d+\\.\\d+(-.*)?\\)))(; [a-zA-Z. ]+ (\\(\\d+((\\.\\d+)?\\.\\d+)?(-.*)?\\))?)*$".toRegex() + val header = it.url.parameters["X-Algolia-Agent"]?.decodeURLPart().orEmpty() + assertTrue(actual = header.matches(regexp), message = "Expected $header to match the following regex: $regexp") + }, + ) + } + + @Test + fun `calls api with default read timeouts`() = runTest { + val client = PersonalizationClient(appId = "appId", apiKey = "apiKey", region = "us") + client.runTest( + call = { + get( + path = "/test", + ) + }, + intercept = { + assertEquals(2000, it.connectTimeout) + assertEquals(5000, it.socketTimeout) + }, + ) + } + + @Test + fun `calls api with default write timeouts`() = runTest { + val client = PersonalizationClient(appId = "appId", apiKey = "apiKey", region = "us") + client.runTest( + call = { + post( + path = "/test", + ) + }, + intercept = { + assertEquals(2000, it.connectTimeout) + assertEquals(30000, it.socketTimeout) + }, + ) + } + + @Test + fun `throws when region is not given`() = runTest { + assertFails { + val client = PersonalizationClient(appId = "my-app-id", apiKey = "my-api-key", "") + }.let { error -> assertError(error, "`region` is required and must be one of the following: eu, us") } + } + + @Test + fun `throws when incorrect region is given`() = runTest { + assertFails { + val client = PersonalizationClient(appId = "my-app-id", apiKey = "my-api-key", "not_a_region") + }.let { error -> assertError(error, "`region` is required and must be one of the following: eu, us") } + } + + @Test + fun `does not throw when region is given`() = runTest { + val client = PersonalizationClient(appId = "my-app-id", apiKey = "my-api-key", "us") + } +} diff --git a/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/PredictTest.kt b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/PredictTest.kt new file mode 100644 index 0000000000..dab5c74ef8 --- /dev/null +++ b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/PredictTest.kt @@ -0,0 +1,83 @@ +package com.algolia.client + +import com.algolia.client.api.PredictClient +import com.algolia.client.configuration.* +import com.algolia.client.model.predict.* +import com.algolia.client.transport.* +import com.algolia.extension.* +import com.algolia.utils.* +import io.ktor.http.* +import kotlinx.coroutines.test.* +import kotlinx.serialization.json.* +import kotlin.test.* + +class PredictTest { + + @Test + fun `calls api with correct user agent`() = runTest { + val client = PredictClient(appId = "appId", apiKey = "apiKey", region = "eu") + client.runTest( + call = { + post( + path = "/test", + ) + }, + intercept = { + val regexp = "^Algolia for Kotlin \\(\\d+\\.\\d+\\.\\d+(-.*)?\\)(; [a-zA-Z. ]+ (\\(\\d+((\\.\\d+)?\\.\\d+)?(-.*)?\\))?)*(; Predict (\\(\\d+\\.\\d+\\.\\d+(-.*)?\\)))(; [a-zA-Z. ]+ (\\(\\d+((\\.\\d+)?\\.\\d+)?(-.*)?\\))?)*$".toRegex() + val header = it.url.parameters["X-Algolia-Agent"]?.decodeURLPart().orEmpty() + assertTrue(actual = header.matches(regexp), message = "Expected $header to match the following regex: $regexp") + }, + ) + } + + @Test + fun `calls api with default read timeouts`() = runTest { + val client = PredictClient(appId = "appId", apiKey = "apiKey", region = "eu") + client.runTest( + call = { + get( + path = "/test", + ) + }, + intercept = { + assertEquals(2000, it.connectTimeout) + assertEquals(5000, it.socketTimeout) + }, + ) + } + + @Test + fun `calls api with default write timeouts`() = runTest { + val client = PredictClient(appId = "appId", apiKey = "apiKey", region = "eu") + client.runTest( + call = { + post( + path = "/test", + ) + }, + intercept = { + assertEquals(2000, it.connectTimeout) + assertEquals(30000, it.socketTimeout) + }, + ) + } + + @Test + fun `throws when region is not given`() = runTest { + assertFails { + val client = PredictClient(appId = "my-app-id", apiKey = "my-api-key", "") + }.let { error -> assertError(error, "`region` is required and must be one of the following: eu, us") } + } + + @Test + fun `throws when incorrect region is given`() = runTest { + assertFails { + val client = PredictClient(appId = "my-app-id", apiKey = "my-api-key", "not_a_region") + }.let { error -> assertError(error, "`region` is required and must be one of the following: eu, us") } + } + + @Test + fun `does not throw when region is given`() = runTest { + val client = PredictClient(appId = "my-app-id", apiKey = "my-api-key", "eu") + } +} diff --git a/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/QuerySuggestionsTest.kt b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/QuerySuggestionsTest.kt new file mode 100644 index 0000000000..d8acd1bff7 --- /dev/null +++ b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/QuerySuggestionsTest.kt @@ -0,0 +1,83 @@ +package com.algolia.client + +import com.algolia.client.api.QuerySuggestionsClient +import com.algolia.client.configuration.* +import com.algolia.client.model.querysuggestions.* +import com.algolia.client.transport.* +import com.algolia.extension.* +import com.algolia.utils.* +import io.ktor.http.* +import kotlinx.coroutines.test.* +import kotlinx.serialization.json.* +import kotlin.test.* + +class QuerySuggestionsTest { + + @Test + fun `calls api with correct user agent`() = runTest { + val client = QuerySuggestionsClient(appId = "appId", apiKey = "apiKey", region = "us") + client.runTest( + call = { + post( + path = "/test", + ) + }, + intercept = { + val regexp = "^Algolia for Kotlin \\(\\d+\\.\\d+\\.\\d+(-.*)?\\)(; [a-zA-Z. ]+ (\\(\\d+((\\.\\d+)?\\.\\d+)?(-.*)?\\))?)*(; QuerySuggestions (\\(\\d+\\.\\d+\\.\\d+(-.*)?\\)))(; [a-zA-Z. ]+ (\\(\\d+((\\.\\d+)?\\.\\d+)?(-.*)?\\))?)*$".toRegex() + val header = it.url.parameters["X-Algolia-Agent"]?.decodeURLPart().orEmpty() + assertTrue(actual = header.matches(regexp), message = "Expected $header to match the following regex: $regexp") + }, + ) + } + + @Test + fun `calls api with default read timeouts`() = runTest { + val client = QuerySuggestionsClient(appId = "appId", apiKey = "apiKey", region = "us") + client.runTest( + call = { + get( + path = "/test", + ) + }, + intercept = { + assertEquals(2000, it.connectTimeout) + assertEquals(5000, it.socketTimeout) + }, + ) + } + + @Test + fun `calls api with default write timeouts`() = runTest { + val client = QuerySuggestionsClient(appId = "appId", apiKey = "apiKey", region = "us") + client.runTest( + call = { + post( + path = "/test", + ) + }, + intercept = { + assertEquals(2000, it.connectTimeout) + assertEquals(30000, it.socketTimeout) + }, + ) + } + + @Test + fun `throws when region is not given`() = runTest { + assertFails { + val client = QuerySuggestionsClient(appId = "my-app-id", apiKey = "my-api-key", "") + }.let { error -> assertError(error, "`region` is required and must be one of the following: eu, us") } + } + + @Test + fun `throws when incorrect region is given`() = runTest { + assertFails { + val client = QuerySuggestionsClient(appId = "my-app-id", apiKey = "my-api-key", "not_a_region") + }.let { error -> assertError(error, "`region` is required and must be one of the following: eu, us") } + } + + @Test + fun `does not throw when region is given`() = runTest { + val client = QuerySuggestionsClient(appId = "my-app-id", apiKey = "my-api-key", "us") + } +} diff --git a/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/RecommendTest.kt b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/RecommendTest.kt new file mode 100644 index 0000000000..64c22f8a3d --- /dev/null +++ b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/RecommendTest.kt @@ -0,0 +1,94 @@ +package com.algolia.client + +import com.algolia.client.api.RecommendClient +import com.algolia.client.configuration.* +import com.algolia.client.model.recommend.* +import com.algolia.client.transport.* +import com.algolia.extension.* +import com.algolia.utils.* +import io.ktor.http.* +import kotlinx.coroutines.test.* +import kotlinx.serialization.json.* +import kotlin.test.* + +class RecommendTest { + + @Test + fun `calls api with correct read host`() = runTest { + val client = RecommendClient(appId = "test-app-id", apiKey = "test-api-key") + client.runTest( + call = { + get( + path = "/test", + ) + }, + intercept = { + assertEquals("test-app-id-dsn.algolia.net", it.url.host) + }, + ) + } + + @Test + fun `calls api with correct write host`() = runTest { + val client = RecommendClient(appId = "test-app-id", apiKey = "test-api-key") + client.runTest( + call = { + post( + path = "/test", + ) + }, + intercept = { + assertEquals("test-app-id.algolia.net", it.url.host) + }, + ) + } + + @Test + fun `calls api with correct user agent`() = runTest { + val client = RecommendClient(appId = "appId", apiKey = "apiKey") + client.runTest( + call = { + post( + path = "/test", + ) + }, + intercept = { + val regexp = "^Algolia for Kotlin \\(\\d+\\.\\d+\\.\\d+(-.*)?\\)(; [a-zA-Z. ]+ (\\(\\d+((\\.\\d+)?\\.\\d+)?(-.*)?\\))?)*(; Recommend (\\(\\d+\\.\\d+\\.\\d+(-.*)?\\)))(; [a-zA-Z. ]+ (\\(\\d+((\\.\\d+)?\\.\\d+)?(-.*)?\\))?)*$".toRegex() + val header = it.url.parameters["X-Algolia-Agent"]?.decodeURLPart().orEmpty() + assertTrue(actual = header.matches(regexp), message = "Expected $header to match the following regex: $regexp") + }, + ) + } + + @Test + fun `calls api with default read timeouts`() = runTest { + val client = RecommendClient(appId = "appId", apiKey = "apiKey") + client.runTest( + call = { + get( + path = "/test", + ) + }, + intercept = { + assertEquals(2000, it.connectTimeout) + assertEquals(5000, it.socketTimeout) + }, + ) + } + + @Test + fun `calls api with default write timeouts`() = runTest { + val client = RecommendClient(appId = "appId", apiKey = "apiKey") + client.runTest( + call = { + post( + path = "/test", + ) + }, + intercept = { + assertEquals(2000, it.connectTimeout) + assertEquals(30000, it.socketTimeout) + }, + ) + } +} 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 new file mode 100644 index 0000000000..79636342d5 --- /dev/null +++ b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/client/SearchTest.kt @@ -0,0 +1,145 @@ +package com.algolia.client + +import com.algolia.client.api.SearchClient +import com.algolia.client.configuration.* +import com.algolia.client.model.search.* +import com.algolia.client.transport.* +import com.algolia.extension.* +import com.algolia.utils.* +import io.ktor.http.* +import kotlinx.coroutines.test.* +import kotlinx.serialization.json.* +import kotlin.test.* + +class SearchTest { + + @Test + fun `calls api with correct read host`() = runTest { + val client = SearchClient(appId = "test-app-id", apiKey = "test-api-key") + client.runTest( + call = { + get( + path = "/test", + ) + }, + intercept = { + assertEquals("test-app-id-dsn.algolia.net", it.url.host) + }, + ) + } + + @Test + fun `calls api with correct write host`() = runTest { + val client = SearchClient(appId = "test-app-id", apiKey = "test-api-key") + client.runTest( + call = { + post( + path = "/test", + ) + }, + intercept = { + assertEquals("test-app-id.algolia.net", it.url.host) + }, + ) + } + + @Test + fun `calls api with correct user agent`() = runTest { + val client = SearchClient(appId = "appId", apiKey = "apiKey") + client.runTest( + call = { + post( + path = "/test", + ) + }, + intercept = { + val regexp = "^Algolia for Kotlin \\(\\d+\\.\\d+\\.\\d+(-.*)?\\)(; [a-zA-Z. ]+ (\\(\\d+((\\.\\d+)?\\.\\d+)?(-.*)?\\))?)*(; Search (\\(\\d+\\.\\d+\\.\\d+(-.*)?\\)))(; [a-zA-Z. ]+ (\\(\\d+((\\.\\d+)?\\.\\d+)?(-.*)?\\))?)*$".toRegex() + val header = it.url.parameters["X-Algolia-Agent"]?.decodeURLPart().orEmpty() + assertTrue(actual = header.matches(regexp), message = "Expected $header to match the following regex: $regexp") + }, + ) + } + + @Test + fun `calls api with default read timeouts`() = runTest { + val client = SearchClient(appId = "appId", apiKey = "apiKey") + client.runTest( + call = { + get( + path = "/test", + ) + }, + intercept = { + assertEquals(2000, it.connectTimeout) + assertEquals(5000, it.socketTimeout) + }, + ) + } + + @Test + fun `calls api with default write timeouts`() = runTest { + val client = SearchClient(appId = "appId", apiKey = "apiKey") + client.runTest( + call = { + post( + path = "/test", + ) + }, + intercept = { + assertEquals(2000, it.connectTimeout) + assertEquals(30000, it.socketTimeout) + }, + ) + } + + @Test + fun `client throws with invalid parameters`() = runTest { + assertFails { + val client = SearchClient(appId = "", apiKey = "") + }.let { error -> assertError(error, "`appId` is missing.") } + assertFails { + val client = SearchClient(appId = "", apiKey = "my-api-key") + }.let { error -> assertError(error, "`appId` is missing.") } + assertFails { + val client = SearchClient(appId = "my-app-id", apiKey = "") + }.let { error -> assertError(error, "`apiKey` is missing.") } + } + + @Test + fun `'addApiKey' throws with invalid parameters`() = runTest { + val client = SearchClient(appId = "appId", apiKey = "apiKey") + assertFails { + client.addApiKey( + apiKey = empty(), + ) + }.let { error -> assertError(error, "Parameter `apiKey` is required when calling `addApiKey`.") } + } + + @Test + fun `'addOrUpdateObject' throws with invalid parameters`() = runTest { + val client = SearchClient(appId = "appId", apiKey = "apiKey") + assertFails { + client.addOrUpdateObject( + indexName = empty(), + objectID = "my-object-id", + body = buildJsonObject { + }, + ) + }.let { error -> assertError(error, "Parameter `indexName` is required when calling `addOrUpdateObject`.") } + assertFails { + client.addOrUpdateObject( + indexName = "my-index-name", + objectID = empty(), + body = buildJsonObject { + }, + ) + }.let { error -> assertError(error, "Parameter `objectID` is required when calling `addOrUpdateObject`.") } + assertFails { + client.addOrUpdateObject( + indexName = "my-index-name", + objectID = "my-object-id", + body = empty(), + ) + }.let { error -> assertError(error, "Parameter `body` is required when calling `addOrUpdateObject`.") } + } +} diff --git a/tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/AbtestingTest.kt b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/AbtestingTest.kt new file mode 100644 index 0000000000..1cc8b001f7 --- /dev/null +++ b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/AbtestingTest.kt @@ -0,0 +1,561 @@ +package com.algolia.methods.requests + +import com.algolia.client.api.AbtestingClient +import com.algolia.client.configuration.* +import com.algolia.client.model.abtesting.* +import com.algolia.client.transport.* +import com.algolia.extension.* +import com.algolia.utils.* +import io.ktor.http.* +import kotlinx.coroutines.test.* +import kotlinx.serialization.json.* +import kotlin.test.* + +class AbtestingTest { + + val client = AbtestingClient( + appId = "appId", + apiKey = "apiKey", + region = "us", + ) + + // addABTests + + @Test + fun `addABTests with minimal parameters`() = runTest { + client.runTest( + call = { + addABTests( + addABTestsRequest = AddABTestsRequest( + endAt = "2022-12-31T00:00:00.000Z", + name = "myABTest", + variant = listOf( + AbTestsVariant( + index = "AB_TEST_1", + trafficPercentage = 30, + ), + AbTestsVariant( + index = "AB_TEST_2", + trafficPercentage = 50, + ), + ), + ), + ) + }, + intercept = { + assertEquals("/2/abtests".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"endAt":"2022-12-31T00:00:00.000Z","name":"myABTest","variant":[{"index":"AB_TEST_1","trafficPercentage":30},{"index":"AB_TEST_2","trafficPercentage":50}]}""", it.body) + }, + ) + } + + // del + + @Test + fun `allow del method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + del( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `allow del method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + del( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // deleteABTest + + @Test + fun `deleteABTest`() = runTest { + client.runTest( + call = { + deleteABTest( + id = 42, + ) + }, + intercept = { + assertEquals("/2/abtests/42".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertNoBody(it.body) + }, + ) + } + + // get + + @Test + fun `allow get method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + get( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `allow get method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + get( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // getABTest + + @Test + fun `getABTest`() = runTest { + client.runTest( + call = { + getABTest( + id = 42, + ) + }, + intercept = { + assertEquals("/2/abtests/42".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // listABTests + + @Test + fun `listABTests with minimal parameters`() = runTest { + client.runTest( + call = { + listABTests() + }, + intercept = { + assertEquals("/2/abtests".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `listABTests with parameters`() = runTest { + client.runTest( + call = { + listABTests( + offset = 42, + limit = 21, + indexPrefix = "foo", + indexSuffix = "bar", + ) + }, + intercept = { + assertEquals("/2/abtests".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"offset":"42","limit":"21","indexPrefix":"foo","indexSuffix":"bar"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // post + + @Test + fun `allow post method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + post( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{}""", it.body) + }, + ) + } + + @Test + fun `allow post method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + post( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "body", + JsonPrimitive("parameters"), + ) + }, + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"body":"parameters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions can override default query parameters`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("query", "myQueryParameter") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"myQueryParameter"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions merges query parameters with default ones`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("query2", "myQueryParameter") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","query2":"myQueryParameter"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions can override default headers`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + headers = buildMap { + put("x-algolia-api-key", "myApiKey") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"x-algolia-api-key":"myApiKey"}""", it.headers) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions merges headers with default ones`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + headers = buildMap { + put("x-algolia-api-key", "myApiKey") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"x-algolia-api-key":"myApiKey"}""", it.headers) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts booleans`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("isItWorking", true) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","isItWorking":"true"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts integers`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", 2) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"2"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts list of string`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", listOf("c", "d")) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"c,d"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts list of booleans`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", listOf(true, true, false)) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"true,true,false"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts list of integers`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", listOf(1, 2)) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"1,2"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + // put + + @Test + fun `allow put method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + put( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertJsonBody("""{}""", it.body) + }, + ) + } + + @Test + fun `allow put method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + put( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "body", + JsonPrimitive("parameters"), + ) + }, + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"body":"parameters"}""", it.body) + }, + ) + } + + // stopABTest + + @Test + fun `stopABTest`() = runTest { + client.runTest( + call = { + stopABTest( + id = 42, + ) + }, + intercept = { + assertEquals("/2/abtests/42/stop".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertEmptyBody(it.body) + }, + ) + } +} diff --git a/tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/AnalyticsTest.kt b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/AnalyticsTest.kt new file mode 100644 index 0000000000..86bdffbab1 --- /dev/null +++ b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/AnalyticsTest.kt @@ -0,0 +1,1151 @@ +package com.algolia.methods.requests + +import com.algolia.client.api.AnalyticsClient +import com.algolia.client.configuration.* +import com.algolia.client.model.analytics.* +import com.algolia.client.transport.* +import com.algolia.extension.* +import com.algolia.utils.* +import io.ktor.http.* +import kotlinx.coroutines.test.* +import kotlinx.serialization.json.* +import kotlin.test.* + +class AnalyticsTest { + + val client = AnalyticsClient( + appId = "appId", + apiKey = "apiKey", + region = "us", + ) + + // del + + @Test + fun `allow del method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + del( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `allow del method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + del( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // get + + @Test + fun `allow get method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + get( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `allow get method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + get( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // getAverageClickPosition + + @Test + fun `get getAverageClickPosition with minimal parameters`() = runTest { + client.runTest( + call = { + getAverageClickPosition( + index = "index", + ) + }, + intercept = { + assertEquals("/2/clicks/averageClickPosition".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `get getAverageClickPosition with all parameters`() = runTest { + client.runTest( + call = { + getAverageClickPosition( + index = "index", + startDate = "1999-09-19", + endDate = "2001-01-01", + tags = "tag", + ) + }, + intercept = { + assertEquals("/2/clicks/averageClickPosition".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","tags":"tag"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // getClickPositions + + @Test + fun `get getClickPositions with minimal parameters`() = runTest { + client.runTest( + call = { + getClickPositions( + index = "index", + ) + }, + intercept = { + assertEquals("/2/clicks/positions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `get getClickPositions with all parameters`() = runTest { + client.runTest( + call = { + getClickPositions( + index = "index", + startDate = "1999-09-19", + endDate = "2001-01-01", + tags = "tag", + ) + }, + intercept = { + assertEquals("/2/clicks/positions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","tags":"tag"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // getClickThroughRate + + @Test + fun `get getClickThroughRate with minimal parameters`() = runTest { + client.runTest( + call = { + getClickThroughRate( + index = "index", + ) + }, + intercept = { + assertEquals("/2/clicks/clickThroughRate".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `get getClickThroughRate with all parameters`() = runTest { + client.runTest( + call = { + getClickThroughRate( + index = "index", + startDate = "1999-09-19", + endDate = "2001-01-01", + tags = "tag", + ) + }, + intercept = { + assertEquals("/2/clicks/clickThroughRate".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","tags":"tag"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // getConversationRate + + @Test + fun `get getConversationRate with minimal parameters`() = runTest { + client.runTest( + call = { + getConversationRate( + index = "index", + ) + }, + intercept = { + assertEquals("/2/conversions/conversionRate".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `get getConversationRate with all parameters`() = runTest { + client.runTest( + call = { + getConversationRate( + index = "index", + startDate = "1999-09-19", + endDate = "2001-01-01", + tags = "tag", + ) + }, + intercept = { + assertEquals("/2/conversions/conversionRate".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","tags":"tag"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // getNoClickRate + + @Test + fun `get getNoClickRate with minimal parameters`() = runTest { + client.runTest( + call = { + getNoClickRate( + index = "index", + ) + }, + intercept = { + assertEquals("/2/searches/noClickRate".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `get getNoClickRate with all parameters`() = runTest { + client.runTest( + call = { + getNoClickRate( + index = "index", + startDate = "1999-09-19", + endDate = "2001-01-01", + tags = "tag", + ) + }, + intercept = { + assertEquals("/2/searches/noClickRate".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","tags":"tag"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // getNoResultsRate + + @Test + fun `get getNoResultsRate with minimal parameters`() = runTest { + client.runTest( + call = { + getNoResultsRate( + index = "index", + ) + }, + intercept = { + assertEquals("/2/searches/noResultRate".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `get getNoResultsRate with all parameters`() = runTest { + client.runTest( + call = { + getNoResultsRate( + index = "index", + startDate = "1999-09-19", + endDate = "2001-01-01", + tags = "tag", + ) + }, + intercept = { + assertEquals("/2/searches/noResultRate".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","tags":"tag"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // getSearchesCount + + @Test + fun `get getSearchesCount with minimal parameters`() = runTest { + client.runTest( + call = { + getSearchesCount( + index = "index", + ) + }, + intercept = { + assertEquals("/2/searches/count".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `get getSearchesCount with all parameters`() = runTest { + client.runTest( + call = { + getSearchesCount( + index = "index", + startDate = "1999-09-19", + endDate = "2001-01-01", + tags = "tag", + ) + }, + intercept = { + assertEquals("/2/searches/count".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","tags":"tag"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // getSearchesNoClicks + + @Test + fun `get getSearchesNoClicks with minimal parameters`() = runTest { + client.runTest( + call = { + getSearchesNoClicks( + index = "index", + ) + }, + intercept = { + assertEquals("/2/searches/noClicks".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `get getSearchesNoClicks with all parameters`() = runTest { + client.runTest( + call = { + getSearchesNoClicks( + index = "index", + startDate = "1999-09-19", + endDate = "2001-01-01", + limit = 21, + offset = 42, + tags = "tag", + ) + }, + intercept = { + assertEquals("/2/searches/noClicks".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","limit":"21","offset":"42","tags":"tag"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // getSearchesNoResults + + @Test + fun `get getSearchesNoResults with minimal parameters`() = runTest { + client.runTest( + call = { + getSearchesNoResults( + index = "index", + ) + }, + intercept = { + assertEquals("/2/searches/noResults".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `get getSearchesNoResults with all parameters`() = runTest { + client.runTest( + call = { + getSearchesNoResults( + index = "index", + startDate = "1999-09-19", + endDate = "2001-01-01", + limit = 21, + offset = 42, + tags = "tag", + ) + }, + intercept = { + assertEquals("/2/searches/noResults".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","limit":"21","offset":"42","tags":"tag"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // getStatus + + @Test + fun `get getStatus with minimal parameters`() = runTest { + client.runTest( + call = { + getStatus( + index = "index", + ) + }, + intercept = { + assertEquals("/2/status".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // getTopCountries + + @Test + fun `get getTopCountries with minimal parameters`() = runTest { + client.runTest( + call = { + getTopCountries( + index = "index", + ) + }, + intercept = { + assertEquals("/2/countries".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `get getTopCountries with all parameters`() = runTest { + client.runTest( + call = { + getTopCountries( + index = "index", + startDate = "1999-09-19", + endDate = "2001-01-01", + limit = 21, + offset = 42, + tags = "tag", + ) + }, + intercept = { + assertEquals("/2/countries".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","limit":"21","offset":"42","tags":"tag"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // getTopFilterAttributes + + @Test + fun `get getTopFilterAttributes with minimal parameters`() = runTest { + client.runTest( + call = { + getTopFilterAttributes( + index = "index", + ) + }, + intercept = { + assertEquals("/2/filters".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `get getTopFilterAttributes with all parameters`() = runTest { + client.runTest( + call = { + getTopFilterAttributes( + index = "index", + search = "mySearch", + startDate = "1999-09-19", + endDate = "2001-01-01", + limit = 21, + offset = 42, + tags = "tag", + ) + }, + intercept = { + assertEquals("/2/filters".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index","search":"mySearch","startDate":"1999-09-19","endDate":"2001-01-01","limit":"21","offset":"42","tags":"tag"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // getTopFilterForAttribute + + @Test + fun `get getTopFilterForAttribute with minimal parameters`() = runTest { + client.runTest( + call = { + getTopFilterForAttribute( + attribute = "myAttribute", + index = "index", + ) + }, + intercept = { + assertEquals("/2/filters/myAttribute".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `get getTopFilterForAttribute with minimal parameters and multiple attributes`() = runTest { + client.runTest( + call = { + getTopFilterForAttribute( + attribute = "myAttribute1,myAttribute2", + index = "index", + ) + }, + intercept = { + assertEquals("/2/filters/myAttribute1%2CmyAttribute2".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `get getTopFilterForAttribute with all parameters`() = runTest { + client.runTest( + call = { + getTopFilterForAttribute( + attribute = "myAttribute", + index = "index", + search = "mySearch", + startDate = "1999-09-19", + endDate = "2001-01-01", + limit = 21, + offset = 42, + tags = "tag", + ) + }, + intercept = { + assertEquals("/2/filters/myAttribute".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index","search":"mySearch","startDate":"1999-09-19","endDate":"2001-01-01","limit":"21","offset":"42","tags":"tag"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `get getTopFilterForAttribute with all parameters and multiple attributes`() = runTest { + client.runTest( + call = { + getTopFilterForAttribute( + attribute = "myAttribute1,myAttribute2", + index = "index", + search = "mySearch", + startDate = "1999-09-19", + endDate = "2001-01-01", + limit = 21, + offset = 42, + tags = "tag", + ) + }, + intercept = { + assertEquals("/2/filters/myAttribute1%2CmyAttribute2".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index","search":"mySearch","startDate":"1999-09-19","endDate":"2001-01-01","limit":"21","offset":"42","tags":"tag"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // getTopFiltersNoResults + + @Test + fun `get getTopFiltersNoResults with minimal parameters`() = runTest { + client.runTest( + call = { + getTopFiltersNoResults( + index = "index", + ) + }, + intercept = { + assertEquals("/2/filters/noResults".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `get getTopFiltersNoResults with all parameters`() = runTest { + client.runTest( + call = { + getTopFiltersNoResults( + index = "index", + search = "mySearch", + startDate = "1999-09-19", + endDate = "2001-01-01", + limit = 21, + offset = 42, + tags = "tag", + ) + }, + intercept = { + assertEquals("/2/filters/noResults".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index","search":"mySearch","startDate":"1999-09-19","endDate":"2001-01-01","limit":"21","offset":"42","tags":"tag"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // getTopHits + + @Test + fun `get getTopHits with minimal parameters`() = runTest { + client.runTest( + call = { + getTopHits( + index = "index", + ) + }, + intercept = { + assertEquals("/2/hits".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `get getTopHits with all parameters`() = runTest { + client.runTest( + call = { + getTopHits( + index = "index", + search = "mySearch", + clickAnalytics = true, + startDate = "1999-09-19", + endDate = "2001-01-01", + limit = 21, + offset = 42, + tags = "tag", + ) + }, + intercept = { + assertEquals("/2/hits".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index","search":"mySearch","clickAnalytics":"true","startDate":"1999-09-19","endDate":"2001-01-01","limit":"21","offset":"42","tags":"tag"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // getTopSearches + + @Test + fun `get getTopSearches with minimal parameters`() = runTest { + client.runTest( + call = { + getTopSearches( + index = "index", + ) + }, + intercept = { + assertEquals("/2/searches".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `get getTopSearches with all parameters`() = runTest { + client.runTest( + call = { + getTopSearches( + index = "index", + clickAnalytics = true, + startDate = "1999-09-19", + endDate = "2001-01-01", + orderBy = OrderBy.values().first { it.value == "searchCount" }, + direction = Direction.values().first { it.value == "asc" }, + limit = 21, + offset = 42, + tags = "tag", + ) + }, + intercept = { + assertEquals("/2/searches".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index","clickAnalytics":"true","startDate":"1999-09-19","endDate":"2001-01-01","orderBy":"searchCount","direction":"asc","limit":"21","offset":"42","tags":"tag"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // getUsersCount + + @Test + fun `get getUsersCount with minimal parameters`() = runTest { + client.runTest( + call = { + getUsersCount( + index = "index", + ) + }, + intercept = { + assertEquals("/2/users/count".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `get getUsersCount with all parameters`() = runTest { + client.runTest( + call = { + getUsersCount( + index = "index", + startDate = "1999-09-19", + endDate = "2001-01-01", + tags = "tag", + ) + }, + intercept = { + assertEquals("/2/users/count".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"index":"index","startDate":"1999-09-19","endDate":"2001-01-01","tags":"tag"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // post + + @Test + fun `allow post method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + post( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{}""", it.body) + }, + ) + } + + @Test + fun `allow post method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + post( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "body", + JsonPrimitive("parameters"), + ) + }, + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"body":"parameters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions can override default query parameters`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("query", "myQueryParameter") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"myQueryParameter"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions merges query parameters with default ones`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("query2", "myQueryParameter") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","query2":"myQueryParameter"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions can override default headers`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + headers = buildMap { + put("x-algolia-api-key", "myApiKey") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"x-algolia-api-key":"myApiKey"}""", it.headers) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions merges headers with default ones`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + headers = buildMap { + put("x-algolia-api-key", "myApiKey") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"x-algolia-api-key":"myApiKey"}""", it.headers) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts booleans`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("isItWorking", true) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","isItWorking":"true"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts integers`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", 2) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"2"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts list of string`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", listOf("c", "d")) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"c,d"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts list of booleans`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", listOf(true, true, false)) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"true,true,false"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts list of integers`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", listOf(1, 2)) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"1,2"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + // put + + @Test + fun `allow put method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + put( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertJsonBody("""{}""", it.body) + }, + ) + } + + @Test + fun `allow put method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + put( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "body", + JsonPrimitive("parameters"), + ) + }, + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"body":"parameters"}""", it.body) + }, + ) + } +} diff --git a/tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/IngestionTest.kt b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/IngestionTest.kt new file mode 100644 index 0000000000..9714257101 --- /dev/null +++ b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/IngestionTest.kt @@ -0,0 +1,1111 @@ +package com.algolia.methods.requests + +import com.algolia.client.api.IngestionClient +import com.algolia.client.configuration.* +import com.algolia.client.model.ingestion.* +import com.algolia.client.transport.* +import com.algolia.extension.* +import com.algolia.utils.* +import io.ktor.http.* +import kotlinx.coroutines.test.* +import kotlinx.serialization.json.* +import kotlin.test.* + +class IngestionTest { + + val client = IngestionClient( + appId = "appId", + apiKey = "apiKey", + region = "us", + ) + + // createAuthentication + + @Test + fun `createAuthenticationOAuth`() = runTest { + client.runTest( + call = { + createAuthentication( + authenticationCreate = AuthenticationCreate( + type = AuthenticationType.values().first { it.value == "oauth" }, + name = "authName", + input = AuthOAuth( + url = "http://test.oauth", + clientId = "myID", + clientSecret = "mySecret", + ), + ), + ) + }, + intercept = { + assertEquals("/1/authentications".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"type":"oauth","name":"authName","input":{"url":"http://test.oauth","client_id":"myID","client_secret":"mySecret"}}""", it.body) + }, + ) + } + + @Test + fun `createAuthenticationAlgolia`() = runTest { + client.runTest( + call = { + createAuthentication( + authenticationCreate = AuthenticationCreate( + type = AuthenticationType.values().first { it.value == "algolia" }, + name = "authName", + input = AuthAlgolia( + appID = "myappID", + apiKey = "randomApiKey", + ), + ), + ) + }, + intercept = { + assertEquals("/1/authentications".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"type":"algolia","name":"authName","input":{"appID":"myappID","apiKey":"randomApiKey"}}""", it.body) + }, + ) + } + + // createDestination + + @Test + fun `createDestination`() = runTest { + client.runTest( + call = { + createDestination( + destinationCreate = DestinationCreate( + type = DestinationType.values().first { it.value == "search" }, + name = "destinationName", + input = DestinationIndexPrefix( + indexPrefix = "prefix_", + ), + authenticationID = "6c02aeb1-775e-418e-870b-1faccd4b2c0f", + ), + ) + }, + intercept = { + assertEquals("/1/destinations".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"type":"search","name":"destinationName","input":{"indexPrefix":"prefix_"},"authenticationID":"6c02aeb1-775e-418e-870b-1faccd4b2c0f"}""", it.body) + }, + ) + } + + // createSource + + @Test + fun `createSource`() = runTest { + client.runTest( + call = { + createSource( + sourceCreate = SourceCreate( + type = SourceType.values().first { it.value == "commercetools" }, + name = "sourceName", + input = SourceCommercetools( + storeKeys = listOf("myStore"), + locales = listOf("de"), + url = "http://commercetools.com", + projectKey = "keyID", + ), + authenticationID = "6c02aeb1-775e-418e-870b-1faccd4b2c0f", + ), + ) + }, + intercept = { + assertEquals("/1/sources".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"type":"commercetools","name":"sourceName","input":{"storeKeys":["myStore"],"locales":["de"],"url":"http://commercetools.com","projectKey":"keyID"},"authenticationID":"6c02aeb1-775e-418e-870b-1faccd4b2c0f"}""", it.body) + }, + ) + } + + // createTask + + @Test + fun `createTaskOnDemand`() = runTest { + client.runTest( + call = { + createTask( + taskCreate = TaskCreate( + sourceID = "search", + destinationID = "destinationName", + trigger = OnDemandTriggerInput( + type = OnDemandTriggerType.values().first { it.value == "onDemand" }, + ), + action = ActionType.values().first { it.value == "replace" }, + ), + ) + }, + intercept = { + assertEquals("/1/tasks".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"sourceID":"search","destinationID":"destinationName","trigger":{"type":"onDemand"},"action":"replace"}""", it.body) + }, + ) + } + + @Test + fun `createTaskSchedule`() = runTest { + client.runTest( + call = { + createTask( + taskCreate = TaskCreate( + sourceID = "search", + destinationID = "destinationName", + trigger = ScheduleTriggerInput( + type = ScheduleTriggerType.values().first { it.value == "schedule" }, + cron = "* * * * *", + ), + action = ActionType.values().first { it.value == "replace" }, + ), + ) + }, + intercept = { + assertEquals("/1/tasks".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"sourceID":"search","destinationID":"destinationName","trigger":{"type":"schedule","cron":"* * * * *"},"action":"replace"}""", it.body) + }, + ) + } + + @Test + fun `createTaskSubscription`() = runTest { + client.runTest( + call = { + createTask( + taskCreate = TaskCreate( + sourceID = "search", + destinationID = "destinationName", + trigger = OnDemandTriggerInput( + type = OnDemandTriggerType.values().first { it.value == "onDemand" }, + ), + action = ActionType.values().first { it.value == "replace" }, + ), + ) + }, + intercept = { + assertEquals("/1/tasks".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"sourceID":"search","destinationID":"destinationName","trigger":{"type":"onDemand"},"action":"replace"}""", it.body) + }, + ) + } + + // del + + @Test + fun `allow del method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + del( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `allow del method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + del( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // deleteAuthentication + + @Test + fun `deleteAuthentication`() = runTest { + client.runTest( + call = { + deleteAuthentication( + authenticationID = "6c02aeb1-775e-418e-870b-1faccd4b2c0f", + ) + }, + intercept = { + assertEquals("/1/authentications/6c02aeb1-775e-418e-870b-1faccd4b2c0f".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertNoBody(it.body) + }, + ) + } + + // deleteDestination + + @Test + fun `deleteDestination`() = runTest { + client.runTest( + call = { + deleteDestination( + destinationID = "6c02aeb1-775e-418e-870b-1faccd4b2c0f", + ) + }, + intercept = { + assertEquals("/1/destinations/6c02aeb1-775e-418e-870b-1faccd4b2c0f".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertNoBody(it.body) + }, + ) + } + + // deleteSource + + @Test + fun `deleteSource`() = runTest { + client.runTest( + call = { + deleteSource( + sourceID = "6c02aeb1-775e-418e-870b-1faccd4b2c0f", + ) + }, + intercept = { + assertEquals("/1/sources/6c02aeb1-775e-418e-870b-1faccd4b2c0f".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertNoBody(it.body) + }, + ) + } + + // deleteTask + + @Test + fun `deleteTask`() = runTest { + client.runTest( + call = { + deleteTask( + taskID = "6c02aeb1-775e-418e-870b-1faccd4b2c0f", + ) + }, + intercept = { + assertEquals("/1/tasks/6c02aeb1-775e-418e-870b-1faccd4b2c0f".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertNoBody(it.body) + }, + ) + } + + // disableTask + + @Test + fun `disableTask`() = runTest { + client.runTest( + call = { + disableTask( + taskID = "6c02aeb1-775e-418e-870b-1faccd4b2c0f", + ) + }, + intercept = { + assertEquals("/1/tasks/6c02aeb1-775e-418e-870b-1faccd4b2c0f/disable".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertEmptyBody(it.body) + }, + ) + } + + // enableTask + + @Test + fun `enableTask`() = runTest { + client.runTest( + call = { + enableTask( + taskID = "6c02aeb1-775e-418e-870b-1faccd4b2c0f", + ) + }, + intercept = { + assertEquals("/1/tasks/6c02aeb1-775e-418e-870b-1faccd4b2c0f/enable".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertEmptyBody(it.body) + }, + ) + } + + // get + + @Test + fun `allow get method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + get( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `allow get method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + get( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // getAuthentication + + @Test + fun `getAuthentication`() = runTest { + client.runTest( + call = { + getAuthentication( + authenticationID = "6c02aeb1-775e-418e-870b-1faccd4b2c0f", + ) + }, + intercept = { + assertEquals("/1/authentications/6c02aeb1-775e-418e-870b-1faccd4b2c0f".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // getAuthentications + + @Test + fun `getAuthentications`() = runTest { + client.runTest( + call = { + getAuthentications() + }, + intercept = { + assertEquals("/1/authentications".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // getDestination + + @Test + fun `getDestination`() = runTest { + client.runTest( + call = { + getDestination( + destinationID = "6c02aeb1-775e-418e-870b-1faccd4b2c0f", + ) + }, + intercept = { + assertEquals("/1/destinations/6c02aeb1-775e-418e-870b-1faccd4b2c0f".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // getDestinations + + @Test + fun `getDestinations`() = runTest { + client.runTest( + call = { + getDestinations() + }, + intercept = { + assertEquals("/1/destinations".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // getEvent + + @Test + fun `getEvent`() = runTest { + client.runTest( + call = { + getEvent( + runID = "6c02aeb1-775e-418e-870b-1faccd4b2c0f", + eventID = "6c02aeb1-775e-418e-870b-1faccd4b2c0c", + ) + }, + intercept = { + assertEquals("/1/runs/6c02aeb1-775e-418e-870b-1faccd4b2c0f/events/6c02aeb1-775e-418e-870b-1faccd4b2c0c".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // getEvents + + @Test + fun `getEvents`() = runTest { + client.runTest( + call = { + getEvents( + runID = "6c02aeb1-775e-418e-870b-1faccd4b2c0f", + ) + }, + intercept = { + assertEquals("/1/runs/6c02aeb1-775e-418e-870b-1faccd4b2c0f/events".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // getRun + + @Test + fun `getRun`() = runTest { + client.runTest( + call = { + getRun( + runID = "6c02aeb1-775e-418e-870b-1faccd4b2c0f", + ) + }, + intercept = { + assertEquals("/1/runs/6c02aeb1-775e-418e-870b-1faccd4b2c0f".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // getRuns + + @Test + fun `getRuns`() = runTest { + client.runTest( + call = { + getRuns() + }, + intercept = { + assertEquals("/1/runs".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // getSource + + @Test + fun `getSource`() = runTest { + client.runTest( + call = { + getSource( + sourceID = "6c02aeb1-775e-418e-870b-1faccd4b2c0f", + ) + }, + intercept = { + assertEquals("/1/sources/6c02aeb1-775e-418e-870b-1faccd4b2c0f".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // getSources + + @Test + fun `getSources`() = runTest { + client.runTest( + call = { + getSources() + }, + intercept = { + assertEquals("/1/sources".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // getTask + + @Test + fun `getTask`() = runTest { + client.runTest( + call = { + getTask( + taskID = "6c02aeb1-775e-418e-870b-1faccd4b2c0f", + ) + }, + intercept = { + assertEquals("/1/tasks/6c02aeb1-775e-418e-870b-1faccd4b2c0f".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // getTasks + + @Test + fun `getTasks`() = runTest { + client.runTest( + call = { + getTasks() + }, + intercept = { + assertEquals("/1/tasks".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // post + + @Test + fun `allow post method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + post( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{}""", it.body) + }, + ) + } + + @Test + fun `allow post method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + post( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "body", + JsonPrimitive("parameters"), + ) + }, + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"body":"parameters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions can override default query parameters`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("query", "myQueryParameter") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"myQueryParameter"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions merges query parameters with default ones`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("query2", "myQueryParameter") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","query2":"myQueryParameter"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions can override default headers`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + headers = buildMap { + put("x-algolia-api-key", "myApiKey") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"x-algolia-api-key":"myApiKey"}""", it.headers) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions merges headers with default ones`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + headers = buildMap { + put("x-algolia-api-key", "myApiKey") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"x-algolia-api-key":"myApiKey"}""", it.headers) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts booleans`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("isItWorking", true) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","isItWorking":"true"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts integers`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", 2) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"2"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts list of string`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", listOf("c", "d")) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"c,d"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts list of booleans`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", listOf(true, true, false)) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"true,true,false"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts list of integers`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", listOf(1, 2)) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"1,2"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + // put + + @Test + fun `allow put method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + put( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertJsonBody("""{}""", it.body) + }, + ) + } + + @Test + fun `allow put method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + put( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "body", + JsonPrimitive("parameters"), + ) + }, + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"body":"parameters"}""", it.body) + }, + ) + } + + // runTask + + @Test + fun `runTask`() = runTest { + client.runTest( + call = { + runTask( + taskID = "6c02aeb1-775e-418e-870b-1faccd4b2c0f", + ) + }, + intercept = { + assertEquals("/1/tasks/6c02aeb1-775e-418e-870b-1faccd4b2c0f/run".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertEmptyBody(it.body) + }, + ) + } + + // searchAuthentications + + @Test + fun `searchAuthentications`() = runTest { + client.runTest( + call = { + searchAuthentications( + authenticationSearch = AuthenticationSearch( + authenticationIDs = listOf("6c02aeb1-775e-418e-870b-1faccd4b2c0f", "947ac9c4-7e58-4c87-b1e7-14a68e99699a"), + ), + ) + }, + intercept = { + assertEquals("/1/authentications/search".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"authenticationIDs":["6c02aeb1-775e-418e-870b-1faccd4b2c0f","947ac9c4-7e58-4c87-b1e7-14a68e99699a"]}""", it.body) + }, + ) + } + + // searchDestinations + + @Test + fun `searchDestinations`() = runTest { + client.runTest( + call = { + searchDestinations( + destinationSearch = DestinationSearch( + destinationIDs = listOf("6c02aeb1-775e-418e-870b-1faccd4b2c0f", "947ac9c4-7e58-4c87-b1e7-14a68e99699a"), + ), + ) + }, + intercept = { + assertEquals("/1/destinations/search".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"destinationIDs":["6c02aeb1-775e-418e-870b-1faccd4b2c0f","947ac9c4-7e58-4c87-b1e7-14a68e99699a"]}""", it.body) + }, + ) + } + + // searchSources + + @Test + fun `searchSources`() = runTest { + client.runTest( + call = { + searchSources( + sourceSearch = SourceSearch( + sourceIDs = listOf("6c02aeb1-775e-418e-870b-1faccd4b2c0f", "947ac9c4-7e58-4c87-b1e7-14a68e99699a"), + ), + ) + }, + intercept = { + assertEquals("/1/sources/search".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"sourceIDs":["6c02aeb1-775e-418e-870b-1faccd4b2c0f","947ac9c4-7e58-4c87-b1e7-14a68e99699a"]}""", it.body) + }, + ) + } + + // searchTasks + + @Test + fun `searchTasks`() = runTest { + client.runTest( + call = { + searchTasks( + taskSearch = TaskSearch( + taskIDs = listOf("6c02aeb1-775e-418e-870b-1faccd4b2c0f", "947ac9c4-7e58-4c87-b1e7-14a68e99699a"), + ), + ) + }, + intercept = { + assertEquals("/1/tasks/search".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"taskIDs":["6c02aeb1-775e-418e-870b-1faccd4b2c0f","947ac9c4-7e58-4c87-b1e7-14a68e99699a"]}""", it.body) + }, + ) + } + + // updateAuthentication + + @Test + fun `updateAuthentication`() = runTest { + client.runTest( + call = { + updateAuthentication( + authenticationID = "6c02aeb1-775e-418e-870b-1faccd4b2c0f", + authenticationUpdate = AuthenticationUpdate( + name = "newName", + ), + ) + }, + intercept = { + assertEquals("/1/authentications/6c02aeb1-775e-418e-870b-1faccd4b2c0f".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertJsonBody("""{"name":"newName"}""", it.body) + }, + ) + } + + // updateDestination + + @Test + fun `updateDestination`() = runTest { + client.runTest( + call = { + updateDestination( + destinationID = "6c02aeb1-775e-418e-870b-1faccd4b2c0f", + destinationUpdate = DestinationUpdate( + name = "newName", + ), + ) + }, + intercept = { + assertEquals("/1/destinations/6c02aeb1-775e-418e-870b-1faccd4b2c0f".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertJsonBody("""{"name":"newName"}""", it.body) + }, + ) + } + + // updateSource + + @Test + fun `updateSource`() = runTest { + client.runTest( + call = { + updateSource( + sourceID = "6c02aeb1-775e-418e-870b-1faccd4b2c0f", + sourceUpdate = SourceUpdate( + name = "newName", + ), + ) + }, + intercept = { + assertEquals("/1/sources/6c02aeb1-775e-418e-870b-1faccd4b2c0f".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertJsonBody("""{"name":"newName"}""", it.body) + }, + ) + } + + // updateTask + + @Test + fun `updateTask`() = runTest { + client.runTest( + call = { + updateTask( + taskID = "6c02aeb1-775e-418e-870b-1faccd4b2c0f", + taskUpdate = TaskUpdate( + enabled = false, + ), + ) + }, + intercept = { + assertEquals("/1/tasks/6c02aeb1-775e-418e-870b-1faccd4b2c0f".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertJsonBody("""{"enabled":false}""", it.body) + }, + ) + } +} diff --git a/tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/InsightsTest.kt b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/InsightsTest.kt new file mode 100644 index 0000000000..b3346a76d3 --- /dev/null +++ b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/InsightsTest.kt @@ -0,0 +1,488 @@ +package com.algolia.methods.requests + +import com.algolia.client.api.InsightsClient +import com.algolia.client.configuration.* +import com.algolia.client.model.insights.* +import com.algolia.client.transport.* +import com.algolia.extension.* +import com.algolia.utils.* +import io.ktor.http.* +import kotlinx.coroutines.test.* +import kotlinx.serialization.json.* +import kotlin.test.* + +class InsightsTest { + + val client = InsightsClient( + appId = "appId", + apiKey = "apiKey", + region = "us", + ) + + // del + + @Test + fun `allow del method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + del( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `allow del method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + del( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // get + + @Test + fun `allow get method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + get( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `allow get method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + get( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // post + + @Test + fun `allow post method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + post( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{}""", it.body) + }, + ) + } + + @Test + fun `allow post method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + post( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "body", + JsonPrimitive("parameters"), + ) + }, + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"body":"parameters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions can override default query parameters`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("query", "myQueryParameter") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"myQueryParameter"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions merges query parameters with default ones`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("query2", "myQueryParameter") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","query2":"myQueryParameter"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions can override default headers`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + headers = buildMap { + put("x-algolia-api-key", "myApiKey") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"x-algolia-api-key":"myApiKey"}""", it.headers) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions merges headers with default ones`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + headers = buildMap { + put("x-algolia-api-key", "myApiKey") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"x-algolia-api-key":"myApiKey"}""", it.headers) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts booleans`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("isItWorking", true) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","isItWorking":"true"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts integers`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", 2) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"2"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts list of string`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", listOf("c", "d")) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"c,d"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts list of booleans`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", listOf(true, true, false)) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"true,true,false"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts list of integers`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", listOf(1, 2)) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"1,2"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + // pushEvents + + @Test + fun `pushEvents`() = runTest { + client.runTest( + call = { + pushEvents( + insightEvents = InsightEvents( + events = listOf( + InsightEvent( + eventType = EventType.values().first { it.value == "click" }, + eventName = "Product Clicked", + index = "products", + userToken = "user-123456", + timestamp = 1641290601962L, + objectIDs = listOf("9780545139700", "9780439784542"), + queryID = "43b15df305339e827f0ac0bdc5ebcaa7", + positions = listOf(7, 6), + ), + InsightEvent( + eventType = EventType.values().first { it.value == "view" }, + eventName = "Product Detail Page Viewed", + index = "products", + userToken = "user-123456", + timestamp = 1641290601962L, + objectIDs = listOf("9780545139700", "9780439784542"), + ), + InsightEvent( + eventType = EventType.values().first { it.value == "conversion" }, + eventName = "Product Purchased", + index = "products", + userToken = "user-123456", + timestamp = 1641290601962L, + objectIDs = listOf("9780545139700", "9780439784542"), + queryID = "43b15df305339e827f0ac0bdc5ebcaa7", + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/events".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"events":[{"eventType":"click","eventName":"Product Clicked","index":"products","userToken":"user-123456","timestamp":1641290601962,"objectIDs":["9780545139700","9780439784542"],"queryID":"43b15df305339e827f0ac0bdc5ebcaa7","positions":[7,6]},{"eventType":"view","eventName":"Product Detail Page Viewed","index":"products","userToken":"user-123456","timestamp":1641290601962,"objectIDs":["9780545139700","9780439784542"]},{"eventType":"conversion","eventName":"Product Purchased","index":"products","userToken":"user-123456","timestamp":1641290601962,"objectIDs":["9780545139700","9780439784542"],"queryID":"43b15df305339e827f0ac0bdc5ebcaa7"}]}""", it.body) + }, + ) + } + + // put + + @Test + fun `allow put method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + put( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertJsonBody("""{}""", it.body) + }, + ) + } + + @Test + fun `allow put method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + put( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "body", + JsonPrimitive("parameters"), + ) + }, + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"body":"parameters"}""", it.body) + }, + ) + } +} diff --git a/tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/PersonalizationTest.kt b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/PersonalizationTest.kt new file mode 100644 index 0000000000..ce200ee999 --- /dev/null +++ b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/PersonalizationTest.kt @@ -0,0 +1,525 @@ +package com.algolia.methods.requests + +import com.algolia.client.api.PersonalizationClient +import com.algolia.client.configuration.* +import com.algolia.client.model.personalization.* +import com.algolia.client.transport.* +import com.algolia.extension.* +import com.algolia.utils.* +import io.ktor.http.* +import kotlinx.coroutines.test.* +import kotlinx.serialization.json.* +import kotlin.test.* + +class PersonalizationTest { + + val client = PersonalizationClient( + appId = "appId", + apiKey = "apiKey", + region = "us", + ) + + // del + + @Test + fun `allow del method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + del( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `allow del method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + del( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // deleteUserProfile + + @Test + fun `delete deleteUserProfile`() = runTest { + client.runTest( + call = { + deleteUserProfile( + userToken = "UserToken", + ) + }, + intercept = { + assertEquals("/1/profiles/UserToken".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertNoBody(it.body) + }, + ) + } + + // get + + @Test + fun `allow get method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + get( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `allow get method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + get( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // getPersonalizationStrategy + + @Test + fun `get getPersonalizationStrategy`() = runTest { + client.runTest( + call = { + getPersonalizationStrategy() + }, + intercept = { + assertEquals("/1/strategies/personalization".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // getUserTokenProfile + + @Test + fun `get getUserTokenProfile`() = runTest { + client.runTest( + call = { + getUserTokenProfile( + userToken = "UserToken", + ) + }, + intercept = { + assertEquals("/1/profiles/personalization/UserToken".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // post + + @Test + fun `allow post method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + post( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{}""", it.body) + }, + ) + } + + @Test + fun `allow post method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + post( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "body", + JsonPrimitive("parameters"), + ) + }, + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"body":"parameters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions can override default query parameters`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("query", "myQueryParameter") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"myQueryParameter"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions merges query parameters with default ones`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("query2", "myQueryParameter") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","query2":"myQueryParameter"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions can override default headers`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + headers = buildMap { + put("x-algolia-api-key", "myApiKey") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"x-algolia-api-key":"myApiKey"}""", it.headers) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions merges headers with default ones`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + headers = buildMap { + put("x-algolia-api-key", "myApiKey") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"x-algolia-api-key":"myApiKey"}""", it.headers) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts booleans`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("isItWorking", true) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","isItWorking":"true"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts integers`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", 2) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"2"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts list of string`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", listOf("c", "d")) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"c,d"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts list of booleans`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", listOf(true, true, false)) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"true,true,false"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts list of integers`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", listOf(1, 2)) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"1,2"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + // put + + @Test + fun `allow put method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + put( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertJsonBody("""{}""", it.body) + }, + ) + } + + @Test + fun `allow put method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + put( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "body", + JsonPrimitive("parameters"), + ) + }, + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"body":"parameters"}""", it.body) + }, + ) + } + + // setPersonalizationStrategy + + @Test + fun `set setPersonalizationStrategy`() = runTest { + client.runTest( + call = { + setPersonalizationStrategy( + personalizationStrategyParams = PersonalizationStrategyParams( + eventScoring = listOf( + EventScoring( + score = 42, + eventName = "Algolia", + eventType = "Event", + ), + ), + facetScoring = listOf( + FacetScoring( + score = 42, + facetName = "Event", + ), + ), + personalizationImpact = 42, + ), + ) + }, + intercept = { + assertEquals("/1/strategies/personalization".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"eventScoring":[{"score":42,"eventName":"Algolia","eventType":"Event"}],"facetScoring":[{"score":42,"facetName":"Event"}],"personalizationImpact":42}""", it.body) + }, + ) + } +} diff --git a/tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/PredictTest.kt b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/PredictTest.kt new file mode 100644 index 0000000000..c0a18899ad --- /dev/null +++ b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/PredictTest.kt @@ -0,0 +1,1118 @@ +package com.algolia.methods.requests + +import com.algolia.client.api.PredictClient +import com.algolia.client.configuration.* +import com.algolia.client.model.predict.* +import com.algolia.client.transport.* +import com.algolia.extension.* +import com.algolia.utils.* +import io.ktor.http.* +import kotlinx.coroutines.test.* +import kotlinx.serialization.json.* +import kotlin.test.* + +class PredictTest { + + val client = PredictClient( + appId = "appId", + apiKey = "apiKey", + region = "eu", + ) + + // activateModelInstance + + @Test + fun `activate a model instance`() = runTest { + client.runTest( + call = { + activateModelInstance( + activateModelParams = ActivateModelParams( + type = ModelsToRetrieve.values().first { it.value == "funnel_stage" }, + name = "Shopping stage for EU users", + sourceID = "0200030-129930", + index = "Products Production", + modelAttributes = listOf(), + ), + ) + }, + intercept = { + assertEquals("/1/predict/models".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"type":"funnel_stage","name":"Shopping stage for EU users","sourceID":"0200030-129930","index":"Products Production","modelAttributes":[]}""", it.body) + }, + ) + } + + // createSegment + + @Test + fun `create segment with required params`() = runTest { + client.runTest( + call = { + createSegment( + createSegmentParams = CreateSegmentParams( + name = "segment1", + conditions = SegmentParentConditions( + operator = SegmentConditionOperator.values().first { it.value == "AND" }, + operands = listOf( + SegmentOperandAffinity( + name = "predictions.order_value", + filters = listOf( + SegmentAffinityFilter( + operator = SegmentFilterOperatorNumerical.values().first { it.value == "GT" }, + value = SegmentAffinityFilterValue.Number(200.toNumberType()), + ), + ), + ), + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/segments".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"name":"segment1","conditions":{"operator":"AND","operands":[{"name":"predictions.order_value","filters":[{"operator":"GT","value":200}]}]}}""", it.body) + }, + ) + } + + @Test + fun `create segment with filter probability`() = runTest { + client.runTest( + call = { + createSegment( + createSegmentParams = CreateSegmentParams( + name = "segment1", + conditions = SegmentParentConditions( + operator = SegmentConditionOperator.values().first { it.value == "AND" }, + operands = listOf( + SegmentOperandAffinity( + name = "predictions.affinities.color", + filters = listOf( + SegmentAffinityFilter( + operator = SegmentFilterOperatorNumerical.values().first { it.value == "EQ" }, + value = SegmentAffinityFilterValue.String("red"), + probability = SegmentFilterProbability( + gte = 0.5, + lte = 1, + ), + ), + ), + ), + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/segments".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"name":"segment1","conditions":{"operator":"AND","operands":[{"name":"predictions.affinities.color","filters":[{"operator":"EQ","value":"red","probability":{"GTE":0.5,"LTE":1}}]}]}}""", it.body) + }, + ) + } + + // del + + @Test + fun `allow del method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + del( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `allow del method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + del( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // deleteModelInstance + + @Test + fun `delete a model instance`() = runTest { + client.runTest( + call = { + deleteModelInstance( + modelID = "model1", + ) + }, + intercept = { + assertEquals("/1/predict/models/model1".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertNoBody(it.body) + }, + ) + } + + // deleteSegment + + @Test + fun `delete a segments configuration`() = runTest { + client.runTest( + call = { + deleteSegment( + segmentID = "segment1", + ) + }, + intercept = { + assertEquals("/1/segments/segment1".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertNoBody(it.body) + }, + ) + } + + // deleteUserProfile + + @Test + fun `deleteUserProfile`() = runTest { + client.runTest( + call = { + deleteUserProfile( + userID = "user1", + ) + }, + intercept = { + assertEquals("/1/users/user1".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertNoBody(it.body) + }, + ) + } + + // fetchAllSegments + + @Test + fun `fetchAllSegments with no segmentType`() = runTest { + client.runTest( + call = { + fetchAllSegments() + }, + intercept = { + assertEquals("/1/segments".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `fetchAllSegments with segmentType custom`() = runTest { + client.runTest( + call = { + fetchAllSegments( + type = SegmentType.values().first { it.value == "custom" }, + ) + }, + intercept = { + assertEquals("/1/segments".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"type":"custom"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `fetchAllSegments with segmentType computed`() = runTest { + client.runTest( + call = { + fetchAllSegments( + type = SegmentType.values().first { it.value == "computed" }, + ) + }, + intercept = { + assertEquals("/1/segments".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"type":"computed"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // fetchAllUserProfiles + + @Test + fun `fetchAllUserProfiles with minimal parameters for modelsToRetrieve`() = runTest { + client.runTest( + call = { + fetchAllUserProfiles( + fetchAllUserProfilesParams = ModelsToRetrieveParam( + modelsToRetrieve = listOf(ModelsToRetrieve.values().first { it.value == "funnel_stage" }, ModelsToRetrieve.values().first { it.value == "order_value" }, ModelsToRetrieve.values().first { it.value == "affinities" }), + ), + ) + }, + intercept = { + assertEquals("/1/users".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"modelsToRetrieve":["funnel_stage","order_value","affinities"]}""", it.body) + }, + ) + } + + @Test + fun `fetchAllUserProfiles with minimal parameters for typesToRetrieve`() = runTest { + client.runTest( + call = { + fetchAllUserProfiles( + fetchAllUserProfilesParams = TypesToRetrieveParam( + typesToRetrieve = listOf(TypesToRetrieve.values().first { it.value == "properties" }, TypesToRetrieve.values().first { it.value == "segments" }), + ), + ) + }, + intercept = { + assertEquals("/1/users".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"typesToRetrieve":["properties","segments"]}""", it.body) + }, + ) + } + + @Test + fun `fetchAllUserProfiles with a limit`() = runTest { + client.runTest( + call = { + fetchAllUserProfiles( + fetchAllUserProfilesParams = LimitParam( + limit = 10, + ), + ) + }, + intercept = { + assertEquals("/1/users".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"limit":10}""", it.body) + }, + ) + } + + @Test + fun `fetchAllUserProfiles with a nextPageToken`() = runTest { + client.runTest( + call = { + fetchAllUserProfiles( + fetchAllUserProfilesParams = NextPageTokenParam( + nextPageToken = "nextPageTokenExample123", + ), + ) + }, + intercept = { + assertEquals("/1/users".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"nextPageToken":"nextPageTokenExample123"}""", it.body) + }, + ) + } + + @Test + fun `fetchAllUserProfiles with a previousPageToken`() = runTest { + client.runTest( + call = { + fetchAllUserProfiles( + fetchAllUserProfilesParams = PreviousPageTokenParam( + previousPageToken = "previousPageTokenExample123", + ), + ) + }, + intercept = { + assertEquals("/1/users".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"previousPageToken":"previousPageTokenExample123"}""", it.body) + }, + ) + } + + // fetchSegment + + @Test + fun `fetchSegment with user ID`() = runTest { + client.runTest( + call = { + fetchSegment( + segmentID = "segment1", + ) + }, + intercept = { + assertEquals("/1/segments/segment1".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // fetchUserProfile + + @Test + fun `fetchUserProfile with minimal parameters for modelsToRetrieve`() = runTest { + client.runTest( + call = { + fetchUserProfile( + userID = "user1", + params = ModelsToRetrieveParam( + modelsToRetrieve = listOf(ModelsToRetrieve.values().first { it.value == "funnel_stage" }, ModelsToRetrieve.values().first { it.value == "order_value" }, ModelsToRetrieve.values().first { it.value == "affinities" }), + ), + ) + }, + intercept = { + assertEquals("/1/users/user1/fetch".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"modelsToRetrieve":["funnel_stage","order_value","affinities"]}""", it.body) + }, + ) + } + + @Test + fun `fetchUserProfile with minimal parameters for typesToRetrieve`() = runTest { + client.runTest( + call = { + fetchUserProfile( + userID = "user1", + params = TypesToRetrieveParam( + typesToRetrieve = listOf(TypesToRetrieve.values().first { it.value == "properties" }, TypesToRetrieve.values().first { it.value == "segments" }), + ), + ) + }, + intercept = { + assertEquals("/1/users/user1/fetch".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"typesToRetrieve":["properties","segments"]}""", it.body) + }, + ) + } + + @Test + fun `fetchUserProfile with all parameters`() = runTest { + client.runTest( + call = { + fetchUserProfile( + userID = "user1", + params = AllParams( + modelsToRetrieve = listOf(ModelsToRetrieve.values().first { it.value == "funnel_stage" }, ModelsToRetrieve.values().first { it.value == "order_value" }, ModelsToRetrieve.values().first { it.value == "affinities" }), + typesToRetrieve = listOf(TypesToRetrieve.values().first { it.value == "properties" }, TypesToRetrieve.values().first { it.value == "segments" }), + ), + ) + }, + intercept = { + assertEquals("/1/users/user1/fetch".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"modelsToRetrieve":["funnel_stage","order_value","affinities"],"typesToRetrieve":["properties","segments"]}""", it.body) + }, + ) + } + + // get + + @Test + fun `allow get method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + get( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `allow get method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + get( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // getAvailableModelTypes + + @Test + fun `get available model types`() = runTest { + client.runTest( + call = { + getAvailableModelTypes() + }, + intercept = { + assertEquals("/1/predict/modeltypes".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // getModelInstanceConfig + + @Test + fun `get configurations for a model instance`() = runTest { + client.runTest( + call = { + getModelInstanceConfig( + modelID = "model1", + ) + }, + intercept = { + assertEquals("/1/predict/models/model1".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // getModelInstances + + @Test + fun `get a list of model instances`() = runTest { + client.runTest( + call = { + getModelInstances() + }, + intercept = { + assertEquals("/1/predict/models".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // getModelMetrics + + @Test + fun `get metrics for a model instance`() = runTest { + client.runTest( + call = { + getModelMetrics( + modelID = "model1", + ) + }, + intercept = { + assertEquals("/1/predict/models/model1/metrics".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // getSegmentUsers + + @Test + fun `getSegmentUsers with minimal parameters for modelsToRetrieve`() = runTest { + client.runTest( + call = { + getSegmentUsers( + segmentID = "segmentID1", + fetchAllUserProfilesParams = ModelsToRetrieveParam( + modelsToRetrieve = listOf(ModelsToRetrieve.values().first { it.value == "funnel_stage" }), + ), + ) + }, + intercept = { + assertEquals("/1/segments/segmentID1/users".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"modelsToRetrieve":["funnel_stage"]}""", it.body) + }, + ) + } + + @Test + fun `getSegmentUsers with minimal parameters for typesToRetrieve`() = runTest { + client.runTest( + call = { + getSegmentUsers( + segmentID = "segmentID1", + fetchAllUserProfilesParams = TypesToRetrieveParam( + typesToRetrieve = listOf(TypesToRetrieve.values().first { it.value == "properties" }), + ), + ) + }, + intercept = { + assertEquals("/1/segments/segmentID1/users".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"typesToRetrieve":["properties"]}""", it.body) + }, + ) + } + + @Test + fun `getSegmentUsers with a limit`() = runTest { + client.runTest( + call = { + getSegmentUsers( + segmentID = "segmentID1", + fetchAllUserProfilesParams = LimitParam( + limit = 10, + ), + ) + }, + intercept = { + assertEquals("/1/segments/segmentID1/users".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"limit":10}""", it.body) + }, + ) + } + + @Test + fun `getSegmentUsers with a nextPageToken`() = runTest { + client.runTest( + call = { + getSegmentUsers( + segmentID = "segmentID1", + fetchAllUserProfilesParams = NextPageTokenParam( + nextPageToken = "nextPageTokenExample123", + ), + ) + }, + intercept = { + assertEquals("/1/segments/segmentID1/users".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"nextPageToken":"nextPageTokenExample123"}""", it.body) + }, + ) + } + + @Test + fun `getSegmentUsers with a previousPageToken`() = runTest { + client.runTest( + call = { + getSegmentUsers( + segmentID = "segmentID1", + fetchAllUserProfilesParams = PreviousPageTokenParam( + previousPageToken = "previousPageTokenExample123", + ), + ) + }, + intercept = { + assertEquals("/1/segments/segmentID1/users".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"previousPageToken":"previousPageTokenExample123"}""", it.body) + }, + ) + } + + // post + + @Test + fun `allow post method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + post( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{}""", it.body) + }, + ) + } + + @Test + fun `allow post method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + post( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "body", + JsonPrimitive("parameters"), + ) + }, + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"body":"parameters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions can override default query parameters`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("query", "myQueryParameter") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"myQueryParameter"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions merges query parameters with default ones`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("query2", "myQueryParameter") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","query2":"myQueryParameter"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions can override default headers`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + headers = buildMap { + put("x-algolia-api-key", "myApiKey") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"x-algolia-api-key":"myApiKey"}""", it.headers) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions merges headers with default ones`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + headers = buildMap { + put("x-algolia-api-key", "myApiKey") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"x-algolia-api-key":"myApiKey"}""", it.headers) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts booleans`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("isItWorking", true) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","isItWorking":"true"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts integers`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", 2) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"2"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts list of string`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", listOf("c", "d")) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"c,d"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts list of booleans`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", listOf(true, true, false)) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"true,true,false"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts list of integers`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", listOf(1, 2)) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"1,2"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + // put + + @Test + fun `allow put method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + put( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertJsonBody("""{}""", it.body) + }, + ) + } + + @Test + fun `allow put method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + put( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "body", + JsonPrimitive("parameters"), + ) + }, + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"body":"parameters"}""", it.body) + }, + ) + } + + // updateModelInstance + + @Test + fun `update a model instance`() = runTest { + client.runTest( + call = { + updateModelInstance( + modelID = "model1", + updateModelParams = UpdateModelParams( + name = "Shopping stage for EU users", + modelAttributes = listOf("brand", "color", "category_level0", "category_level1"), + modelStatus = ModelStatus.values().first { it.value == "inactive" }, + ), + ) + }, + intercept = { + assertEquals("/1/predict/models/model1".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"name":"Shopping stage for EU users","modelAttributes":["brand","color","category_level0","category_level1"],"modelStatus":"inactive"}""", it.body) + }, + ) + } + + // updateSegment + + @Test + fun `updateSegment with name`() = runTest { + client.runTest( + call = { + updateSegment( + segmentID = "segment1", + updateSegmentParams = SegmentNameParam( + name = "example segment name", + ), + ) + }, + intercept = { + assertEquals("/1/segments/segment1".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"name":"example segment name"}""", it.body) + }, + ) + } + + @Test + fun `updateSegment with conditions`() = runTest { + client.runTest( + call = { + updateSegment( + segmentID = "segment1", + updateSegmentParams = SegmentConditionsParam( + conditions = SegmentParentConditions( + operator = SegmentConditionOperator.values().first { it.value == "AND" }, + operands = listOf( + SegmentOperandAffinity( + name = "predictions.order_value", + filters = listOf( + SegmentAffinityFilter( + operator = SegmentFilterOperatorNumerical.values().first { it.value == "GT" }, + value = SegmentAffinityFilterValue.Number(200.toNumberType()), + ), + ), + ), + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/segments/segment1".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"conditions":{"operator":"AND","operands":[{"name":"predictions.order_value","filters":[{"operator":"GT","value":200}]}]}}""", it.body) + }, + ) + } + + @Test + fun `updateSegment with name and conditions`() = runTest { + client.runTest( + call = { + updateSegment( + segmentID = "segment1", + updateSegmentParams = AllUpdateSegmentParams( + name = "example segment name", + conditions = SegmentParentConditions( + operator = SegmentConditionOperator.values().first { it.value == "AND" }, + operands = listOf( + SegmentOperandAffinity( + name = "predictions.order_value", + filters = listOf( + SegmentAffinityFilter( + operator = SegmentFilterOperatorNumerical.values().first { it.value == "GT" }, + value = SegmentAffinityFilterValue.Number(200.toNumberType()), + ), + ), + ), + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/segments/segment1".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"name":"example segment name","conditions":{"operator":"AND","operands":[{"name":"predictions.order_value","filters":[{"operator":"GT","value":200}]}]}}""", it.body) + }, + ) + } + + @Test + fun `updateSegment with filter probability`() = runTest { + client.runTest( + call = { + updateSegment( + segmentID = "segment1", + updateSegmentParams = SegmentConditionsParam( + conditions = SegmentParentConditions( + operator = SegmentConditionOperator.values().first { it.value == "AND" }, + operands = listOf( + SegmentOperandAffinity( + name = "predictions.affinities.color", + filters = listOf( + SegmentAffinityFilter( + operator = SegmentFilterOperatorNumerical.values().first { it.value == "EQ" }, + value = SegmentAffinityFilterValue.String("red"), + probability = SegmentFilterProbability( + gte = 0.5, + lte = 1, + ), + ), + ), + ), + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/segments/segment1".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"conditions":{"operator":"AND","operands":[{"name":"predictions.affinities.color","filters":[{"operator":"EQ","value":"red","probability":{"GTE":0.5,"LTE":1}}]}]}}""", it.body) + }, + ) + } +} diff --git a/tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/QuerySuggestionsTest.kt b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/QuerySuggestionsTest.kt new file mode 100644 index 0000000000..d547337534 --- /dev/null +++ b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/QuerySuggestionsTest.kt @@ -0,0 +1,600 @@ +package com.algolia.methods.requests + +import com.algolia.client.api.QuerySuggestionsClient +import com.algolia.client.configuration.* +import com.algolia.client.model.querysuggestions.* +import com.algolia.client.transport.* +import com.algolia.extension.* +import com.algolia.utils.* +import io.ktor.http.* +import kotlinx.coroutines.test.* +import kotlinx.serialization.json.* +import kotlin.test.* + +class QuerySuggestionsTest { + + val client = QuerySuggestionsClient( + appId = "appId", + apiKey = "apiKey", + region = "us", + ) + + // createConfig + + @Test + fun `createConfig`() = runTest { + client.runTest( + call = { + createConfig( + querySuggestionsIndexWithIndexParam = QuerySuggestionsIndexWithIndexParam( + indexName = "theIndexName", + sourceIndices = listOf( + SourceIndex( + indexName = "testIndex", + facets = listOf( + buildJsonObject { + put( + "attributes", + JsonPrimitive("test"), + ) + }, + ), + generate = listOf(listOf("facetA", "facetB"), listOf("facetC")), + ), + ), + languages = listOf("french"), + exclude = listOf("test"), + ), + ) + }, + intercept = { + assertEquals("/1/configs".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"indexName":"theIndexName","sourceIndices":[{"indexName":"testIndex","facets":[{"attributes":"test"}],"generate":[["facetA","facetB"],["facetC"]]}],"languages":["french"],"exclude":["test"]}""", it.body) + }, + ) + } + + // del + + @Test + fun `allow del method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + del( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `allow del method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + del( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // deleteConfig + + @Test + fun `deleteConfig`() = runTest { + client.runTest( + call = { + deleteConfig( + indexName = "theIndexName", + ) + }, + intercept = { + assertEquals("/1/configs/theIndexName".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertNoBody(it.body) + }, + ) + } + + // get + + @Test + fun `allow get method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + get( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `allow get method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + get( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // getAllConfigs + + @Test + fun `getAllConfigs`() = runTest { + client.runTest( + call = { + getAllConfigs() + }, + intercept = { + assertEquals("/1/configs".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // getConfig + + @Test + fun `getConfig`() = runTest { + client.runTest( + call = { + getConfig( + indexName = "theIndexName", + ) + }, + intercept = { + assertEquals("/1/configs/theIndexName".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // getConfigStatus + + @Test + fun `getConfigStatus`() = runTest { + client.runTest( + call = { + getConfigStatus( + indexName = "theIndexName", + ) + }, + intercept = { + assertEquals("/1/configs/theIndexName/status".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // getLogFile + + @Test + fun `getLogFile`() = runTest { + client.runTest( + call = { + getLogFile( + indexName = "theIndexName", + ) + }, + intercept = { + assertEquals("/1/logs/theIndexName".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // post + + @Test + fun `allow post method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + post( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{}""", it.body) + }, + ) + } + + @Test + fun `allow post method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + post( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "body", + JsonPrimitive("parameters"), + ) + }, + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"body":"parameters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions can override default query parameters`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("query", "myQueryParameter") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"myQueryParameter"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions merges query parameters with default ones`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("query2", "myQueryParameter") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","query2":"myQueryParameter"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions can override default headers`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + headers = buildMap { + put("x-algolia-api-key", "myApiKey") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"x-algolia-api-key":"myApiKey"}""", it.headers) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions merges headers with default ones`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + headers = buildMap { + put("x-algolia-api-key", "myApiKey") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"x-algolia-api-key":"myApiKey"}""", it.headers) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts booleans`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("isItWorking", true) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","isItWorking":"true"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts integers`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", 2) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"2"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts list of string`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", listOf("c", "d")) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"c,d"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts list of booleans`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", listOf(true, true, false)) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"true,true,false"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts list of integers`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", listOf(1, 2)) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"1,2"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + // put + + @Test + fun `allow put method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + put( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertJsonBody("""{}""", it.body) + }, + ) + } + + @Test + fun `allow put method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + put( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "body", + JsonPrimitive("parameters"), + ) + }, + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"body":"parameters"}""", it.body) + }, + ) + } + + // updateConfig + + @Test + fun `updateConfig`() = runTest { + client.runTest( + call = { + updateConfig( + indexName = "theIndexName", + querySuggestionsIndexParam = QuerySuggestionsIndexParam( + sourceIndices = listOf( + SourceIndex( + indexName = "testIndex", + facets = listOf( + buildJsonObject { + put( + "attributes", + JsonPrimitive("test"), + ) + }, + ), + generate = listOf(listOf("facetA", "facetB"), listOf("facetC")), + ), + ), + languages = listOf("french"), + exclude = listOf("test"), + ), + ) + }, + intercept = { + assertEquals("/1/configs/theIndexName".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertJsonBody("""{"sourceIndices":[{"indexName":"testIndex","facets":[{"attributes":"test"}],"generate":[["facetA","facetB"],["facetC"]]}],"languages":["french"],"exclude":["test"]}""", it.body) + }, + ) + } +} diff --git a/tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/RecommendTest.kt b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/RecommendTest.kt new file mode 100644 index 0000000000..7357024971 --- /dev/null +++ b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/RecommendTest.kt @@ -0,0 +1,664 @@ +package com.algolia.methods.requests + +import com.algolia.client.api.RecommendClient +import com.algolia.client.configuration.* +import com.algolia.client.model.recommend.* +import com.algolia.client.transport.* +import com.algolia.extension.* +import com.algolia.utils.* +import io.ktor.http.* +import kotlinx.coroutines.test.* +import kotlinx.serialization.json.* +import kotlin.test.* + +class RecommendTest { + + val client = RecommendClient( + appId = "appId", + apiKey = "apiKey", + ) + + // del + + @Test + fun `allow del method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + del( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `allow del method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + del( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // get + + @Test + fun `allow get method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + get( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `allow get method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + get( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // getRecommendations + + @Test + fun `get recommendations for recommend model with minimal parameters`() = runTest { + client.runTest( + call = { + getRecommendations( + getRecommendationsParams = GetRecommendationsParams( + requests = listOf( + RecommendationRequest( + indexName = "indexName", + objectID = "objectID", + model = RecommendationModels.values().first { it.value == "related-products" }, + threshold = 42, + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/indexes/*/recommendations".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"requests":[{"indexName":"indexName","objectID":"objectID","model":"related-products","threshold":42}]}""", it.body) + }, + ) + } + + @Test + fun `get recommendations for recommend model with all parameters`() = runTest { + client.runTest( + call = { + getRecommendations( + getRecommendationsParams = GetRecommendationsParams( + requests = listOf( + RecommendationRequest( + indexName = "indexName", + objectID = "objectID", + model = RecommendationModels.values().first { it.value == "related-products" }, + threshold = 42, + maxRecommendations = 10, + queryParameters = SearchParamsObject( + query = "myQuery", + facetFilters = FacetFilters.ListOfMixedSearchFilters(listOf(MixedSearchFilters.String("query"))), + ), + fallbackParameters = SearchParamsObject( + query = "myQuery", + facetFilters = FacetFilters.ListOfMixedSearchFilters(listOf(MixedSearchFilters.String("fallback"))), + ), + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/indexes/*/recommendations".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"requests":[{"indexName":"indexName","objectID":"objectID","model":"related-products","threshold":42,"maxRecommendations":10,"queryParameters":{"query":"myQuery","facetFilters":["query"]},"fallbackParameters":{"query":"myQuery","facetFilters":["fallback"]}}]}""", it.body) + }, + ) + } + + @Test + fun `get recommendations for trending model with minimal parameters`() = runTest { + client.runTest( + call = { + getRecommendations( + getRecommendationsParams = GetRecommendationsParams( + requests = listOf( + TrendingRequest( + indexName = "indexName", + model = TrendingModels.values().first { it.value == "trending-items" }, + threshold = 42, + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/indexes/*/recommendations".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"requests":[{"indexName":"indexName","model":"trending-items","threshold":42}]}""", it.body) + }, + ) + } + + @Test + fun `get recommendations for trending model with all parameters`() = runTest { + client.runTest( + call = { + getRecommendations( + getRecommendationsParams = GetRecommendationsParams( + requests = listOf( + TrendingRequest( + indexName = "indexName", + model = TrendingModels.values().first { it.value == "trending-items" }, + threshold = 42, + maxRecommendations = 10, + facetName = "myFacetName", + facetValue = "myFacetValue", + queryParameters = SearchParamsObject( + query = "myQuery", + facetFilters = FacetFilters.ListOfMixedSearchFilters(listOf(MixedSearchFilters.String("query"))), + ), + fallbackParameters = SearchParamsObject( + query = "myQuery", + facetFilters = FacetFilters.ListOfMixedSearchFilters(listOf(MixedSearchFilters.String("fallback"))), + ), + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/indexes/*/recommendations".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"requests":[{"indexName":"indexName","model":"trending-items","threshold":42,"maxRecommendations":10,"facetName":"myFacetName","facetValue":"myFacetValue","queryParameters":{"query":"myQuery","facetFilters":["query"]},"fallbackParameters":{"query":"myQuery","facetFilters":["fallback"]}}]}""", it.body) + }, + ) + } + + @Test + fun `get multiple recommendations with minimal parameters`() = runTest { + client.runTest( + call = { + getRecommendations( + getRecommendationsParams = GetRecommendationsParams( + requests = listOf( + RecommendationRequest( + indexName = "indexName1", + objectID = "objectID1", + model = RecommendationModels.values().first { it.value == "related-products" }, + threshold = 21, + ), + RecommendationRequest( + indexName = "indexName2", + objectID = "objectID2", + model = RecommendationModels.values().first { it.value == "related-products" }, + threshold = 21, + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/indexes/*/recommendations".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"requests":[{"indexName":"indexName1","objectID":"objectID1","model":"related-products","threshold":21},{"indexName":"indexName2","objectID":"objectID2","model":"related-products","threshold":21}]}""", it.body) + }, + ) + } + + @Test + fun `get multiple recommendations with all parameters`() = runTest { + client.runTest( + call = { + getRecommendations( + getRecommendationsParams = GetRecommendationsParams( + requests = listOf( + RecommendationRequest( + indexName = "indexName1", + objectID = "objectID1", + model = RecommendationModels.values().first { it.value == "related-products" }, + threshold = 21, + maxRecommendations = 10, + queryParameters = SearchParamsObject( + query = "myQuery", + facetFilters = FacetFilters.ListOfMixedSearchFilters(listOf(MixedSearchFilters.String("query1"))), + ), + fallbackParameters = SearchParamsObject( + query = "myQuery", + facetFilters = FacetFilters.ListOfMixedSearchFilters(listOf(MixedSearchFilters.String("fallback1"))), + ), + ), + RecommendationRequest( + indexName = "indexName2", + objectID = "objectID2", + model = RecommendationModels.values().first { it.value == "related-products" }, + threshold = 21, + maxRecommendations = 10, + queryParameters = SearchParamsObject( + query = "myQuery", + facetFilters = FacetFilters.ListOfMixedSearchFilters(listOf(MixedSearchFilters.String("query2"))), + ), + fallbackParameters = SearchParamsObject( + query = "myQuery", + facetFilters = FacetFilters.ListOfMixedSearchFilters(listOf(MixedSearchFilters.String("fallback2"))), + ), + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/indexes/*/recommendations".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"requests":[{"indexName":"indexName1","objectID":"objectID1","model":"related-products","threshold":21,"maxRecommendations":10,"queryParameters":{"query":"myQuery","facetFilters":["query1"]},"fallbackParameters":{"query":"myQuery","facetFilters":["fallback1"]}},{"indexName":"indexName2","objectID":"objectID2","model":"related-products","threshold":21,"maxRecommendations":10,"queryParameters":{"query":"myQuery","facetFilters":["query2"]},"fallbackParameters":{"query":"myQuery","facetFilters":["fallback2"]}}]}""", it.body) + }, + ) + } + + @Test + fun `get frequently bought together recommendations`() = runTest { + client.runTest( + call = { + getRecommendations( + getRecommendationsParams = GetRecommendationsParams( + requests = listOf( + RecommendationRequest( + indexName = "indexName1", + objectID = "objectID1", + model = RecommendationModels.values().first { it.value == "bought-together" }, + threshold = 42, + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/indexes/*/recommendations".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"requests":[{"indexName":"indexName1","objectID":"objectID1","model":"bought-together","threshold":42}]}""", it.body) + }, + ) + } + + // post + + @Test + fun `allow post method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + post( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{}""", it.body) + }, + ) + } + + @Test + fun `allow post method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + post( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "body", + JsonPrimitive("parameters"), + ) + }, + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"body":"parameters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions can override default query parameters`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("query", "myQueryParameter") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"myQueryParameter"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions merges query parameters with default ones`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("query2", "myQueryParameter") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","query2":"myQueryParameter"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions can override default headers`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + headers = buildMap { + put("x-algolia-api-key", "myApiKey") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"x-algolia-api-key":"myApiKey"}""", it.headers) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions merges headers with default ones`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + headers = buildMap { + put("x-algolia-api-key", "myApiKey") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"x-algolia-api-key":"myApiKey"}""", it.headers) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts booleans`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("isItWorking", true) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","isItWorking":"true"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts integers`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", 2) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"2"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts list of string`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", listOf("c", "d")) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"c,d"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts list of booleans`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", listOf(true, true, false)) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"true,true,false"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts list of integers`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", listOf(1, 2)) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"1,2"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + // put + + @Test + fun `allow put method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + put( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertJsonBody("""{}""", it.body) + }, + ) + } + + @Test + fun `allow put method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + put( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "body", + JsonPrimitive("parameters"), + ) + }, + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"body":"parameters"}""", it.body) + }, + ) + } +} diff --git a/tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/SearchTest.kt b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/SearchTest.kt new file mode 100644 index 0000000000..4a3416ecc1 --- /dev/null +++ b/tests/output/kotlin/src/commonTest/kotlin/com/algolia/methods/requests/SearchTest.kt @@ -0,0 +1,2833 @@ +package com.algolia.methods.requests + +import com.algolia.client.api.SearchClient +import com.algolia.client.configuration.* +import com.algolia.client.model.search.* +import com.algolia.client.transport.* +import com.algolia.extension.* +import com.algolia.utils.* +import io.ktor.http.* +import kotlinx.coroutines.test.* +import kotlinx.serialization.json.* +import kotlin.test.* + +class SearchTest { + + val client = SearchClient( + appId = "appId", + apiKey = "apiKey", + ) + + // addApiKey + + @Test + fun `addApiKey`() = runTest { + client.runTest( + call = { + addApiKey( + apiKey = ApiKey( + acl = listOf(Acl.values().first { it.value == "search" }, Acl.values().first { it.value == "addObject" }), + description = "my new api key", + validity = 300, + maxQueriesPerIPPerHour = 100, + maxHitsPerQuery = 20, + ), + ) + }, + intercept = { + assertEquals("/1/keys".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"acl":["search","addObject"],"description":"my new api key","validity":300,"maxQueriesPerIPPerHour":100,"maxHitsPerQuery":20}""", it.body) + }, + ) + } + + // addOrUpdateObject + + @Test + fun `addOrUpdateObject`() = runTest { + client.runTest( + call = { + addOrUpdateObject( + indexName = "indexName", + objectID = "uniqueID", + body = buildJsonObject { + put( + "key", + JsonPrimitive("value"), + ) + }, + ) + }, + intercept = { + assertEquals("/1/indexes/indexName/uniqueID".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertJsonBody("""{"key":"value"}""", it.body) + }, + ) + } + + // appendSource + + @Test + fun `appendSource`() = runTest { + client.runTest( + call = { + appendSource( + source = Source( + source = "theSource", + description = "theDescription", + ), + ) + }, + intercept = { + assertEquals("/1/security/sources/append".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"source":"theSource","description":"theDescription"}""", it.body) + }, + ) + } + + // assignUserId + + @Test + fun `assignUserId`() = runTest { + client.runTest( + call = { + assignUserId( + xAlgoliaUserID = "userID", + assignUserIdParams = AssignUserIdParams( + cluster = "theCluster", + ), + ) + }, + intercept = { + assertEquals("/1/clusters/mapping".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"x-algolia-user-id":"userID"}""", it.headers) + assertJsonBody("""{"cluster":"theCluster"}""", it.body) + }, + ) + } + + // batch + + @Test + fun `allows batch method with 'addObject' action`() = runTest { + client.runTest( + call = { + batch( + indexName = "theIndexName", + batchWriteParams = BatchWriteParams( + requests = listOf( + BatchRequest( + action = Action.values().first { it.value == "addObject" }, + body = buildJsonObject { + put( + "key", + JsonPrimitive("value"), + ) + }, + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/indexes/theIndexName/batch".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"requests":[{"action":"addObject","body":{"key":"value"}}]}""", it.body) + }, + ) + } + + @Test + fun `allows batch method with 'clear' action`() = runTest { + client.runTest( + call = { + batch( + indexName = "theIndexName", + batchWriteParams = BatchWriteParams( + requests = listOf( + BatchRequest( + action = Action.values().first { it.value == "clear" }, + body = buildJsonObject { + put( + "key", + JsonPrimitive("value"), + ) + }, + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/indexes/theIndexName/batch".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"requests":[{"action":"clear","body":{"key":"value"}}]}""", it.body) + }, + ) + } + + @Test + fun `allows batch method with 'delete' action`() = runTest { + client.runTest( + call = { + batch( + indexName = "theIndexName", + batchWriteParams = BatchWriteParams( + requests = listOf( + BatchRequest( + action = Action.values().first { it.value == "delete" }, + body = buildJsonObject { + put( + "key", + JsonPrimitive("value"), + ) + }, + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/indexes/theIndexName/batch".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"requests":[{"action":"delete","body":{"key":"value"}}]}""", it.body) + }, + ) + } + + @Test + fun `allows batch method with 'deleteObject' action`() = runTest { + client.runTest( + call = { + batch( + indexName = "theIndexName", + batchWriteParams = BatchWriteParams( + requests = listOf( + BatchRequest( + action = Action.values().first { it.value == "deleteObject" }, + body = buildJsonObject { + put( + "key", + JsonPrimitive("value"), + ) + }, + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/indexes/theIndexName/batch".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"requests":[{"action":"deleteObject","body":{"key":"value"}}]}""", it.body) + }, + ) + } + + @Test + fun `allows batch method with 'partialUpdateObject' action`() = runTest { + client.runTest( + call = { + batch( + indexName = "theIndexName", + batchWriteParams = BatchWriteParams( + requests = listOf( + BatchRequest( + action = Action.values().first { it.value == "partialUpdateObject" }, + body = buildJsonObject { + put( + "key", + JsonPrimitive("value"), + ) + }, + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/indexes/theIndexName/batch".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"requests":[{"action":"partialUpdateObject","body":{"key":"value"}}]}""", it.body) + }, + ) + } + + @Test + fun `allows batch method with 'partialUpdateObjectNoCreate' action`() = runTest { + client.runTest( + call = { + batch( + indexName = "theIndexName", + batchWriteParams = BatchWriteParams( + requests = listOf( + BatchRequest( + action = Action.values().first { it.value == "partialUpdateObjectNoCreate" }, + body = buildJsonObject { + put( + "key", + JsonPrimitive("value"), + ) + }, + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/indexes/theIndexName/batch".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"requests":[{"action":"partialUpdateObjectNoCreate","body":{"key":"value"}}]}""", it.body) + }, + ) + } + + @Test + fun `allows batch method with 'updateObject' action`() = runTest { + client.runTest( + call = { + batch( + indexName = "theIndexName", + batchWriteParams = BatchWriteParams( + requests = listOf( + BatchRequest( + action = Action.values().first { it.value == "updateObject" }, + body = buildJsonObject { + put( + "key", + JsonPrimitive("value"), + ) + }, + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/indexes/theIndexName/batch".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"requests":[{"action":"updateObject","body":{"key":"value"}}]}""", it.body) + }, + ) + } + + // batchAssignUserIds + + @Test + fun `batchAssignUserIds`() = runTest { + client.runTest( + call = { + batchAssignUserIds( + xAlgoliaUserID = "userID", + batchAssignUserIdsParams = BatchAssignUserIdsParams( + cluster = "theCluster", + users = listOf("user1", "user2"), + ), + ) + }, + intercept = { + assertEquals("/1/clusters/mapping/batch".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"x-algolia-user-id":"userID"}""", it.headers) + assertJsonBody("""{"cluster":"theCluster","users":["user1","user2"]}""", it.body) + }, + ) + } + + // batchDictionaryEntries + + @Test + fun `get batchDictionaryEntries results with minimal parameters`() = runTest { + client.runTest( + call = { + batchDictionaryEntries( + dictionaryName = DictionaryType.values().first { it.value == "compounds" }, + batchDictionaryEntriesParams = BatchDictionaryEntriesParams( + requests = listOf( + BatchDictionaryEntriesRequest( + action = DictionaryAction.values().first { it.value == "addEntry" }, + body = DictionaryEntry( + objectID = "1", + language = "en", + ), + ), + BatchDictionaryEntriesRequest( + action = DictionaryAction.values().first { it.value == "deleteEntry" }, + body = DictionaryEntry( + objectID = "2", + language = "fr", + ), + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/dictionaries/compounds/batch".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"requests":[{"action":"addEntry","body":{"objectID":"1","language":"en"}},{"action":"deleteEntry","body":{"objectID":"2","language":"fr"}}]}""", it.body) + }, + ) + } + + @Test + fun `get batchDictionaryEntries results with all parameters`() = runTest { + client.runTest( + call = { + batchDictionaryEntries( + dictionaryName = DictionaryType.values().first { it.value == "compounds" }, + batchDictionaryEntriesParams = BatchDictionaryEntriesParams( + clearExistingDictionaryEntries = false, + requests = listOf( + BatchDictionaryEntriesRequest( + action = DictionaryAction.values().first { it.value == "addEntry" }, + body = DictionaryEntry( + objectID = "1", + language = "en", + word = "fancy", + words = listOf("believe", "algolia"), + decomposition = listOf("trust", "algolia"), + state = DictionaryEntryState.values().first { it.value == "enabled" }, + ), + ), + BatchDictionaryEntriesRequest( + action = DictionaryAction.values().first { it.value == "deleteEntry" }, + body = DictionaryEntry( + objectID = "2", + language = "fr", + word = "humility", + words = listOf("candor", "algolia"), + decomposition = listOf("grit", "algolia"), + state = DictionaryEntryState.values().first { it.value == "enabled" }, + ), + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/dictionaries/compounds/batch".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"clearExistingDictionaryEntries":false,"requests":[{"action":"addEntry","body":{"objectID":"1","language":"en","word":"fancy","words":["believe","algolia"],"decomposition":["trust","algolia"],"state":"enabled"}},{"action":"deleteEntry","body":{"objectID":"2","language":"fr","word":"humility","words":["candor","algolia"],"decomposition":["grit","algolia"],"state":"enabled"}}]}""", it.body) + }, + ) + } + + @Test + fun `get batchDictionaryEntries results additional properties`() = runTest { + client.runTest( + call = { + batchDictionaryEntries( + dictionaryName = DictionaryType.values().first { it.value == "compounds" }, + batchDictionaryEntriesParams = BatchDictionaryEntriesParams( + requests = listOf( + BatchDictionaryEntriesRequest( + action = DictionaryAction.values().first { it.value == "addEntry" }, + body = DictionaryEntry( + objectID = "1", + language = "en", + additionalProperties = mapOf( + "additional" to JsonPrimitive("try me"), + ), + ), + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/dictionaries/compounds/batch".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"requests":[{"action":"addEntry","body":{"objectID":"1","language":"en","additional":"try me"}}]}""", it.body) + }, + ) + } + + // browse + + @Test + fun `browse with minimal parameters`() = runTest { + client.runTest( + call = { + browse( + indexName = "indexName", + ) + }, + intercept = { + assertEquals("/1/indexes/indexName/browse".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{}""", it.body) + }, + ) + } + + @Test + fun `browse with search parameters`() = runTest { + client.runTest( + call = { + browse( + indexName = "indexName", + browseParams = BrowseParamsObject( + query = "myQuery", + facetFilters = FacetFilters.ListOfMixedSearchFilters(listOf(MixedSearchFilters.String("tags:algolia"))), + ), + ) + }, + intercept = { + assertEquals("/1/indexes/indexName/browse".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"query":"myQuery","facetFilters":["tags:algolia"]}""", it.body) + }, + ) + } + + @Test + fun `browse allow a cursor in parameters`() = runTest { + client.runTest( + call = { + browse( + indexName = "indexName", + browseParams = BrowseParamsObject( + cursor = "test", + ), + ) + }, + intercept = { + assertEquals("/1/indexes/indexName/browse".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"cursor":"test"}""", it.body) + }, + ) + } + + // clearAllSynonyms + + @Test + fun `clearAllSynonyms`() = runTest { + client.runTest( + call = { + clearAllSynonyms( + indexName = "indexName", + ) + }, + intercept = { + assertEquals("/1/indexes/indexName/synonyms/clear".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertEmptyBody(it.body) + }, + ) + } + + // clearObjects + + @Test + fun `clearObjects`() = runTest { + client.runTest( + call = { + clearObjects( + indexName = "theIndexName", + ) + }, + intercept = { + assertEquals("/1/indexes/theIndexName/clear".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertEmptyBody(it.body) + }, + ) + } + + // clearRules + + @Test + fun `clearRules`() = runTest { + client.runTest( + call = { + clearRules( + indexName = "indexName", + ) + }, + intercept = { + assertEquals("/1/indexes/indexName/rules/clear".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertEmptyBody(it.body) + }, + ) + } + + // del + + @Test + fun `allow del method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + del( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `allow del method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + del( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // deleteApiKey + + @Test + fun `deleteApiKey`() = runTest { + client.runTest( + call = { + deleteApiKey( + key = "myTestApiKey", + ) + }, + intercept = { + assertEquals("/1/keys/myTestApiKey".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertNoBody(it.body) + }, + ) + } + + // deleteBy + + @Test + fun `deleteBy`() = runTest { + client.runTest( + call = { + deleteBy( + indexName = "theIndexName", + deleteByParams = DeleteByParams( + filters = "brand:brandName", + ), + ) + }, + intercept = { + assertEquals("/1/indexes/theIndexName/deleteByQuery".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"filters":"brand:brandName"}""", it.body) + }, + ) + } + + // deleteIndex + + @Test + fun `deleteIndex`() = runTest { + client.runTest( + call = { + deleteIndex( + indexName = "theIndexName", + ) + }, + intercept = { + assertEquals("/1/indexes/theIndexName".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertNoBody(it.body) + }, + ) + } + + // deleteObject + + @Test + fun `deleteObject`() = runTest { + client.runTest( + call = { + deleteObject( + indexName = "theIndexName", + objectID = "uniqueID", + ) + }, + intercept = { + assertEquals("/1/indexes/theIndexName/uniqueID".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertNoBody(it.body) + }, + ) + } + + // deleteRule + + @Test + fun `deleteRule`() = runTest { + client.runTest( + call = { + deleteRule( + indexName = "indexName", + objectID = "id1", + ) + }, + intercept = { + assertEquals("/1/indexes/indexName/rules/id1".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertNoBody(it.body) + }, + ) + } + + // deleteSource + + @Test + fun `deleteSource`() = runTest { + client.runTest( + call = { + deleteSource( + source = "theSource", + ) + }, + intercept = { + assertEquals("/1/security/sources/theSource".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertNoBody(it.body) + }, + ) + } + + // deleteSynonym + + @Test + fun `deleteSynonym`() = runTest { + client.runTest( + call = { + deleteSynonym( + indexName = "indexName", + objectID = "id1", + ) + }, + intercept = { + assertEquals("/1/indexes/indexName/synonyms/id1".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertNoBody(it.body) + }, + ) + } + + // get + + @Test + fun `allow get method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + get( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `allow get method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + get( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // getApiKey + + @Test + fun `getApiKey`() = runTest { + client.runTest( + call = { + getApiKey( + key = "myTestApiKey", + ) + }, + intercept = { + assertEquals("/1/keys/myTestApiKey".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // getDictionaryLanguages + + @Test + fun `get getDictionaryLanguages`() = runTest { + client.runTest( + call = { + getDictionaryLanguages() + }, + intercept = { + assertEquals("/1/dictionaries/*/languages".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // getDictionarySettings + + @Test + fun `get getDictionarySettings results`() = runTest { + client.runTest( + call = { + getDictionarySettings() + }, + intercept = { + assertEquals("/1/dictionaries/*/settings".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // getLogs + + @Test + fun `getLogs with minimal parameters`() = runTest { + client.runTest( + call = { + getLogs() + }, + intercept = { + assertEquals("/1/logs".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `getLogs with parameters`() = runTest { + client.runTest( + call = { + getLogs( + offset = 5, + length = 10, + indexName = "theIndexName", + type = LogType.values().first { it.value == "all" }, + ) + }, + intercept = { + assertEquals("/1/logs".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"offset":"5","length":"10","indexName":"theIndexName","type":"all"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // getObject + + @Test + fun `getObject`() = runTest { + client.runTest( + call = { + getObject( + indexName = "theIndexName", + objectID = "uniqueID", + attributesToRetrieve = listOf("attr1", "attr2"), + ) + }, + intercept = { + assertEquals("/1/indexes/theIndexName/uniqueID".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"attributesToRetrieve":"attr1,attr2"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // getObjects + + @Test + fun `getObjects`() = runTest { + client.runTest( + call = { + getObjects( + getObjectsParams = GetObjectsParams( + requests = listOf( + GetObjectsRequest( + attributesToRetrieve = listOf("attr1", "attr2"), + objectID = "uniqueID", + indexName = "theIndexName", + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/indexes/*/objects".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"requests":[{"attributesToRetrieve":["attr1","attr2"],"objectID":"uniqueID","indexName":"theIndexName"}]}""", it.body) + }, + ) + } + + // getRule + + @Test + fun `getRule`() = runTest { + client.runTest( + call = { + getRule( + indexName = "indexName", + objectID = "id1", + ) + }, + intercept = { + assertEquals("/1/indexes/indexName/rules/id1".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // getSettings + + @Test + fun `getSettings`() = runTest { + client.runTest( + call = { + getSettings( + indexName = "theIndexName", + ) + }, + intercept = { + assertEquals("/1/indexes/theIndexName/settings".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // getSources + + @Test + fun `getSources`() = runTest { + client.runTest( + call = { + getSources() + }, + intercept = { + assertEquals("/1/security/sources".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // getSynonym + + @Test + fun `getSynonym`() = runTest { + client.runTest( + call = { + getSynonym( + indexName = "indexName", + objectID = "id1", + ) + }, + intercept = { + assertEquals("/1/indexes/indexName/synonyms/id1".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // getTask + + @Test + fun `getTask`() = runTest { + client.runTest( + call = { + getTask( + indexName = "theIndexName", + taskID = 123L, + ) + }, + intercept = { + assertEquals("/1/indexes/theIndexName/task/123".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // getTopUserIds + + @Test + fun `getTopUserIds`() = runTest { + client.runTest( + call = { + getTopUserIds() + }, + intercept = { + assertEquals("/1/clusters/mapping/top".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // getUserId + + @Test + fun `getUserId`() = runTest { + client.runTest( + call = { + getUserId( + userID = "uniqueID", + ) + }, + intercept = { + assertEquals("/1/clusters/mapping/uniqueID".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // hasPendingMappings + + @Test + fun `hasPendingMappings with minimal parameters`() = runTest { + client.runTest( + call = { + hasPendingMappings() + }, + intercept = { + assertEquals("/1/clusters/mapping/pending".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `hasPendingMappings with parameters`() = runTest { + client.runTest( + call = { + hasPendingMappings( + getClusters = true, + ) + }, + intercept = { + assertEquals("/1/clusters/mapping/pending".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"getClusters":"true"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // listApiKeys + + @Test + fun `listApiKeys`() = runTest { + client.runTest( + call = { + listApiKeys() + }, + intercept = { + assertEquals("/1/keys".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // listClusters + + @Test + fun `listClusters`() = runTest { + client.runTest( + call = { + listClusters() + }, + intercept = { + assertEquals("/1/clusters".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + // listIndices + + @Test + fun `listIndices with minimal parameters`() = runTest { + client.runTest( + call = { + listIndices() + }, + intercept = { + assertEquals("/1/indexes".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `listIndices with parameters`() = runTest { + client.runTest( + call = { + listIndices( + page = 8, + ) + }, + intercept = { + assertEquals("/1/indexes".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"page":"8"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // listUserIds + + @Test + fun `listUserIds with minimal parameters`() = runTest { + client.runTest( + call = { + listUserIds() + }, + intercept = { + assertEquals("/1/clusters/mapping".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertNoBody(it.body) + }, + ) + } + + @Test + fun `listUserIds with parameters`() = runTest { + client.runTest( + call = { + listUserIds( + page = 8, + hitsPerPage = 100, + ) + }, + intercept = { + assertEquals("/1/clusters/mapping".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("GET"), it.method) + assertContainsAll("""{"page":"8","hitsPerPage":"100"}""", it.url.parameters) + assertNoBody(it.body) + }, + ) + } + + // multipleBatch + + @Test + fun `multipleBatch`() = runTest { + client.runTest( + call = { + multipleBatch( + batchParams = BatchParams( + requests = listOf( + MultipleBatchRequest( + action = Action.values().first { it.value == "addObject" }, + body = buildJsonObject { + put( + "key", + JsonPrimitive("value"), + ) + }, + indexName = "theIndexName", + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/indexes/*/batch".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"requests":[{"action":"addObject","body":{"key":"value"},"indexName":"theIndexName"}]}""", it.body) + }, + ) + } + + // operationIndex + + @Test + fun `operationIndex`() = runTest { + client.runTest( + call = { + operationIndex( + indexName = "theIndexName", + operationIndexParams = OperationIndexParams( + operation = OperationType.values().first { it.value == "copy" }, + destination = "dest", + scope = listOf(ScopeType.values().first { it.value == "rules" }, ScopeType.values().first { it.value == "settings" }), + ), + ) + }, + intercept = { + assertEquals("/1/indexes/theIndexName/operation".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"operation":"copy","destination":"dest","scope":["rules","settings"]}""", it.body) + }, + ) + } + + // partialUpdateObject + + @Test + fun `partialUpdateObject`() = runTest { + client.runTest( + call = { + partialUpdateObject( + indexName = "theIndexName", + objectID = "uniqueID", + attributesToUpdate = mapOf( + "id1" to AttributeToUpdate.String("test"), + "id2" to BuiltInOperation( + operation = BuiltInOperationType.values().first { it.value == "AddUnique" }, + value = "test2", + ), + ), + createIfNotExists = true, + ) + }, + intercept = { + assertEquals("/1/indexes/theIndexName/uniqueID/partial".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"createIfNotExists":"true"}""", it.url.parameters) + assertJsonBody("""{"id1":"test","id2":{"_operation":"AddUnique","value":"test2"}}""", it.body) + }, + ) + } + + // post + + @Test + fun `allow post method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + post( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{}""", it.body) + }, + ) + } + + @Test + fun `allow post method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + post( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "body", + JsonPrimitive("parameters"), + ) + }, + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"body":"parameters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions can override default query parameters`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("query", "myQueryParameter") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"myQueryParameter"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions merges query parameters with default ones`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("query2", "myQueryParameter") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","query2":"myQueryParameter"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions can override default headers`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + headers = buildMap { + put("x-algolia-api-key", "myApiKey") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"x-algolia-api-key":"myApiKey"}""", it.headers) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions merges headers with default ones`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + headers = buildMap { + put("x-algolia-api-key", "myApiKey") + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"x-algolia-api-key":"myApiKey"}""", it.headers) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts booleans`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("isItWorking", true) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","isItWorking":"true"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts integers`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", 2) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"2"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts list of string`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", listOf("c", "d")) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"c,d"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts list of booleans`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", listOf(true, true, false)) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"true,true,false"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + @Test + fun `requestOptions queryParameters accepts list of integers`() = runTest { + client.runTest( + call = { + post( + path = "/test/requestOptions", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "facet", + JsonPrimitive("filters"), + ) + }, + requestOptions = RequestOptions( + urlParameters = buildMap { + put("myParam", listOf(1, 2)) + }, + ), + ) + }, + intercept = { + assertEquals("/1/test/requestOptions".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"query":"parameters","myParam":"1,2"}""", it.url.parameters) + assertJsonBody("""{"facet":"filters"}""", it.body) + }, + ) + } + + // put + + @Test + fun `allow put method for a custom path with minimal parameters`() = runTest { + client.runTest( + call = { + put( + path = "/test/minimal", + ) + }, + intercept = { + assertEquals("/1/test/minimal".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertJsonBody("""{}""", it.body) + }, + ) + } + + @Test + fun `allow put method for a custom path with all parameters`() = runTest { + client.runTest( + call = { + put( + path = "/test/all", + parameters = mapOf("query" to "parameters"), + body = buildJsonObject { + put( + "body", + JsonPrimitive("parameters"), + ) + }, + ) + }, + intercept = { + assertEquals("/1/test/all".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertContainsAll("""{"query":"parameters"}""", it.url.parameters) + assertJsonBody("""{"body":"parameters"}""", it.body) + }, + ) + } + + // removeUserId + + @Test + fun `removeUserId`() = runTest { + client.runTest( + call = { + removeUserId( + userID = "uniqueID", + ) + }, + intercept = { + assertEquals("/1/clusters/mapping/uniqueID".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("DELETE"), it.method) + assertNoBody(it.body) + }, + ) + } + + // replaceSources + + @Test + fun `replaceSources`() = runTest { + client.runTest( + call = { + replaceSources( + source = listOf( + Source( + source = "theSource", + description = "theDescription", + ), + ), + ) + }, + intercept = { + assertEquals("/1/security/sources".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertJsonBody("""[{"source":"theSource","description":"theDescription"}]""", it.body) + }, + ) + } + + // restoreApiKey + + @Test + fun `restoreApiKey`() = runTest { + client.runTest( + call = { + restoreApiKey( + key = "myApiKey", + ) + }, + intercept = { + assertEquals("/1/keys/myApiKey/restore".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertEmptyBody(it.body) + }, + ) + } + + // saveObject + + @Test + fun `saveObject`() = runTest { + client.runTest( + call = { + saveObject( + indexName = "theIndexName", + body = buildJsonObject { + put( + "objectID", + JsonPrimitive("id"), + ) + put( + "test", + JsonPrimitive("val"), + ) + }, + ) + }, + intercept = { + assertEquals("/1/indexes/theIndexName".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"objectID":"id","test":"val"}""", it.body) + }, + ) + } + + // saveRule + + @Test + fun `saveRule with minimal parameters`() = runTest { + client.runTest( + call = { + saveRule( + indexName = "indexName", + objectID = "id1", + rule = Rule( + objectID = "id1", + conditions = listOf( + Condition( + pattern = "apple", + anchoring = Anchoring.values().first { it.value == "contains" }, + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/indexes/indexName/rules/id1".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertJsonBody("""{"objectID":"id1","conditions":[{"pattern":"apple","anchoring":"contains"}]}""", it.body) + }, + ) + } + + @Test + fun `saveRule with all parameters`() = runTest { + client.runTest( + call = { + saveRule( + indexName = "indexName", + objectID = "id1", + rule = Rule( + objectID = "id1", + conditions = listOf( + Condition( + pattern = "apple", + anchoring = Anchoring.values().first { it.value == "contains" }, + alternatives = false, + context = "search", + ), + ), + consequence = Consequence( + params = ConsequenceParams( + filters = "brand:apple", + query = ConsequenceQueryObject( + remove = listOf("algolia"), + edits = listOf( + Edit( + type = EditType.values().first { it.value == "remove" }, + delete = "abc", + insert = "cde", + ), + Edit( + type = EditType.values().first { it.value == "replace" }, + delete = "abc", + insert = "cde", + ), + ), + ), + ), + hide = listOf( + ConsequenceHide( + objectID = "321", + ), + ), + filterPromotes = false, + userData = buildJsonObject { + put( + "algolia", + JsonPrimitive("aloglia"), + ) + }, + promote = listOf( + PromoteObjectID( + objectID = "abc", + position = 3, + ), + PromoteObjectIDs( + objectIDs = listOf("abc", "def"), + position = 1, + ), + ), + ), + description = "test", + enabled = true, + validity = listOf( + TimeRange( + from = 1656670273, + until = 1656670277, + ), + ), + ), + forwardToReplicas = true, + ) + }, + intercept = { + assertEquals("/1/indexes/indexName/rules/id1".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertContainsAll("""{"forwardToReplicas":"true"}""", it.url.parameters) + assertJsonBody("""{"objectID":"id1","conditions":[{"pattern":"apple","anchoring":"contains","alternatives":false,"context":"search"}],"consequence":{"params":{"filters":"brand:apple","query":{"remove":["algolia"],"edits":[{"type":"remove","delete":"abc","insert":"cde"},{"type":"replace","delete":"abc","insert":"cde"}]}},"hide":[{"objectID":"321"}],"filterPromotes":false,"userData":{"algolia":"aloglia"},"promote":[{"objectID":"abc","position":3},{"objectIDs":["abc","def"],"position":1}]},"description":"test","enabled":true,"validity":[{"from":1656670273,"until":1656670277}]}""", it.body) + }, + ) + } + + // saveRules + + @Test + fun `saveRules with minimal parameters`() = runTest { + client.runTest( + call = { + saveRules( + indexName = "indexName", + rules = listOf( + Rule( + objectID = "a-rule-id", + conditions = listOf( + Condition( + pattern = "smartphone", + anchoring = Anchoring.values().first { it.value == "contains" }, + ), + ), + ), + Rule( + objectID = "a-second-rule-id", + conditions = listOf( + Condition( + pattern = "apple", + anchoring = Anchoring.values().first { it.value == "contains" }, + ), + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/indexes/indexName/rules/batch".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""[{"objectID":"a-rule-id","conditions":[{"pattern":"smartphone","anchoring":"contains"}]},{"objectID":"a-second-rule-id","conditions":[{"pattern":"apple","anchoring":"contains"}]}]""", it.body) + }, + ) + } + + @Test + fun `saveRules with all parameters`() = runTest { + client.runTest( + call = { + saveRules( + indexName = "indexName", + rules = listOf( + Rule( + objectID = "id1", + conditions = listOf( + Condition( + pattern = "apple", + anchoring = Anchoring.values().first { it.value == "contains" }, + alternatives = false, + context = "search", + ), + ), + consequence = Consequence( + params = ConsequenceParams( + filters = "brand:apple", + query = ConsequenceQueryObject( + remove = listOf("algolia"), + edits = listOf( + Edit( + type = EditType.values().first { it.value == "remove" }, + delete = "abc", + insert = "cde", + ), + Edit( + type = EditType.values().first { it.value == "replace" }, + delete = "abc", + insert = "cde", + ), + ), + ), + ), + hide = listOf( + ConsequenceHide( + objectID = "321", + ), + ), + filterPromotes = false, + userData = buildJsonObject { + put( + "algolia", + JsonPrimitive("aloglia"), + ) + }, + promote = listOf( + PromoteObjectID( + objectID = "abc", + position = 3, + ), + PromoteObjectIDs( + objectIDs = listOf("abc", "def"), + position = 1, + ), + ), + ), + description = "test", + enabled = true, + validity = listOf( + TimeRange( + from = 1656670273, + until = 1656670277, + ), + ), + ), + ), + forwardToReplicas = true, + clearExistingRules = true, + ) + }, + intercept = { + assertEquals("/1/indexes/indexName/rules/batch".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"forwardToReplicas":"true","clearExistingRules":"true"}""", it.url.parameters) + assertJsonBody("""[{"objectID":"id1","conditions":[{"pattern":"apple","anchoring":"contains","alternatives":false,"context":"search"}],"consequence":{"params":{"filters":"brand:apple","query":{"remove":["algolia"],"edits":[{"type":"remove","delete":"abc","insert":"cde"},{"type":"replace","delete":"abc","insert":"cde"}]}},"hide":[{"objectID":"321"}],"filterPromotes":false,"userData":{"algolia":"aloglia"},"promote":[{"objectID":"abc","position":3},{"objectIDs":["abc","def"],"position":1}]},"description":"test","enabled":true,"validity":[{"from":1656670273,"until":1656670277}]}]""", it.body) + }, + ) + } + + // saveSynonym + + @Test + fun `saveSynonym`() = runTest { + client.runTest( + call = { + saveSynonym( + indexName = "indexName", + objectID = "id1", + synonymHit = SynonymHit( + objectID = "id1", + type = SynonymType.values().first { it.value == "synonym" }, + synonyms = listOf("car", "vehicule", "auto"), + ), + forwardToReplicas = true, + ) + }, + intercept = { + assertEquals("/1/indexes/indexName/synonyms/id1".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertContainsAll("""{"forwardToReplicas":"true"}""", it.url.parameters) + assertJsonBody("""{"objectID":"id1","type":"synonym","synonyms":["car","vehicule","auto"]}""", it.body) + }, + ) + } + + // saveSynonyms + + @Test + fun `saveSynonyms`() = runTest { + client.runTest( + call = { + saveSynonyms( + indexName = "indexName", + synonymHit = listOf( + SynonymHit( + objectID = "id1", + type = SynonymType.values().first { it.value == "synonym" }, + synonyms = listOf("car", "vehicule", "auto"), + ), + SynonymHit( + objectID = "id2", + type = SynonymType.values().first { it.value == "onewaysynonym" }, + input = "iphone", + synonyms = listOf("ephone", "aphone", "yphone"), + ), + ), + forwardToReplicas = true, + replaceExistingSynonyms = false, + ) + }, + intercept = { + assertEquals("/1/indexes/indexName/synonyms/batch".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"forwardToReplicas":"true","replaceExistingSynonyms":"false"}""", it.url.parameters) + assertJsonBody("""[{"objectID":"id1","type":"synonym","synonyms":["car","vehicule","auto"]},{"objectID":"id2","type":"onewaysynonym","input":"iphone","synonyms":["ephone","aphone","yphone"]}]""", it.body) + }, + ) + } + + // search + + @Test + fun `search for a single hits request with minimal parameters`() = runTest { + client.runTest( + call = { + search( + searchMethodParams = SearchMethodParams( + requests = listOf( + SearchForHits( + indexName = "theIndexName", + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/indexes/*/queries".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"requests":[{"indexName":"theIndexName"}]}""", it.body) + }, + ) + } + + @Test + fun `search for a single facet request with minimal parameters`() = runTest { + client.runTest( + call = { + search( + searchMethodParams = SearchMethodParams( + requests = listOf( + SearchForFacets( + indexName = "theIndexName", + type = SearchTypeFacet.values().first { it.value == "facet" }, + facet = "theFacet", + ), + ), + strategy = SearchStrategy.values().first { it.value == "stopIfEnoughMatches" }, + ), + ) + }, + intercept = { + assertEquals("/1/indexes/*/queries".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"requests":[{"indexName":"theIndexName","type":"facet","facet":"theFacet"}],"strategy":"stopIfEnoughMatches"}""", it.body) + }, + ) + } + + @Test + fun `search for a single hits request with all parameters`() = runTest { + client.runTest( + call = { + search( + searchMethodParams = SearchMethodParams( + requests = listOf( + SearchForHits( + indexName = "theIndexName", + query = "myQuery", + hitsPerPage = 50, + type = SearchTypeDefault.values().first { it.value == "default" }, + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/indexes/*/queries".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"requests":[{"indexName":"theIndexName","query":"myQuery","hitsPerPage":50,"type":"default"}]}""", it.body) + }, + ) + } + + @Test + fun `search for a single facet request with all parameters`() = runTest { + client.runTest( + call = { + search( + searchMethodParams = SearchMethodParams( + requests = listOf( + SearchForFacets( + indexName = "theIndexName", + type = SearchTypeFacet.values().first { it.value == "facet" }, + facet = "theFacet", + facetQuery = "theFacetQuery", + query = "theQuery", + maxFacetHits = 50, + ), + ), + strategy = SearchStrategy.values().first { it.value == "stopIfEnoughMatches" }, + ), + ) + }, + intercept = { + assertEquals("/1/indexes/*/queries".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"requests":[{"indexName":"theIndexName","type":"facet","facet":"theFacet","facetQuery":"theFacetQuery","query":"theQuery","maxFacetHits":50}],"strategy":"stopIfEnoughMatches"}""", it.body) + }, + ) + } + + @Test + fun `search for multiple mixed requests in multiple indices with minimal parameters`() = runTest { + client.runTest( + call = { + search( + searchMethodParams = SearchMethodParams( + requests = listOf( + SearchForHits( + indexName = "theIndexName", + ), + SearchForFacets( + indexName = "theIndexName2", + type = SearchTypeFacet.values().first { it.value == "facet" }, + facet = "theFacet", + ), + SearchForHits( + indexName = "theIndexName", + type = SearchTypeDefault.values().first { it.value == "default" }, + ), + ), + strategy = SearchStrategy.values().first { it.value == "stopIfEnoughMatches" }, + ), + ) + }, + intercept = { + assertEquals("/1/indexes/*/queries".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"requests":[{"indexName":"theIndexName"},{"indexName":"theIndexName2","type":"facet","facet":"theFacet"},{"indexName":"theIndexName","type":"default"}],"strategy":"stopIfEnoughMatches"}""", it.body) + }, + ) + } + + @Test + fun `search for multiple mixed requests in multiple indices with all parameters`() = runTest { + client.runTest( + call = { + search( + searchMethodParams = SearchMethodParams( + requests = listOf( + SearchForFacets( + indexName = "theIndexName", + type = SearchTypeFacet.values().first { it.value == "facet" }, + facet = "theFacet", + facetQuery = "theFacetQuery", + query = "theQuery", + maxFacetHits = 50, + ), + SearchForHits( + indexName = "theIndexName", + query = "myQuery", + hitsPerPage = 50, + type = SearchTypeDefault.values().first { it.value == "default" }, + ), + ), + strategy = SearchStrategy.values().first { it.value == "stopIfEnoughMatches" }, + ), + ) + }, + intercept = { + assertEquals("/1/indexes/*/queries".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"requests":[{"indexName":"theIndexName","type":"facet","facet":"theFacet","facetQuery":"theFacetQuery","query":"theQuery","maxFacetHits":50},{"indexName":"theIndexName","query":"myQuery","hitsPerPage":50,"type":"default"}],"strategy":"stopIfEnoughMatches"}""", it.body) + }, + ) + } + + @Test + fun `search filters accept all of the possible shapes`() = runTest { + client.runTest( + call = { + search( + searchMethodParams = SearchMethodParams( + requests = listOf( + SearchForHits( + indexName = "theIndexName", + facetFilters = FacetFilters.String("mySearch:filters"), + reRankingApplyFilter = ReRankingApplyFilter.String("mySearch:filters"), + tagFilters = TagFilters.String("mySearch:filters"), + numericFilters = NumericFilters.String("mySearch:filters"), + optionalFilters = OptionalFilters.String("mySearch:filters"), + ), + SearchForHits( + indexName = "theIndexName", + facetFilters = FacetFilters.ListOfMixedSearchFilters(listOf(MixedSearchFilters.String("mySearch:filters"), MixedSearchFilters.ListOfString(listOf("mySearch:filters")))), + reRankingApplyFilter = ReRankingApplyFilter.ListOfMixedSearchFilters(listOf(MixedSearchFilters.String("mySearch:filters"), MixedSearchFilters.ListOfString(listOf("mySearch:filters")))), + tagFilters = TagFilters.ListOfMixedSearchFilters(listOf(MixedSearchFilters.String("mySearch:filters"), MixedSearchFilters.ListOfString(listOf("mySearch:filters")))), + numericFilters = NumericFilters.ListOfMixedSearchFilters(listOf(MixedSearchFilters.String("mySearch:filters"), MixedSearchFilters.ListOfString(listOf("mySearch:filters")))), + optionalFilters = OptionalFilters.ListOfMixedSearchFilters(listOf(MixedSearchFilters.String("mySearch:filters"), MixedSearchFilters.ListOfString(listOf("mySearch:filters")))), + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/indexes/*/queries".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"requests":[{"indexName":"theIndexName","facetFilters":"mySearch:filters","reRankingApplyFilter":"mySearch:filters","tagFilters":"mySearch:filters","numericFilters":"mySearch:filters","optionalFilters":"mySearch:filters"},{"indexName":"theIndexName","facetFilters":["mySearch:filters",["mySearch:filters"]],"reRankingApplyFilter":["mySearch:filters",["mySearch:filters"]],"tagFilters":["mySearch:filters",["mySearch:filters"]],"numericFilters":["mySearch:filters",["mySearch:filters"]],"optionalFilters":["mySearch:filters",["mySearch:filters"]]}]}""", it.body) + }, + ) + } + + @Test + fun `search with all search parameters`() = runTest { + client.runTest( + call = { + search( + searchMethodParams = SearchMethodParams( + requests = listOf( + SearchForHits( + indexName = "theIndexName", + query = "", + similarQuery = "", + filters = "", + facetFilters = FacetFilters.ListOfMixedSearchFilters(listOf(MixedSearchFilters.String(""))), + optionalFilters = OptionalFilters.ListOfMixedSearchFilters(listOf(MixedSearchFilters.String(""))), + numericFilters = NumericFilters.ListOfMixedSearchFilters(listOf(MixedSearchFilters.String(""))), + tagFilters = TagFilters.ListOfMixedSearchFilters(listOf(MixedSearchFilters.String(""))), + sumOrFiltersScores = true, + facets = listOf(""), + maxValuesPerFacet = 0, + facetingAfterDistinct = true, + sortFacetValuesBy = "", + page = 0, + offset = 0, + length = 0, + aroundLatLng = "", + aroundLatLngViaIP = true, + aroundRadius = AroundRadiusAll.values().first { it.value == "all" }, + aroundPrecision = 0, + minimumAroundRadius = 0, + insideBoundingBox = listOf(47.3165, 4.9665), + insidePolygon = listOf(47.3165, 4.9665), + naturalLanguages = listOf(""), + ruleContexts = listOf(""), + personalizationImpact = 0, + userToken = "", + getRankingInfo = true, + clickAnalytics = true, + analytics = true, + analyticsTags = listOf(""), + percentileComputation = true, + enableABTest = true, + enableReRanking = true, + reRankingApplyFilter = ReRankingApplyFilter.ListOfMixedSearchFilters(listOf(MixedSearchFilters.String(""))), + attributesForFaceting = listOf(""), + attributesToRetrieve = listOf(""), + restrictSearchableAttributes = listOf(""), + ranking = listOf(""), + customRanking = listOf(""), + relevancyStrictness = 0, + attributesToHighlight = listOf(""), + attributesToSnippet = listOf(""), + highlightPreTag = "", + highlightPostTag = "", + snippetEllipsisText = "", + restrictHighlightAndSnippetArrays = true, + hitsPerPage = 0, + minWordSizefor1Typo = 0, + minWordSizefor2Typos = 0, + typoTolerance = TypoToleranceEnum.values().first { it.value == "min" }, + allowTyposOnNumericTokens = true, + disableTypoToleranceOnAttributes = listOf(""), + ignorePlurals = IgnorePlurals.Boolean(false), + removeStopWords = RemoveStopWords.Boolean(true), + keepDiacriticsOnCharacters = "", + queryLanguages = listOf(""), + decompoundQuery = true, + enableRules = true, + enablePersonalization = true, + queryType = QueryType.values().first { it.value == "prefixAll" }, + removeWordsIfNoResults = RemoveWordsIfNoResults.values().first { it.value == "allOptional" }, + advancedSyntax = true, + optionalWords = listOf(""), + disableExactOnAttributes = listOf(""), + exactOnSingleWordQuery = ExactOnSingleWordQuery.values().first { it.value == "attribute" }, + alternativesAsExact = listOf(AlternativesAsExact.values().first { it.value == "multiWordsSynonym" }), + advancedSyntaxFeatures = listOf(AdvancedSyntaxFeatures.values().first { it.value == "exactPhrase" }), + distinct = Distinct.Number(0.toNumberType()), + synonyms = true, + replaceSynonymsInHighlight = true, + minProximity = 0, + responseFields = listOf(""), + attributeCriteriaComputedByMinProximity = true, + renderingContent = RenderingContent( + facetOrdering = FacetOrdering( + facets = Facets( + order = listOf("a", "b"), + ), + values = mapOf( + "a" to Value( + order = listOf("b"), + sortRemainingBy = SortRemainingBy.values().first { it.value == "count" }, + ), + ), + ), + ), + type = SearchTypeDefault.values().first { it.value == "default" }, + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/indexes/*/queries".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"requests":[{"indexName":"theIndexName","query":"","similarQuery":"","filters":"","facetFilters":[""],"optionalFilters":[""],"numericFilters":[""],"tagFilters":[""],"sumOrFiltersScores":true,"facets":[""],"maxValuesPerFacet":0,"facetingAfterDistinct":true,"sortFacetValuesBy":"","page":0,"offset":0,"length":0,"aroundLatLng":"","aroundLatLngViaIP":true,"aroundRadius":"all","aroundPrecision":0,"minimumAroundRadius":0,"insideBoundingBox":[47.3165,4.9665],"insidePolygon":[47.3165,4.9665],"naturalLanguages":[""],"ruleContexts":[""],"personalizationImpact":0,"userToken":"","getRankingInfo":true,"clickAnalytics":true,"analytics":true,"analyticsTags":[""],"percentileComputation":true,"enableABTest":true,"enableReRanking":true,"reRankingApplyFilter":[""],"attributesForFaceting":[""],"attributesToRetrieve":[""],"restrictSearchableAttributes":[""],"ranking":[""],"customRanking":[""],"relevancyStrictness":0,"attributesToHighlight":[""],"attributesToSnippet":[""],"highlightPreTag":"","highlightPostTag":"","snippetEllipsisText":"","restrictHighlightAndSnippetArrays":true,"hitsPerPage":0,"minWordSizefor1Typo":0,"minWordSizefor2Typos":0,"typoTolerance":"min","allowTyposOnNumericTokens":true,"disableTypoToleranceOnAttributes":[""],"ignorePlurals":false,"removeStopWords":true,"keepDiacriticsOnCharacters":"","queryLanguages":[""],"decompoundQuery":true,"enableRules":true,"enablePersonalization":true,"queryType":"prefixAll","removeWordsIfNoResults":"allOptional","advancedSyntax":true,"optionalWords":[""],"disableExactOnAttributes":[""],"exactOnSingleWordQuery":"attribute","alternativesAsExact":["multiWordsSynonym"],"advancedSyntaxFeatures":["exactPhrase"],"distinct":0,"synonyms":true,"replaceSynonymsInHighlight":true,"minProximity":0,"responseFields":[""],"attributeCriteriaComputedByMinProximity":true,"renderingContent":{"facetOrdering":{"facets":{"order":["a","b"]},"values":{"a":{"order":["b"],"sortRemainingBy":"count"}}}},"type":"default"}]}""", it.body) + }, + ) + } + + // searchDictionaryEntries + + @Test + fun `get searchDictionaryEntries results with minimal parameters`() = runTest { + client.runTest( + call = { + searchDictionaryEntries( + dictionaryName = DictionaryType.values().first { it.value == "compounds" }, + searchDictionaryEntriesParams = SearchDictionaryEntriesParams( + query = "foo", + ), + ) + }, + intercept = { + assertEquals("/1/dictionaries/compounds/search".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"query":"foo"}""", it.body) + }, + ) + } + + @Test + fun `get searchDictionaryEntries results with all parameters`() = runTest { + client.runTest( + call = { + searchDictionaryEntries( + dictionaryName = DictionaryType.values().first { it.value == "compounds" }, + searchDictionaryEntriesParams = SearchDictionaryEntriesParams( + query = "foo", + page = 4, + hitsPerPage = 2, + language = "fr", + ), + ) + }, + intercept = { + assertEquals("/1/dictionaries/compounds/search".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"query":"foo","page":4,"hitsPerPage":2,"language":"fr"}""", it.body) + }, + ) + } + + // searchForFacetValues + + @Test + fun `get searchForFacetValues results with minimal parameters`() = runTest { + client.runTest( + call = { + searchForFacetValues( + indexName = "indexName", + facetName = "facetName", + ) + }, + intercept = { + assertEquals("/1/indexes/indexName/facets/facetName/query".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{}""", it.body) + }, + ) + } + + @Test + fun `get searchForFacetValues results with all parameters`() = runTest { + client.runTest( + call = { + searchForFacetValues( + indexName = "indexName", + facetName = "facetName", + searchForFacetValuesRequest = SearchForFacetValuesRequest( + params = "query=foo&facetFilters=['bar']", + facetQuery = "foo", + maxFacetHits = 42, + ), + ) + }, + intercept = { + assertEquals("/1/indexes/indexName/facets/facetName/query".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"params":"query=foo&facetFilters=['bar']","facetQuery":"foo","maxFacetHits":42}""", it.body) + }, + ) + } + + // searchRules + + @Test + fun `searchRules`() = runTest { + client.runTest( + call = { + searchRules( + indexName = "indexName", + searchRulesParams = SearchRulesParams( + query = "something", + ), + ) + }, + intercept = { + assertEquals("/1/indexes/indexName/rules/search".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"query":"something"}""", it.body) + }, + ) + } + + // searchSingleIndex + + @Test + fun `search with minimal parameters`() = runTest { + client.runTest( + call = { + searchSingleIndex( + indexName = "indexName", + ) + }, + intercept = { + assertEquals("/1/indexes/indexName/query".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{}""", it.body) + }, + ) + } + + @Test + fun `search with searchParams`() = runTest { + client.runTest( + call = { + searchSingleIndex( + indexName = "indexName", + searchParams = SearchParamsObject( + query = "myQuery", + facetFilters = FacetFilters.ListOfMixedSearchFilters(listOf(MixedSearchFilters.String("tags:algolia"))), + ), + ) + }, + intercept = { + assertEquals("/1/indexes/indexName/query".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"query":"myQuery","facetFilters":["tags:algolia"]}""", it.body) + }, + ) + } + + // searchSynonyms + + @Test + fun `searchSynonyms with minimal parameters`() = runTest { + client.runTest( + call = { + searchSynonyms( + indexName = "indexName", + ) + }, + intercept = { + assertEquals("/1/indexes/indexName/synonyms/search".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{}""", it.body) + }, + ) + } + + @Test + fun `searchSynonyms with all parameters`() = runTest { + client.runTest( + call = { + searchSynonyms( + indexName = "indexName", + type = SynonymType.values().first { it.value == "altcorrection1" }, + page = 10, + hitsPerPage = 10, + searchSynonymsParams = SearchSynonymsParams( + query = "myQuery", + ), + ) + }, + intercept = { + assertEquals("/1/indexes/indexName/synonyms/search".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertContainsAll("""{"type":"altcorrection1","page":"10","hitsPerPage":"10"}""", it.url.parameters) + assertJsonBody("""{"query":"myQuery"}""", it.body) + }, + ) + } + + // searchUserIds + + @Test + fun `searchUserIds`() = runTest { + client.runTest( + call = { + searchUserIds( + searchUserIdsParams = SearchUserIdsParams( + query = "test", + clusterName = "theClusterName", + page = 5, + hitsPerPage = 10, + ), + ) + }, + intercept = { + assertEquals("/1/clusters/mapping/search".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("POST"), it.method) + assertJsonBody("""{"query":"test","clusterName":"theClusterName","page":5,"hitsPerPage":10}""", it.body) + }, + ) + } + + // setDictionarySettings + + @Test + fun `get setDictionarySettings results with minimal parameters`() = runTest { + client.runTest( + call = { + setDictionarySettings( + dictionarySettingsParams = DictionarySettingsParams( + disableStandardEntries = StandardEntries( + plurals = mapOf("fr" to false, "en" to false, "ru" to true), + ), + ), + ) + }, + intercept = { + assertEquals("/1/dictionaries/*/settings".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertJsonBody("""{"disableStandardEntries":{"plurals":{"fr":false,"en":false,"ru":true}}}""", it.body) + }, + ) + } + + @Test + fun `get setDictionarySettings results with all parameters`() = runTest { + client.runTest( + call = { + setDictionarySettings( + dictionarySettingsParams = DictionarySettingsParams( + disableStandardEntries = StandardEntries( + plurals = mapOf("fr" to false, "en" to false, "ru" to true), + stopwords = mapOf("fr" to false), + compounds = mapOf("ru" to true), + ), + ), + ) + }, + intercept = { + assertEquals("/1/dictionaries/*/settings".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertJsonBody("""{"disableStandardEntries":{"plurals":{"fr":false,"en":false,"ru":true},"stopwords":{"fr":false},"compounds":{"ru":true}}}""", it.body) + }, + ) + } + + // setSettings + + @Test + fun `setSettings with minimal parameters`() = runTest { + client.runTest( + call = { + setSettings( + indexName = "theIndexName", + indexSettings = IndexSettings( + paginationLimitedTo = 10, + ), + forwardToReplicas = true, + ) + }, + intercept = { + assertEquals("/1/indexes/theIndexName/settings".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertContainsAll("""{"forwardToReplicas":"true"}""", it.url.parameters) + assertJsonBody("""{"paginationLimitedTo":10}""", it.body) + }, + ) + } + + @Test + fun `setSettings allow boolean 'typoTolerance'`() = runTest { + client.runTest( + call = { + setSettings( + indexName = "theIndexName", + indexSettings = IndexSettings( + typoTolerance = TypoTolerance.Boolean(true), + ), + forwardToReplicas = true, + ) + }, + intercept = { + assertEquals("/1/indexes/theIndexName/settings".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertContainsAll("""{"forwardToReplicas":"true"}""", it.url.parameters) + assertJsonBody("""{"typoTolerance":true}""", it.body) + }, + ) + } + + @Test + fun `setSettings allow enum 'typoTolerance'`() = runTest { + client.runTest( + call = { + setSettings( + indexName = "theIndexName", + indexSettings = IndexSettings( + typoTolerance = TypoToleranceEnum.values().first { it.value == "min" }, + ), + forwardToReplicas = true, + ) + }, + intercept = { + assertEquals("/1/indexes/theIndexName/settings".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertContainsAll("""{"forwardToReplicas":"true"}""", it.url.parameters) + assertJsonBody("""{"typoTolerance":"min"}""", it.body) + }, + ) + } + + @Test + fun `setSettings allow boolean 'ignorePlurals'`() = runTest { + client.runTest( + call = { + setSettings( + indexName = "theIndexName", + indexSettings = IndexSettings( + ignorePlurals = IgnorePlurals.Boolean(true), + ), + forwardToReplicas = true, + ) + }, + intercept = { + assertEquals("/1/indexes/theIndexName/settings".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertContainsAll("""{"forwardToReplicas":"true"}""", it.url.parameters) + assertJsonBody("""{"ignorePlurals":true}""", it.body) + }, + ) + } + + @Test + fun `setSettings allow list of string 'ignorePlurals'`() = runTest { + client.runTest( + call = { + setSettings( + indexName = "theIndexName", + indexSettings = IndexSettings( + ignorePlurals = IgnorePlurals.ListOfString(listOf("algolia")), + ), + forwardToReplicas = true, + ) + }, + intercept = { + assertEquals("/1/indexes/theIndexName/settings".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertContainsAll("""{"forwardToReplicas":"true"}""", it.url.parameters) + assertJsonBody("""{"ignorePlurals":["algolia"]}""", it.body) + }, + ) + } + + @Test + fun `setSettings allow boolean 'removeStopWords'`() = runTest { + client.runTest( + call = { + setSettings( + indexName = "theIndexName", + indexSettings = IndexSettings( + removeStopWords = RemoveStopWords.Boolean(true), + ), + forwardToReplicas = true, + ) + }, + intercept = { + assertEquals("/1/indexes/theIndexName/settings".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertContainsAll("""{"forwardToReplicas":"true"}""", it.url.parameters) + assertJsonBody("""{"removeStopWords":true}""", it.body) + }, + ) + } + + @Test + fun `setSettings allow list of string 'removeStopWords'`() = runTest { + client.runTest( + call = { + setSettings( + indexName = "theIndexName", + indexSettings = IndexSettings( + removeStopWords = RemoveStopWords.ListOfString(listOf("algolia")), + ), + forwardToReplicas = true, + ) + }, + intercept = { + assertEquals("/1/indexes/theIndexName/settings".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertContainsAll("""{"forwardToReplicas":"true"}""", it.url.parameters) + assertJsonBody("""{"removeStopWords":["algolia"]}""", it.body) + }, + ) + } + + @Test + fun `setSettings allow boolean 'distinct'`() = runTest { + client.runTest( + call = { + setSettings( + indexName = "theIndexName", + indexSettings = IndexSettings( + distinct = Distinct.Boolean(true), + ), + forwardToReplicas = true, + ) + }, + intercept = { + assertEquals("/1/indexes/theIndexName/settings".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertContainsAll("""{"forwardToReplicas":"true"}""", it.url.parameters) + assertJsonBody("""{"distinct":true}""", it.body) + }, + ) + } + + @Test + fun `setSettings allow integers for 'distinct'`() = runTest { + client.runTest( + call = { + setSettings( + indexName = "theIndexName", + indexSettings = IndexSettings( + distinct = Distinct.Number(1.toNumberType()), + ), + forwardToReplicas = true, + ) + }, + intercept = { + assertEquals("/1/indexes/theIndexName/settings".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertContainsAll("""{"forwardToReplicas":"true"}""", it.url.parameters) + assertJsonBody("""{"distinct":1}""", it.body) + }, + ) + } + + @Test + fun `setSettings allow all 'indexSettings'`() = runTest { + client.runTest( + call = { + setSettings( + indexName = "theIndexName", + indexSettings = IndexSettings( + replicas = listOf(""), + paginationLimitedTo = 0, + disableTypoToleranceOnWords = listOf("algolia"), + attributesToTransliterate = listOf("algolia"), + camelCaseAttributes = listOf("algolia"), + decompoundedAttributes = buildJsonObject { + put( + "algolia", + JsonPrimitive("aloglia"), + ) + }, + indexLanguages = listOf("algolia"), + disablePrefixOnAttributes = listOf("algolia"), + allowCompressionOfIntegerArray = true, + numericAttributesForFiltering = listOf("algolia"), + separatorsToIndex = "algolia", + searchableAttributes = listOf("algolia"), + userData = buildJsonObject { + put( + "user", + JsonPrimitive("data"), + ) + }, + customNormalization = mapOf("algolia" to mapOf("aloglia" to "aglolia")), + attributesForFaceting = listOf("algolia"), + unretrievableAttributes = listOf("algolia"), + attributesToRetrieve = listOf("algolia"), + restrictSearchableAttributes = listOf("algolia"), + ranking = listOf("geo"), + customRanking = listOf("algolia"), + relevancyStrictness = 10, + attributesToHighlight = listOf("algolia"), + attributesToSnippet = listOf("algolia"), + highlightPreTag = "", + highlightPostTag = "", + snippetEllipsisText = "---", + restrictHighlightAndSnippetArrays = true, + hitsPerPage = 10, + minWordSizefor1Typo = 5, + minWordSizefor2Typos = 11, + typoTolerance = TypoTolerance.Boolean(false), + allowTyposOnNumericTokens = true, + disableTypoToleranceOnAttributes = listOf("algolia"), + ignorePlurals = IgnorePlurals.Boolean(false), + removeStopWords = RemoveStopWords.Boolean(false), + keepDiacriticsOnCharacters = "abc", + queryLanguages = listOf("algolia"), + decompoundQuery = false, + enableRules = false, + enablePersonalization = true, + queryType = QueryType.values().first { it.value == "prefixLast" }, + removeWordsIfNoResults = RemoveWordsIfNoResults.values().first { it.value == "lastWords" }, + advancedSyntax = true, + optionalWords = listOf("algolia"), + disableExactOnAttributes = listOf("algolia"), + exactOnSingleWordQuery = ExactOnSingleWordQuery.values().first { it.value == "attribute" }, + alternativesAsExact = listOf(AlternativesAsExact.values().first { it.value == "singleWordSynonym" }), + advancedSyntaxFeatures = listOf(AdvancedSyntaxFeatures.values().first { it.value == "exactPhrase" }), + distinct = Distinct.Number(3.toNumberType()), + attributeForDistinct = "test", + synonyms = false, + replaceSynonymsInHighlight = true, + minProximity = 6, + responseFields = listOf("algolia"), + maxFacetHits = 50, + attributeCriteriaComputedByMinProximity = true, + renderingContent = RenderingContent( + facetOrdering = FacetOrdering( + facets = Facets( + order = listOf("a", "b"), + ), + values = mapOf( + "a" to Value( + order = listOf("b"), + sortRemainingBy = SortRemainingBy.values().first { it.value == "count" }, + ), + ), + ), + ), + ), + ) + }, + intercept = { + assertEquals("/1/indexes/theIndexName/settings".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertJsonBody("""{"replicas":[""],"paginationLimitedTo":0,"disableTypoToleranceOnWords":["algolia"],"attributesToTransliterate":["algolia"],"camelCaseAttributes":["algolia"],"decompoundedAttributes":{"algolia":"aloglia"},"indexLanguages":["algolia"],"disablePrefixOnAttributes":["algolia"],"allowCompressionOfIntegerArray":true,"numericAttributesForFiltering":["algolia"],"separatorsToIndex":"algolia","searchableAttributes":["algolia"],"userData":{"user":"data"},"customNormalization":{"algolia":{"aloglia":"aglolia"}},"attributesForFaceting":["algolia"],"unretrievableAttributes":["algolia"],"attributesToRetrieve":["algolia"],"restrictSearchableAttributes":["algolia"],"ranking":["geo"],"customRanking":["algolia"],"relevancyStrictness":10,"attributesToHighlight":["algolia"],"attributesToSnippet":["algolia"],"highlightPreTag":"","highlightPostTag":"","snippetEllipsisText":"---","restrictHighlightAndSnippetArrays":true,"hitsPerPage":10,"minWordSizefor1Typo":5,"minWordSizefor2Typos":11,"typoTolerance":false,"allowTyposOnNumericTokens":true,"disableTypoToleranceOnAttributes":["algolia"],"ignorePlurals":false,"removeStopWords":false,"keepDiacriticsOnCharacters":"abc","queryLanguages":["algolia"],"decompoundQuery":false,"enableRules":false,"enablePersonalization":true,"queryType":"prefixLast","removeWordsIfNoResults":"lastWords","advancedSyntax":true,"optionalWords":["algolia"],"disableExactOnAttributes":["algolia"],"exactOnSingleWordQuery":"attribute","alternativesAsExact":["singleWordSynonym"],"advancedSyntaxFeatures":["exactPhrase"],"distinct":3,"attributeForDistinct":"test","synonyms":false,"replaceSynonymsInHighlight":true,"minProximity":6,"responseFields":["algolia"],"maxFacetHits":50,"attributeCriteriaComputedByMinProximity":true,"renderingContent":{"facetOrdering":{"facets":{"order":["a","b"]},"values":{"a":{"order":["b"],"sortRemainingBy":"count"}}}}}""", it.body) + }, + ) + } + + // updateApiKey + + @Test + fun `updateApiKey`() = runTest { + client.runTest( + call = { + updateApiKey( + key = "myApiKey", + apiKey = ApiKey( + acl = listOf(Acl.values().first { it.value == "search" }, Acl.values().first { it.value == "addObject" }), + validity = 300, + maxQueriesPerIPPerHour = 100, + maxHitsPerQuery = 20, + ), + ) + }, + intercept = { + assertEquals("/1/keys/myApiKey".toPathSegments(), it.url.pathSegments) + assertEquals(HttpMethod.parse("PUT"), it.method) + assertJsonBody("""{"acl":["search","addObject"],"validity":300,"maxQueriesPerIPPerHour":100,"maxHitsPerQuery":20}""", it.body) + }, + ) + } +}