From d67eddd9394ec1649d92ec3b524bfea528ee4c12 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Sun, 31 Aug 2025 13:54:41 +0700 Subject: [PATCH 01/41] use custom openapi generator template --- custom-templates/.travis.yml | 1 + custom-templates/Cargo.mustache | 109 + custom-templates/README.mustache | 54 + custom-templates/api_doc.mustache | 47 + custom-templates/git_push.sh.mustache | 57 + custom-templates/gitignore.mustache | 3 + custom-templates/hyper/api.mustache | 182 + custom-templates/hyper/api_mod.mustache | 83 + custom-templates/hyper/client.mustache | 55 + custom-templates/hyper/configuration.mustache | 83 + custom-templates/hyper0x/api.mustache | 181 + custom-templates/hyper0x/api_mod.mustache | 64 + custom-templates/hyper0x/client.mustache | 54 + .../hyper0x/configuration.mustache | 34 + custom-templates/lib.mustache | 17 + custom-templates/model.mustache | 225 + custom-templates/model_doc.mustache | 54 + custom-templates/model_mod.mustache | 45 + custom-templates/partial_header.mustache | 13 + custom-templates/request.rs | 247 + custom-templates/reqwest-trait/api.mustache | 558 ++ .../reqwest-trait/api_mod.mustache | 236 + .../reqwest-trait/configuration.mustache | 120 + custom-templates/reqwest/api.mustache | 515 ++ custom-templates/reqwest/api_mod.mustache | 164 + .../reqwest/configuration.mustache | 122 + openapi.yml | 2362 +++++++- preprocessed_openapi.yml | 4812 +++++++++++++++++ typesense/Cargo.toml | 19 + typesense/src/builders/mod.rs | 13 + .../multi_search_collection_parameters.rs | 265 + .../src/builders/multi_search_parameters.rs | 260 + .../multi_search_searches_parameters.rs | 127 + typesense/src/client/collection/document.rs | 154 + typesense/src/client/collection/documents.rs | 305 ++ typesense/src/client/collection/mod.rs | 103 + typesense/src/client/collections.rs | 60 + typesense/src/client/key.rs | 55 + typesense/src/client/keys.rs | 78 + typesense/src/client/mod.rs | 542 ++ typesense/src/collection_schema.rs | 1 + typesense/src/error.rs | 109 + typesense/src/field/mod.rs | 110 - typesense/src/keys.rs | 83 - typesense/src/lib.rs | 15 +- .../src/models/document_index_parameters.rs | 13 + typesense/src/models/mod.rs | 10 + typesense/src/models/multi_search.rs | 23 + typesense/src/models/scoped_key_parameters.rs | 25 + typesense/src/prelude.rs | 9 + typesense/src/traits/document.rs | 14 + typesense/src/{field => traits}/field_type.rs | 19 +- typesense/src/traits/mod.rs | 9 + typesense/src/traits/multi_search_ext.rs | 18 + typesense/tests/api/collection.rs | 136 - typesense/tests/api/documents.rs | 111 - typesense/tests/api/lib.rs | 41 - typesense_codegen/.openapi-generator-ignore | 5 + typesense_codegen/.openapi-generator/FILES | 167 +- typesense_codegen/.openapi-generator/VERSION | 2 +- typesense_codegen/Cargo.toml | 18 +- typesense_codegen/README.md | 132 +- typesense_codegen/docs/AnalyticsApi.md | 189 +- typesense_codegen/docs/AnalyticsEvent.md | 13 + .../docs/AnalyticsEventCreateResponse.md | 11 + .../docs/AnalyticsEventCreateSchema.md | 13 + typesense_codegen/docs/AnalyticsEventData.md | 15 + .../docs/AnalyticsEventsResponse.md | 11 + .../AnalyticsEventsResponseEventsInner.md | 18 + typesense_codegen/docs/AnalyticsRule.md | 16 + typesense_codegen/docs/AnalyticsRuleCreate.md | 16 + .../docs/AnalyticsRuleCreateParams.md | 17 + .../docs/AnalyticsRuleDeleteResponse.md | 11 + .../docs/AnalyticsRuleParameters.md | 7 +- .../AnalyticsRuleParametersDestination.md | 3 +- .../docs/AnalyticsRuleParametersSource.md | 3 +- ...nalyticsRuleParametersSourceEventsInner.md | 13 + typesense_codegen/docs/AnalyticsRuleSchema.md | 4 +- typesense_codegen/docs/AnalyticsRuleUpdate.md | 13 + .../docs/AnalyticsRuleUpsertSchema.md | 12 + .../docs/AnalyticsRulesRetrieveSchema.md | 2 +- typesense_codegen/docs/AnalyticsStatus.md | 17 + .../docs/ApiKeyDeleteResponse.md | 11 + typesense_codegen/docs/ApiKeysResponse.md | 2 +- typesense_codegen/docs/ApiStatsResponse.md | 23 + .../docs/CollectionAliasesResponse.md | 2 +- typesense_codegen/docs/CollectionResponse.md | 7 +- typesense_codegen/docs/CollectionSchema.md | 7 +- .../docs/CollectionUpdateSchema.md | 4 +- typesense_codegen/docs/CollectionsApi.md | 45 +- .../docs/ConversationModelCreateSchema.md | 19 + .../docs/ConversationModelSchema.md | 19 + .../docs/ConversationModelUpdateSchema.md | 19 + typesense_codegen/docs/ConversationsApi.md | 161 + .../docs/CreateAnalyticsRule200Response.md | 12 + ...reateAnalyticsRule200ResponseOneOfInner.md | 17 + ...AnalyticsRule200ResponseOneOfInnerAnyOf.md | 11 + .../docs/CreateAnalyticsRuleRequest.md | 12 + .../docs/{PromoteApi.md => CurationApi.md} | 22 +- typesense_codegen/docs/DebugApi.md | 6 +- ...mentsDeleteDocumentsParametersParameter.md | 4 +- .../docs/DeleteDocumentsParameters.md | 14 + .../docs/DeleteStopwordsSet200Response.md | 11 + typesense_codegen/docs/DirtyValues.md | 15 + .../docs/DocumentIndexParameters.md | 11 + typesense_codegen/docs/DocumentsApi.md | 329 +- typesense_codegen/docs/DropTokensMode.md | 14 + ...mentsExportDocumentsParametersParameter.md | 4 +- .../docs/ExportDocumentsParameters.md | 13 + typesense_codegen/docs/FacetCounts.md | 4 +- .../docs/FacetCountsCountsInner.md | 1 + typesense_codegen/docs/Field.md | 10 +- typesense_codegen/docs/FieldEmbed.md | 2 +- .../docs/FieldEmbedModelConfig.md | 4 + ...ctionsGetCollectionsParametersParameter.md | 13 + .../docs/GetCollectionsParameters.md | 13 + typesense_codegen/docs/HealthApi.md | 6 +- ...mentsImportDocumentsParametersParameter.md | 6 +- .../docs/ImportDocumentsParameters.md | 16 + typesense_codegen/docs/IndexAction.md | 15 + typesense_codegen/docs/KeysApi.md | 18 +- .../ListStemmingDictionaries200Response.md | 11 + .../docs/MultiSearchCollectionParameters.md | 45 +- .../docs/MultiSearchParameters.md | 41 +- typesense_codegen/docs/MultiSearchResult.md | 3 +- .../docs/MultiSearchResultItem.md | 24 + .../docs/MultiSearchSearchesParameter.md | 3 +- typesense_codegen/docs/NlSearchModelBase.md | 28 + .../docs/NlSearchModelCreateSchema.md | 29 + .../docs/NlSearchModelDeleteSchema.md | 11 + typesense_codegen/docs/NlSearchModelSchema.md | 29 + typesense_codegen/docs/NlSearchModelsApi.md | 161 + typesense_codegen/docs/OperationsApi.md | 181 +- typesense_codegen/docs/OverrideApi.md | 6 +- typesense_codegen/docs/PresetDeleteSchema.md | 11 + typesense_codegen/docs/PresetSchema.md | 12 + typesense_codegen/docs/PresetUpsertSchema.md | 11 + .../docs/PresetUpsertSchemaValue.md | 12 + typesense_codegen/docs/PresetsApi.md | 130 + .../docs/PresetsRetrieveSchema.md | 11 + typesense_codegen/docs/SchemaChangeStatus.md | 13 + typesense_codegen/docs/SearchGroupedHit.md | 2 +- typesense_codegen/docs/SearchOverride.md | 13 +- .../docs/SearchOverrideDeleteResponse.md | 11 + typesense_codegen/docs/SearchOverrideRule.md | 6 +- .../docs/SearchOverrideSchema.md | 13 +- .../docs/SearchOverridesResponse.md | 2 +- typesense_codegen/docs/SearchParameters.md | 52 +- typesense_codegen/docs/SearchRequestParams.md | 14 + .../docs/SearchRequestParamsVoiceQuery.md | 11 + typesense_codegen/docs/SearchResult.md | 11 +- .../docs/SearchResultConversation.md | 14 + typesense_codegen/docs/SearchResultHit.md | 11 +- .../docs/SearchResultHitHybridSearchInfo.md | 11 + .../docs/SearchResultHitTextMatchInfo.md | 17 + .../docs/SearchResultRequestParams.md | 1 + .../SearchResultRequestParamsVoiceQuery.md | 11 + typesense_codegen/docs/SearchSynonym.md | 2 + .../docs/SearchSynonymDeleteResponse.md | 11 + typesense_codegen/docs/SearchSynonymSchema.md | 2 + .../docs/SearchSynonymsResponse.md | 2 +- typesense_codegen/docs/StemmingApi.md | 99 + typesense_codegen/docs/StemmingDictionary.md | 12 + .../docs/StemmingDictionaryWordsInner.md | 12 + typesense_codegen/docs/StopwordsApi.md | 130 + .../docs/StopwordsSetRetrieveSchema.md | 11 + typesense_codegen/docs/StopwordsSetSchema.md | 13 + .../docs/StopwordsSetUpsertSchema.md | 12 + .../docs/StopwordsSetsRetrieveAllSchema.md | 11 + typesense_codegen/docs/SynonymItemSchema.md | 15 + .../docs/SynonymSetCreateSchema.md | 11 + .../docs/SynonymSetDeleteSchema.md | 11 + typesense_codegen/docs/SynonymSetSchema.md | 12 + .../docs/SynonymSetsRetrieveSchema.md | 11 + typesense_codegen/docs/SynonymsApi.md | 130 + .../docs/ToggleSlowRequestLogRequest.md | 11 + .../docs/UpdateDocumentsParameters.md | 11 + .../docs/VoiceQueryModelCollectionConfig.md | 11 + typesense_codegen/src/apis/analytics_api.rs | 614 ++- typesense_codegen/src/apis/collections_api.rs | 775 +-- typesense_codegen/src/apis/configuration.rs | 21 +- .../src/apis/conversations_api.rs | 299 + typesense_codegen/src/apis/curation_api.rs | 196 + typesense_codegen/src/apis/debug_api.rs | 76 +- typesense_codegen/src/apis/documents_api.rs | 2154 ++++---- typesense_codegen/src/apis/health_api.rs | 76 +- typesense_codegen/src/apis/keys_api.rs | 334 +- typesense_codegen/src/apis/mod.rs | 42 +- .../src/apis/nl_search_models_api.rs | 305 ++ typesense_codegen/src/apis/operations_api.rs | 467 +- typesense_codegen/src/apis/override_api.rs | 93 +- typesense_codegen/src/apis/presets_api.rs | 245 + typesense_codegen/src/apis/promote_api.rs | 192 - typesense_codegen/src/apis/stemming_api.rs | 188 + typesense_codegen/src/apis/stopwords_api.rs | 245 + typesense_codegen/src/apis/synonyms_api.rs | 245 + typesense_codegen/src/lib.rs | 5 +- .../src/models/analytics_event.rs | 35 + .../models/analytics_event_create_response.rs | 27 + .../src/models/analytics_event_data.rs | 41 + .../src/models/analytics_events_response.rs | 27 + .../analytics_events_response_events_inner.rs | 48 + .../src/models/analytics_rule.rs | 60 + .../src/models/analytics_rule_create.rs | 60 + .../models/analytics_rule_create_params.rs | 45 + .../src/models/analytics_rule_parameters.rs | 33 - .../analytics_rule_parameters_destination.rs | 21 - .../analytics_rule_parameters_source.rs | 21 - .../src/models/analytics_rule_schema.rs | 33 - .../src/models/analytics_rule_update.rs | 35 + .../models/analytics_rules_retrieve_schema.rs | 21 - .../src/models/analytics_status.rs | 45 + typesense_codegen/src/models/api_key.rs | 8 +- .../src/models/api_key_delete_response.rs | 28 + .../src/models/api_key_schema.rs | 14 +- .../src/models/api_keys_response.rs | 16 +- typesense_codegen/src/models/api_response.rs | 12 +- .../src/models/api_stats_response.rs | 63 + .../src/models/collection_alias.rs | 8 +- .../src/models/collection_alias_schema.rs | 12 +- .../src/models/collection_aliases_response.rs | 16 +- .../src/models/collection_response.rs | 42 +- .../src/models/collection_schema.rs | 37 +- .../src/models/collection_update_schema.rs | 24 +- .../conversation_model_create_schema.rs | 60 + .../src/models/conversation_model_schema.rs | 60 + .../conversation_model_update_schema.rs | 60 + .../create_analytics_rule_200_response.rs | 44 + ...nalytics_rule_200_response_one_of_inner.rs | 63 + ...s_rule_200_response_one_of_inner_any_of.rs | 27 + .../models/create_analytics_rule_request.rs | 44 + .../src/models/debug_200_response.rs | 12 +- .../models/delete_documents_200_response.rs | 12 +- ...s_delete_documents_parameters_parameter.rs | 27 - .../src/models/delete_documents_parameters.rs | 38 + .../delete_stopwords_set_200_response.rs | 27 + typesense_codegen/src/models/dirty_values.rs | 44 + .../src/models/drop_tokens_mode.rs | 42 + .../src/models/error_response.rs | 21 - ...eter.rs => export_documents_parameters.rs} | 31 +- typesense_codegen/src/models/facet_counts.rs | 12 +- .../src/models/facet_counts_counts_inner.rs | 11 +- .../src/models/facet_counts_stats.rs | 8 +- typesense_codegen/src/models/field.rs | 42 +- typesense_codegen/src/models/field_embed.rs | 15 +- .../src/models/field_embed_model_config.rs | 20 +- .../src/models/get_collections_parameters.rs | 36 + typesense_codegen/src/models/health_status.rs | 12 +- ...s_import_documents_parameters_parameter.rs | 53 - .../src/models/import_documents_parameters.rs | 43 + typesense_codegen/src/models/index_action.rs | 44 + ...list_stemming_dictionaries_200_response.rs | 27 + typesense_codegen/src/models/mod.rs | 146 +- .../multi_search_collection_parameters.rs | 196 +- .../src/models/multi_search_parameters.rs | 181 +- .../src/models/multi_search_result.rs | 23 +- .../src/models/multi_search_result_item.rs | 75 + .../models/multi_search_searches_parameter.rs | 22 +- .../src/models/nl_search_model_base.rs | 96 + .../models/nl_search_model_create_schema.rs | 100 + .../models/nl_search_model_delete_schema.rs | 28 + .../src/models/nl_search_model_schema.rs | 100 + .../src/models/preset_delete_schema.rs | 27 + typesense_codegen/src/models/preset_schema.rs | 30 + .../src/models/preset_upsert_schema.rs | 27 + .../src/models/preset_upsert_schema_value.rs | 26 + .../src/models/presets_retrieve_schema.rs | 27 + .../src/models/schema_change_status.rs | 36 + .../src/models/scoped_key_parameters.rs | 8 +- .../src/models/search_grouped_hit.rs | 21 +- .../src/models/search_highlight.rs | 8 +- .../src/models/search_override.rs | 53 +- .../models/search_override_delete_response.rs | 28 + .../src/models/search_override_exclude.rs | 12 +- .../src/models/search_override_include.rs | 13 +- .../src/models/search_override_rule.rs | 36 +- .../src/models/search_override_schema.rs | 53 +- .../src/models/search_overrides_response.rs | 16 +- .../src/models/search_parameters.rs | 224 +- ...est_params.rs => search_request_params.rs} | 19 +- .../search_request_params_voice_query.rs | 27 + typesense_codegen/src/models/search_result.rs | 34 +- .../src/models/search_result_conversation.rs | 36 + .../src/models/search_result_hit.rs | 39 +- .../search_result_hit_hybrid_search_info.rs | 30 + .../search_result_hit_text_match_info.rs | 45 + .../src/models/search_synonym.rs | 16 +- .../models/search_synonym_delete_response.rs | 28 + .../src/models/search_synonym_schema.rs | 16 +- .../src/models/search_synonyms_response.rs | 16 +- .../src/models/snapshot_parameters.rs | 23 - .../src/models/stemming_dictionary.rs | 32 + .../models/stemming_dictionary_words_inner.rs | 32 + .../models/stopwords_set_retrieve_schema.rs | 27 + .../src/models/stopwords_set_schema.rs | 33 + .../src/models/stopwords_set_upsert_schema.rs | 30 + .../stopwords_sets_retrieve_all_schema.rs | 27 + .../src/models/success_status.rs | 12 +- .../src/models/synonym_item_schema.rs | 44 + .../src/models/synonym_set_create_schema.rs | 28 + .../src/models/synonym_set_delete_schema.rs | 28 + .../src/models/synonym_set_schema.rs | 32 + .../models/synonym_sets_retrieve_schema.rs | 28 + .../models/toggle_slow_request_log_request.rs | 27 + .../models/update_documents_200_response.rs | 12 +- ...eter.rs => update_documents_parameters.rs} | 18 +- .../voice_query_model_collection_config.rs | 29 + xtask/src/main.rs | 5 +- xtask/src/preprocess_openapi.rs | 13 +- 309 files changed, 23231 insertions(+), 3892 deletions(-) create mode 100644 custom-templates/.travis.yml create mode 100644 custom-templates/Cargo.mustache create mode 100644 custom-templates/README.mustache create mode 100644 custom-templates/api_doc.mustache create mode 100644 custom-templates/git_push.sh.mustache create mode 100644 custom-templates/gitignore.mustache create mode 100644 custom-templates/hyper/api.mustache create mode 100644 custom-templates/hyper/api_mod.mustache create mode 100644 custom-templates/hyper/client.mustache create mode 100644 custom-templates/hyper/configuration.mustache create mode 100644 custom-templates/hyper0x/api.mustache create mode 100644 custom-templates/hyper0x/api_mod.mustache create mode 100644 custom-templates/hyper0x/client.mustache create mode 100644 custom-templates/hyper0x/configuration.mustache create mode 100644 custom-templates/lib.mustache create mode 100644 custom-templates/model.mustache create mode 100644 custom-templates/model_doc.mustache create mode 100644 custom-templates/model_mod.mustache create mode 100644 custom-templates/partial_header.mustache create mode 100644 custom-templates/request.rs create mode 100644 custom-templates/reqwest-trait/api.mustache create mode 100644 custom-templates/reqwest-trait/api_mod.mustache create mode 100644 custom-templates/reqwest-trait/configuration.mustache create mode 100644 custom-templates/reqwest/api.mustache create mode 100644 custom-templates/reqwest/api_mod.mustache create mode 100644 custom-templates/reqwest/configuration.mustache create mode 100644 preprocessed_openapi.yml create mode 100644 typesense/src/builders/mod.rs create mode 100644 typesense/src/builders/multi_search_collection_parameters.rs create mode 100644 typesense/src/builders/multi_search_parameters.rs create mode 100644 typesense/src/builders/multi_search_searches_parameters.rs create mode 100644 typesense/src/client/collection/document.rs create mode 100644 typesense/src/client/collection/documents.rs create mode 100644 typesense/src/client/collection/mod.rs create mode 100644 typesense/src/client/collections.rs create mode 100644 typesense/src/client/key.rs create mode 100644 typesense/src/client/keys.rs create mode 100644 typesense/src/client/mod.rs create mode 100644 typesense/src/error.rs delete mode 100644 typesense/src/field/mod.rs delete mode 100644 typesense/src/keys.rs create mode 100644 typesense/src/models/document_index_parameters.rs create mode 100644 typesense/src/models/mod.rs create mode 100644 typesense/src/models/multi_search.rs create mode 100644 typesense/src/models/scoped_key_parameters.rs create mode 100644 typesense/src/prelude.rs create mode 100644 typesense/src/traits/document.rs rename typesense/src/{field => traits}/field_type.rs (82%) create mode 100644 typesense/src/traits/mod.rs create mode 100644 typesense/src/traits/multi_search_ext.rs delete mode 100644 typesense/tests/api/collection.rs delete mode 100644 typesense/tests/api/documents.rs delete mode 100644 typesense/tests/api/lib.rs create mode 100644 typesense_codegen/docs/AnalyticsEvent.md create mode 100644 typesense_codegen/docs/AnalyticsEventCreateResponse.md create mode 100644 typesense_codegen/docs/AnalyticsEventCreateSchema.md create mode 100644 typesense_codegen/docs/AnalyticsEventData.md create mode 100644 typesense_codegen/docs/AnalyticsEventsResponse.md create mode 100644 typesense_codegen/docs/AnalyticsEventsResponseEventsInner.md create mode 100644 typesense_codegen/docs/AnalyticsRule.md create mode 100644 typesense_codegen/docs/AnalyticsRuleCreate.md create mode 100644 typesense_codegen/docs/AnalyticsRuleCreateParams.md create mode 100644 typesense_codegen/docs/AnalyticsRuleDeleteResponse.md create mode 100644 typesense_codegen/docs/AnalyticsRuleParametersSourceEventsInner.md create mode 100644 typesense_codegen/docs/AnalyticsRuleUpdate.md create mode 100644 typesense_codegen/docs/AnalyticsRuleUpsertSchema.md create mode 100644 typesense_codegen/docs/AnalyticsStatus.md create mode 100644 typesense_codegen/docs/ApiKeyDeleteResponse.md create mode 100644 typesense_codegen/docs/ApiStatsResponse.md create mode 100644 typesense_codegen/docs/ConversationModelCreateSchema.md create mode 100644 typesense_codegen/docs/ConversationModelSchema.md create mode 100644 typesense_codegen/docs/ConversationModelUpdateSchema.md create mode 100644 typesense_codegen/docs/ConversationsApi.md create mode 100644 typesense_codegen/docs/CreateAnalyticsRule200Response.md create mode 100644 typesense_codegen/docs/CreateAnalyticsRule200ResponseOneOfInner.md create mode 100644 typesense_codegen/docs/CreateAnalyticsRule200ResponseOneOfInnerAnyOf.md create mode 100644 typesense_codegen/docs/CreateAnalyticsRuleRequest.md rename typesense_codegen/docs/{PromoteApi.md => CurationApi.md} (70%) create mode 100644 typesense_codegen/docs/DeleteDocumentsParameters.md create mode 100644 typesense_codegen/docs/DeleteStopwordsSet200Response.md create mode 100644 typesense_codegen/docs/DirtyValues.md create mode 100644 typesense_codegen/docs/DocumentIndexParameters.md create mode 100644 typesense_codegen/docs/DropTokensMode.md create mode 100644 typesense_codegen/docs/ExportDocumentsParameters.md create mode 100644 typesense_codegen/docs/GetCollectionsGetCollectionsParametersParameter.md create mode 100644 typesense_codegen/docs/GetCollectionsParameters.md create mode 100644 typesense_codegen/docs/ImportDocumentsParameters.md create mode 100644 typesense_codegen/docs/IndexAction.md create mode 100644 typesense_codegen/docs/ListStemmingDictionaries200Response.md create mode 100644 typesense_codegen/docs/MultiSearchResultItem.md create mode 100644 typesense_codegen/docs/NlSearchModelBase.md create mode 100644 typesense_codegen/docs/NlSearchModelCreateSchema.md create mode 100644 typesense_codegen/docs/NlSearchModelDeleteSchema.md create mode 100644 typesense_codegen/docs/NlSearchModelSchema.md create mode 100644 typesense_codegen/docs/NlSearchModelsApi.md create mode 100644 typesense_codegen/docs/PresetDeleteSchema.md create mode 100644 typesense_codegen/docs/PresetSchema.md create mode 100644 typesense_codegen/docs/PresetUpsertSchema.md create mode 100644 typesense_codegen/docs/PresetUpsertSchemaValue.md create mode 100644 typesense_codegen/docs/PresetsApi.md create mode 100644 typesense_codegen/docs/PresetsRetrieveSchema.md create mode 100644 typesense_codegen/docs/SchemaChangeStatus.md create mode 100644 typesense_codegen/docs/SearchOverrideDeleteResponse.md create mode 100644 typesense_codegen/docs/SearchRequestParams.md create mode 100644 typesense_codegen/docs/SearchRequestParamsVoiceQuery.md create mode 100644 typesense_codegen/docs/SearchResultConversation.md create mode 100644 typesense_codegen/docs/SearchResultHitHybridSearchInfo.md create mode 100644 typesense_codegen/docs/SearchResultHitTextMatchInfo.md create mode 100644 typesense_codegen/docs/SearchResultRequestParamsVoiceQuery.md create mode 100644 typesense_codegen/docs/SearchSynonymDeleteResponse.md create mode 100644 typesense_codegen/docs/StemmingApi.md create mode 100644 typesense_codegen/docs/StemmingDictionary.md create mode 100644 typesense_codegen/docs/StemmingDictionaryWordsInner.md create mode 100644 typesense_codegen/docs/StopwordsApi.md create mode 100644 typesense_codegen/docs/StopwordsSetRetrieveSchema.md create mode 100644 typesense_codegen/docs/StopwordsSetSchema.md create mode 100644 typesense_codegen/docs/StopwordsSetUpsertSchema.md create mode 100644 typesense_codegen/docs/StopwordsSetsRetrieveAllSchema.md create mode 100644 typesense_codegen/docs/SynonymItemSchema.md create mode 100644 typesense_codegen/docs/SynonymSetCreateSchema.md create mode 100644 typesense_codegen/docs/SynonymSetDeleteSchema.md create mode 100644 typesense_codegen/docs/SynonymSetSchema.md create mode 100644 typesense_codegen/docs/SynonymSetsRetrieveSchema.md create mode 100644 typesense_codegen/docs/SynonymsApi.md create mode 100644 typesense_codegen/docs/ToggleSlowRequestLogRequest.md create mode 100644 typesense_codegen/docs/UpdateDocumentsParameters.md create mode 100644 typesense_codegen/docs/VoiceQueryModelCollectionConfig.md create mode 100644 typesense_codegen/src/apis/conversations_api.rs create mode 100644 typesense_codegen/src/apis/curation_api.rs create mode 100644 typesense_codegen/src/apis/nl_search_models_api.rs create mode 100644 typesense_codegen/src/apis/presets_api.rs delete mode 100644 typesense_codegen/src/apis/promote_api.rs create mode 100644 typesense_codegen/src/apis/stemming_api.rs create mode 100644 typesense_codegen/src/apis/stopwords_api.rs create mode 100644 typesense_codegen/src/apis/synonyms_api.rs create mode 100644 typesense_codegen/src/models/analytics_event.rs create mode 100644 typesense_codegen/src/models/analytics_event_create_response.rs create mode 100644 typesense_codegen/src/models/analytics_event_data.rs create mode 100644 typesense_codegen/src/models/analytics_events_response.rs create mode 100644 typesense_codegen/src/models/analytics_events_response_events_inner.rs create mode 100644 typesense_codegen/src/models/analytics_rule.rs create mode 100644 typesense_codegen/src/models/analytics_rule_create.rs create mode 100644 typesense_codegen/src/models/analytics_rule_create_params.rs delete mode 100644 typesense_codegen/src/models/analytics_rule_parameters.rs delete mode 100644 typesense_codegen/src/models/analytics_rule_parameters_destination.rs delete mode 100644 typesense_codegen/src/models/analytics_rule_parameters_source.rs delete mode 100644 typesense_codegen/src/models/analytics_rule_schema.rs create mode 100644 typesense_codegen/src/models/analytics_rule_update.rs delete mode 100644 typesense_codegen/src/models/analytics_rules_retrieve_schema.rs create mode 100644 typesense_codegen/src/models/analytics_status.rs create mode 100644 typesense_codegen/src/models/api_key_delete_response.rs create mode 100644 typesense_codegen/src/models/api_stats_response.rs create mode 100644 typesense_codegen/src/models/conversation_model_create_schema.rs create mode 100644 typesense_codegen/src/models/conversation_model_schema.rs create mode 100644 typesense_codegen/src/models/conversation_model_update_schema.rs create mode 100644 typesense_codegen/src/models/create_analytics_rule_200_response.rs create mode 100644 typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs create mode 100644 typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs create mode 100644 typesense_codegen/src/models/create_analytics_rule_request.rs delete mode 100644 typesense_codegen/src/models/delete_documents_delete_documents_parameters_parameter.rs create mode 100644 typesense_codegen/src/models/delete_documents_parameters.rs create mode 100644 typesense_codegen/src/models/delete_stopwords_set_200_response.rs create mode 100644 typesense_codegen/src/models/dirty_values.rs create mode 100644 typesense_codegen/src/models/drop_tokens_mode.rs delete mode 100644 typesense_codegen/src/models/error_response.rs rename typesense_codegen/src/models/{export_documents_export_documents_parameters_parameter.rs => export_documents_parameters.rs} (52%) create mode 100644 typesense_codegen/src/models/get_collections_parameters.rs delete mode 100644 typesense_codegen/src/models/import_documents_import_documents_parameters_parameter.rs create mode 100644 typesense_codegen/src/models/import_documents_parameters.rs create mode 100644 typesense_codegen/src/models/index_action.rs create mode 100644 typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs create mode 100644 typesense_codegen/src/models/multi_search_result_item.rs create mode 100644 typesense_codegen/src/models/nl_search_model_base.rs create mode 100644 typesense_codegen/src/models/nl_search_model_create_schema.rs create mode 100644 typesense_codegen/src/models/nl_search_model_delete_schema.rs create mode 100644 typesense_codegen/src/models/nl_search_model_schema.rs create mode 100644 typesense_codegen/src/models/preset_delete_schema.rs create mode 100644 typesense_codegen/src/models/preset_schema.rs create mode 100644 typesense_codegen/src/models/preset_upsert_schema.rs create mode 100644 typesense_codegen/src/models/preset_upsert_schema_value.rs create mode 100644 typesense_codegen/src/models/presets_retrieve_schema.rs create mode 100644 typesense_codegen/src/models/schema_change_status.rs create mode 100644 typesense_codegen/src/models/search_override_delete_response.rs rename typesense_codegen/src/models/{search_result_request_params.rs => search_request_params.rs} (57%) create mode 100644 typesense_codegen/src/models/search_request_params_voice_query.rs create mode 100644 typesense_codegen/src/models/search_result_conversation.rs create mode 100644 typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs create mode 100644 typesense_codegen/src/models/search_result_hit_text_match_info.rs create mode 100644 typesense_codegen/src/models/search_synonym_delete_response.rs delete mode 100644 typesense_codegen/src/models/snapshot_parameters.rs create mode 100644 typesense_codegen/src/models/stemming_dictionary.rs create mode 100644 typesense_codegen/src/models/stemming_dictionary_words_inner.rs create mode 100644 typesense_codegen/src/models/stopwords_set_retrieve_schema.rs create mode 100644 typesense_codegen/src/models/stopwords_set_schema.rs create mode 100644 typesense_codegen/src/models/stopwords_set_upsert_schema.rs create mode 100644 typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs create mode 100644 typesense_codegen/src/models/synonym_item_schema.rs create mode 100644 typesense_codegen/src/models/synonym_set_create_schema.rs create mode 100644 typesense_codegen/src/models/synonym_set_delete_schema.rs create mode 100644 typesense_codegen/src/models/synonym_set_schema.rs create mode 100644 typesense_codegen/src/models/synonym_sets_retrieve_schema.rs create mode 100644 typesense_codegen/src/models/toggle_slow_request_log_request.rs rename typesense_codegen/src/models/{update_documents_update_documents_parameters_parameter.rs => update_documents_parameters.rs} (51%) create mode 100644 typesense_codegen/src/models/voice_query_model_collection_config.rs diff --git a/custom-templates/.travis.yml b/custom-templates/.travis.yml new file mode 100644 index 0000000..22761ba --- /dev/null +++ b/custom-templates/.travis.yml @@ -0,0 +1 @@ +language: rust diff --git a/custom-templates/Cargo.mustache b/custom-templates/Cargo.mustache new file mode 100644 index 0000000..30f73e8 --- /dev/null +++ b/custom-templates/Cargo.mustache @@ -0,0 +1,109 @@ +[package] +name = "{{{packageName}}}" +version = "{{#lambdaVersion}}{{{packageVersion}}}{{/lambdaVersion}}" +{{#infoEmail}} +authors = ["{{{.}}}"] +{{/infoEmail}} +{{^infoEmail}} +authors = ["OpenAPI Generator team and contributors"] +{{/infoEmail}} +{{#appDescription}} +description = "{{{.}}}" +{{/appDescription}} +{{#licenseInfo}} +license = "{{.}}" +{{/licenseInfo}} +{{^licenseInfo}} +# Override this license by providing a License Object in the OpenAPI. +license = "Unlicense" +{{/licenseInfo}} +edition = "2021" +{{#publishRustRegistry}} +publish = ["{{.}}"] +{{/publishRustRegistry}} +{{#repositoryUrl}} +repository = "{{.}}" +{{/repositoryUrl}} +{{#documentationUrl}} +documentation = "{{.}}" +{{/documentationUrl}} +{{#homePageUrl}} +homepage = "{{.}}" +{{/homePageUrl}} + +[dependencies] +serde = { version = "^1.0", features = ["derive"] } +{{#serdeWith}} +serde_with = { version = "^3.8", default-features = false, features = ["base64", "std", "macros"] } +{{/serdeWith}} +serde_json = "^1.0" +serde_repr = "^0.1" +url = "^2.5" +{{#hasUUIDs}} +uuid = { version = "^1.8", features = ["serde", "v4"] } +{{/hasUUIDs}} +{{#hyper}} +{{#hyper0x}} +hyper = { version = "~0.14", features = ["full"] } +hyper-tls = "~0.5" +{{/hyper0x}} +{{^hyper0x}} +hyper = { version = "^1.3.1", features = ["full"] } +hyper-util = { version = "0.1.5", features = ["client", "client-legacy", "http1", "http2"] } +http-body-util = { version = "0.1.2" } +{{/hyper0x}} +http = "~0.2" +base64 = "~0.7.0" +futures = "^0.3" +{{/hyper}} +{{#withAWSV4Signature}} +aws-sigv4 = "0.3.0" +http = "0.2.5" +secrecy = "0.8.0" +{{/withAWSV4Signature}} +{{#reqwest}} +{{^supportAsync}} +reqwest = { version = "^0.12", default-features = false, features = ["json", "blocking", "multipart"] } +{{#supportMiddleware}} +reqwest-middleware = { version = "^0.4", features = ["json", "blocking", "multipart"] } +{{/supportMiddleware}} +{{/supportAsync}} +{{#supportAsync}} +reqwest = { version = "^0.12", default-features = false, features = ["json", "multipart"] } +{{#supportMiddleware}} +reqwest-middleware = { version = "^0.4", features = ["json", "multipart"] } +{{/supportMiddleware}} +{{#supportTokenSource}} +async-trait = "^0.1" +# TODO: propose to Yoshidan to externalize this as non google related crate, so that it can easily be extended for other cloud providers. +google-cloud-token = "^0.1" +{{/supportTokenSource}} +{{/supportAsync}} +{{/reqwest}} +{{#reqwestTrait}} +async-trait = "^0.1" +reqwest = { version = "^0.12", default-features = false, features = ["json", "multipart"] } +{{#supportMiddleware}} +reqwest-middleware = { version = "^0.4", features = ["json", "multipart"] } +{{/supportMiddleware}} +{{#supportTokenSource}} +# TODO: propose to Yoshidan to externalize this as non google related crate, so that it can easily be extended for other cloud providers. +google-cloud-token = "^0.1" +{{/supportTokenSource}} +{{#mockall}} +mockall = { version = "^0.13", optional = true} +{{/mockall}} +{{#useBonBuilder}} +bon = { version = "2.3", optional = true } +{{/useBonBuilder}} +[features] +default = ["native-tls"] +native-tls = ["reqwest/native-tls"] +rustls = ["reqwest/rustls-tls"] +{{#mockall}} +mockall = ["dep:mockall"] +{{/mockall}} +{{#useBonBuilder}} +bon = ["dep:bon"] +{{/useBonBuilder}} +{{/reqwestTrait}} diff --git a/custom-templates/README.mustache b/custom-templates/README.mustache new file mode 100644 index 0000000..0e8bfb3 --- /dev/null +++ b/custom-templates/README.mustache @@ -0,0 +1,54 @@ +# Rust API client for {{{packageName}}} + +{{#appDescriptionWithNewLines}} +{{{.}}} +{{/appDescriptionWithNewLines}} + +{{#infoUrl}} +For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + +## Overview + +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://openapis.org) from a remote server, you can easily generate an API client. + +- API version: {{{appVersion}}} +- Package version: {{{packageVersion}}} +{{^hideGenerationTimestamp}} +- Build date: {{{generatedDate}}} +{{/hideGenerationTimestamp}} +- Generator version: {{generatorVersion}} +- Build package: `{{{generatorClass}}}` + +## Installation + +Put the package under your project folder in a directory named `{{packageName}}` and add the following to `Cargo.toml` under `[dependencies]`: + +``` +{{{packageName}}} = { path = "./{{{packageName}}}" } +``` + +## Documentation for API Endpoints + +All URIs are relative to *{{{basePath}}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{{classname}}}* | [**{{{operationId}}}**]({{{apiDocPath}}}{{classname}}.md#{{{operationIdLowerCase}}}) | **{{{httpMethod}}}** {{{path}}} | {{{summary}}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + +## Documentation For Models + +{{#models}}{{#model}} - [{{{classname}}}]({{{modelDocPath}}}{{{classname}}}.md) +{{/model}}{{/models}} + +To get access to the crate's generated documentation, use: + +``` +cargo doc --open +``` + +## Author + +{{#apiInfo}}{{#apis}}{{#-last}}{{{infoEmail}}} +{{/-last}}{{/apis}}{{/apiInfo}} diff --git a/custom-templates/api_doc.mustache b/custom-templates/api_doc.mustache new file mode 100644 index 0000000..f8ea520 --- /dev/null +++ b/custom-templates/api_doc.mustache @@ -0,0 +1,47 @@ +# {{{invokerPackage}}}\{{{classname}}}{{#description}} + +{{{.}}}{{/description}} + +All URIs are relative to *{{{basePath}}}* + +Method | HTTP request | Description +------------- | ------------- | ------------- +{{#operations}}{{#operation}}[**{{{operationId}}}**]({{{classname}}}.md#{{{operationId}}}) | **{{{httpMethod}}}** {{{path}}} | {{{summary}}} +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} + +## {{{operationId}}} + +> {{#returnType}}{{{.}}} {{/returnType}}{{{operationId}}}({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}) +{{{summary}}}{{#notes}} + +{{{.}}}{{/notes}} + +### Parameters + +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} +{{#allParams}} +**{{{paramName}}}** | {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{{dataType}}}**]({{{baseType}}}.md){{/isPrimitiveType}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}} | {{{description}}} | {{#required}}[required]{{/required}} |{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} +{{/allParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{{returnBaseType}}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}} (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}](../README.md#{{{name}}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP request headers + +- **Content-Type**: {{#consumes}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} +- **Accept**: {{#produces}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/produces}}{{^produces}}Not defined{{/produces}} + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +{{/operation}} +{{/operations}} diff --git a/custom-templates/git_push.sh.mustache b/custom-templates/git_push.sh.mustache new file mode 100644 index 0000000..0e3776a --- /dev/null +++ b/custom-templates/git_push.sh.mustache @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="{{{gitHost}}}" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/custom-templates/gitignore.mustache b/custom-templates/gitignore.mustache new file mode 100644 index 0000000..6aa1064 --- /dev/null +++ b/custom-templates/gitignore.mustache @@ -0,0 +1,3 @@ +/target/ +**/*.rs.bk +Cargo.lock diff --git a/custom-templates/hyper/api.mustache b/custom-templates/hyper/api.mustache new file mode 100644 index 0000000..9c0f7fd --- /dev/null +++ b/custom-templates/hyper/api.mustache @@ -0,0 +1,182 @@ +{{>partial_header}} +use std::sync::Arc; +use std::borrow::Borrow; +use std::pin::Pin; +#[allow(unused_imports)] +use std::option::Option; + +use hyper; +use hyper_util::client::legacy::connect::Connect; +use futures::Future; + +use crate::models; +use super::{Error, configuration}; +use super::request as __internal_request; + +pub struct {{{classname}}}Client + where C: Clone + std::marker::Send + Sync + 'static { + configuration: Arc>, +} + +impl {{{classname}}}Client + where C: Clone + std::marker::Send + Sync { + pub fn new(configuration: Arc>) -> {{{classname}}}Client { + {{{classname}}}Client { + configuration, + } + } +} + +pub trait {{{classname}}}: Send + Sync { +{{#operations}} +{{#operation}} + fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isString}}{{^isUuid}}&str{{/isUuid}}{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> Pin> + Send>>; +{{/operation}} +{{/operations}} +} + +impl{{{classname}}} for {{{classname}}}Client + where C: Clone + std::marker::Send + Sync { + {{#operations}} + {{#operation}} + #[allow(unused_mut)] + fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isString}}{{^isUuid}}&str{{/isUuid}}{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> Pin> + Send>> { + let mut req = __internal_request::Request::new(hyper::Method::{{{httpMethod.toUpperCase}}}, "{{{path}}}".to_string()) + {{#hasAuthMethods}} + {{#authMethods}} + {{#isApiKey}} + .with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{ + in_header: {{#isKeyInHeader}}true{{/isKeyInHeader}}{{^isKeyInHeader}}false{{/isKeyInHeader}}, + in_query: {{#isKeyInQuery}}true{{/isKeyInQuery}}{{^isKeyInQuery}}false{{/isKeyInQuery}}, + param_name: "{{{keyParamName}}}".to_owned(), + })) + {{/isApiKey}} + {{#isBasicBasic}} + .with_auth(__internal_request::Auth::Basic) + {{/isBasicBasic}} + {{#isOAuth}} + .with_auth(__internal_request::Auth::Oauth) + {{/isOAuth}} + {{/authMethods}} + {{/hasAuthMethods}} + ; + {{#queryParams}} + {{#required}} + {{^isNullable}} + req = req.with_query_param("{{{baseName}}}".to_string(), {{{paramName}}}{{#isArray}}.join(","){{/isArray}}.to_string()); + {{/isNullable}} + {{#isNullable}} + match {{{paramName}}} { + Some(param_value) => { req = req.with_query_param("{{{baseName}}}".to_string(), param_value{{#isArray}}.join(","){{/isArray}}.to_string()); }, + None => { req = req.with_query_param("{{{baseName}}}".to_string(), "".to_string()); }, + } + {{/isNullable}} + {{/required}} + {{^required}} + if let Some(ref s) = {{{paramName}}} { + {{#isArray}} + let query_value = s.iter().map(|s| s.to_string()).collect::>().join(","); + {{/isArray}} + {{^isArray}} + let query_value = match serde_json::to_string(s) { + Ok(value) => value, + Err(e) => return Box::pin(futures::future::err(Error::Serde(e))), + }; + {{/isArray}} + req = req.with_query_param("{{{baseName}}}".to_string(), query_value); + } + {{/required}} + {{/queryParams}} + {{#pathParams}} + {{#required}} + {{^isNullable}} + req = req.with_path_param("{{{baseName}}}".to_string(), {{{paramName}}}{{#isArray}}.join(","){{/isArray}}.to_string()); + {{/isNullable}} + {{#isNullable}} + match {{{paramName}}} { + Some(param_value) => { req = req.with_path_param("{{{baseName}}}".to_string(), param_value{{#isArray}}.join(","){{/isArray}}.to_string()); }, + None => { req = req.with_path_param("{{{baseName}}}".to_string(), "".to_string()); }, + } + {{/isNullable}} + {{/required}} + {{^required}} + if let Some(param_value) = {{{paramName}}} { + req = req.with_path_param("{{{baseName}}}".to_string(), param_value{{#isArray}}.join(","){{/isArray}}.to_string()); + } + {{/required}} + {{/pathParams}} + {{#hasHeaderParams}} + {{#headerParams}} + {{#required}} + {{^isNullable}} + req = req.with_header_param("{{{baseName}}}".to_string(), {{{paramName}}}{{#isArray}}.join(","){{/isArray}}.to_string()); + {{/isNullable}} + {{#isNullable}} + match {{{paramName}}} { + Some(param_value) => { req = req.with_header_param("{{{baseName}}}".to_string(), param_value{{#isArray}}.join(","){{/isArray}}.to_string()); }, + None => { req = req.with_header_param("{{{baseName}}}".to_string(), "".to_string()); }, + } + {{/isNullable}} + {{/required}} + {{^required}} + if let Some(param_value) = {{{paramName}}} { + req = req.with_header_param("{{{baseName}}}".to_string(), param_value{{#isArray}}.join(","){{/isArray}}.to_string()); + } + {{/required}} + {{/headerParams}} + {{/hasHeaderParams}} + {{#hasFormParams}} + {{#formParams}} + {{#isFile}} + {{#required}} + {{^isNullable}} + req = req.with_form_param("{{{baseName}}}".to_string(), unimplemented!()); + {{/isNullable}} + {{#isNullable}} + match {{{paramName}}} { + Some(param_value) => { req = req.with_form_param("{{{baseName}}}".to_string(), unimplemented!()); }, + None => { req = req.with_form_param("{{{baseName}}}".to_string(), unimplemented!()); }, + } + {{/isNullable}} + {{/required}} + {{^required}} + if let Some(param_value) = {{{paramName}}} { + req = req.with_form_param("{{{baseName}}}".to_string(), unimplemented!()); + } + {{/required}} + {{/isFile}} + {{^isFile}} + {{#required}} + {{^isNullable}} + req = req.with_form_param("{{{baseName}}}".to_string(), {{{paramName}}}{{#isArray}}.join(","){{/isArray}}.to_string()); + {{/isNullable}} + {{#isNullable}} + match {{{paramName}}} { + Some(param_value) => { req = req.with_form_param("{{{baseName}}}".to_string(), param_value{{#isArray}}.join(","){{/isArray}}.to_string()); }, + None => { req = req.with_form_param("{{{baseName}}}".to_string(), "".to_string()); }, + } + {{/isNullable}} + {{/required}} + {{^required}} + if let Some(param_value) = {{{paramName}}} { + req = req.with_form_param("{{{baseName}}}".to_string(), param_value{{#isArray}}.join(","){{/isArray}}.to_string()); + } + {{/required}} + {{/isFile}} + {{/formParams}} + {{/hasFormParams}} + {{#hasBodyParam}} + {{#bodyParams}} + req = req.with_body_param({{{paramName}}}); + {{/bodyParams}} + {{/hasBodyParam}} + {{^returnType}} + req = req.returns_nothing(); + {{/returnType}} + + req.execute(self.configuration.borrow()) + } + +{{/operation}} +{{/operations}} +} diff --git a/custom-templates/hyper/api_mod.mustache b/custom-templates/hyper/api_mod.mustache new file mode 100644 index 0000000..67baa44 --- /dev/null +++ b/custom-templates/hyper/api_mod.mustache @@ -0,0 +1,83 @@ +use std::fmt; +use std::fmt::Debug; + +use hyper; +use hyper::http; +use hyper_util::client::legacy::connect::Connect; +use serde_json; + +#[derive(Debug)] +pub enum Error { + Api(ApiError), + Header(http::header::InvalidHeaderValue), + Http(http::Error), + Hyper(hyper::Error), + HyperClient(hyper_util::client::legacy::Error), + Serde(serde_json::Error), + UriError(http::uri::InvalidUri), +} + +pub struct ApiError { + pub code: hyper::StatusCode, + pub body: hyper::body::Incoming, +} + +impl Debug for ApiError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ApiError") + .field("code", &self.code) + .field("body", &"hyper::body::Incoming") + .finish() + } +} + +impl From<(hyper::StatusCode, hyper::body::Incoming)> for Error { + fn from(e: (hyper::StatusCode, hyper::body::Incoming)) -> Self { + Error::Api(ApiError { + code: e.0, + body: e.1, + }) + } +} + +impl From for Error { + fn from(e: http::Error) -> Self { + Error::Http(e) + } +} + +impl From for Error { + fn from(e: hyper_util::client::legacy::Error) -> Self { + Error::HyperClient(e) + } +} + +impl From for Error { + fn from(e: hyper::Error) -> Self { + Error::Hyper(e) + } +} + +impl From for Error { + fn from(e: serde_json::Error) -> Self { + Error::Serde(e) + } +} + +mod request; + +{{#apiInfo}} +{{#apis}} +mod {{{classFilename}}}; +{{#operations}} +{{#operation}} +{{#-last}} +pub use self::{{{classFilename}}}::{ {{{classname}}}, {{{classname}}}Client }; +{{/-last}} +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + +pub mod configuration; +pub mod client; diff --git a/custom-templates/hyper/client.mustache b/custom-templates/hyper/client.mustache new file mode 100644 index 0000000..d54e334 --- /dev/null +++ b/custom-templates/hyper/client.mustache @@ -0,0 +1,55 @@ +use std::sync::Arc; + +use hyper; +use hyper_util::client::legacy::connect::Connect; +use super::configuration::Configuration; + +pub struct APIClient { +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + {{#-last}} + {{{classFilename}}}: Box, + {{/-last}} +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} +} + +impl APIClient { + pub fn new(configuration: Configuration) -> APIClient + where C: Clone + std::marker::Send + Sync + 'static { + let rc = Arc::new(configuration); + + APIClient { +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + {{#-last}} + {{{classFilename}}}: Box::new(crate::apis::{{{classname}}}Client::new(rc.clone())), + {{/-last}} +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + } + } + +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} +{{#-last}} + pub fn {{{classFilename}}}(&self) -> &dyn crate::apis::{{{classname}}}{ + self.{{{classFilename}}}.as_ref() + } + +{{/-last}} +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} +} diff --git a/custom-templates/hyper/configuration.mustache b/custom-templates/hyper/configuration.mustache new file mode 100644 index 0000000..43a48ff --- /dev/null +++ b/custom-templates/hyper/configuration.mustache @@ -0,0 +1,83 @@ +{{>partial_header}} +use hyper; +use hyper_util::client::legacy::Client; +use hyper_util::client::legacy::connect::Connect; +use hyper_util::client::legacy::connect::HttpConnector; +use hyper_util::rt::TokioExecutor; + +pub struct Configuration + where C: Clone + std::marker::Send + Sync + 'static { + pub base_path: String, + pub user_agent: Option, + pub client: Client, + pub basic_auth: Option, + pub oauth_access_token: Option, + pub api_key: Option, + // TODO: take an oauth2 token source, similar to the go one +} + +pub type BasicAuth = (String, Option); + +pub struct ApiKey { + pub prefix: Option, + pub key: String, +} + +impl Configuration { + /// Construct a default [`Configuration`](Self) with a hyper client using a default + /// [`HttpConnector`](hyper_util::client::legacy::connect::HttpConnector). + /// + /// Use [`with_client`](Configuration::with_client) to construct a Configuration with a + /// custom hyper client. + /// + /// # Example + /// + /// ``` + /// # use {{externCrateName}}::apis::configuration::Configuration; + /// let api_config = Configuration { + /// basic_auth: Some(("user".into(), None)), + /// ..Configuration::new() + /// }; + /// ``` + pub fn new() -> Configuration { + Configuration::default() + } +} + +impl Configuration + where C: Clone + std::marker::Send + Sync { + + /// Construct a new Configuration with a custom hyper client. + /// + /// # Example + /// + /// ``` + /// # use core::time::Duration; + /// # use {{externCrateName}}::apis::configuration::Configuration; + /// use hyper_util::client::legacy::Client; + /// use hyper_util::rt::TokioExecutor; + /// + /// let client = Client::builder(TokioExecutor::new()) + /// .pool_idle_timeout(Duration::from_secs(30)) + /// .build_http(); + /// + /// let api_config = Configuration::with_client(client); + /// ``` + pub fn with_client(client: Client) -> Configuration { + Configuration { + base_path: "{{{basePath}}}".to_owned(), + user_agent: {{#httpUserAgent}}Some("{{{.}}}".to_owned()){{/httpUserAgent}}{{^httpUserAgent}}Some("OpenAPI-Generator/{{{version}}}/rust".to_owned()){{/httpUserAgent}}, + client, + basic_auth: None, + oauth_access_token: None, + api_key: None, + } + } +} + +impl Default for Configuration { + fn default() -> Self { + let client = Client::builder(TokioExecutor::new()).build_http(); + Configuration::with_client(client) + } +} diff --git a/custom-templates/hyper0x/api.mustache b/custom-templates/hyper0x/api.mustache new file mode 100644 index 0000000..fe1a65c --- /dev/null +++ b/custom-templates/hyper0x/api.mustache @@ -0,0 +1,181 @@ +{{>partial_header}} +use std::rc::Rc; +use std::borrow::Borrow; +use std::pin::Pin; +#[allow(unused_imports)] +use std::option::Option; + +use hyper; +use futures::Future; + +use crate::models; +use super::{Error, configuration}; +use super::request as __internal_request; + +pub struct {{{classname}}}Client + where C: Clone + std::marker::Send + Sync + 'static { + configuration: Rc>, +} + +impl {{{classname}}}Client + where C: Clone + std::marker::Send + Sync { + pub fn new(configuration: Rc>) -> {{{classname}}}Client { + {{{classname}}}Client { + configuration, + } + } +} + +pub trait {{{classname}}} { +{{#operations}} +{{#operation}} + fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isString}}{{^isUuid}}&str{{/isUuid}}{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> Pin>>>; +{{/operation}} +{{/operations}} +} + +impl{{{classname}}} for {{{classname}}}Client + where C: Clone + std::marker::Send + Sync { + {{#operations}} + {{#operation}} + #[allow(unused_mut)] + fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isString}}{{^isUuid}}&str{{/isUuid}}{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> Pin>>> { + let mut req = __internal_request::Request::new(hyper::Method::{{{httpMethod.toUpperCase}}}, "{{{path}}}".to_string()) + {{#hasAuthMethods}} + {{#authMethods}} + {{#isApiKey}} + .with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{ + in_header: {{#isKeyInHeader}}true{{/isKeyInHeader}}{{^isKeyInHeader}}false{{/isKeyInHeader}}, + in_query: {{#isKeyInQuery}}true{{/isKeyInQuery}}{{^isKeyInQuery}}false{{/isKeyInQuery}}, + param_name: "{{{keyParamName}}}".to_owned(), + })) + {{/isApiKey}} + {{#isBasicBasic}} + .with_auth(__internal_request::Auth::Basic) + {{/isBasicBasic}} + {{#isOAuth}} + .with_auth(__internal_request::Auth::Oauth) + {{/isOAuth}} + {{/authMethods}} + {{/hasAuthMethods}} + ; + {{#queryParams}} + {{#required}} + {{^isNullable}} + req = req.with_query_param("{{{baseName}}}".to_string(), {{{paramName}}}{{#isArray}}.join(","){{/isArray}}.to_string()); + {{/isNullable}} + {{#isNullable}} + match {{{paramName}}} { + Some(param_value) => { req = req.with_query_param("{{{baseName}}}".to_string(), param_value{{#isArray}}.join(","){{/isArray}}.to_string()); }, + None => { req = req.with_query_param("{{{baseName}}}".to_string(), "".to_string()); }, + } + {{/isNullable}} + {{/required}} + {{^required}} + if let Some(ref s) = {{{paramName}}} { + {{#isArray}} + let query_value = s.iter().map(|s| s.to_string()).collect::>().join(","); + {{/isArray}} + {{^isArray}} + let query_value = match serde_json::to_string(s) { + Ok(value) => value, + Err(e) => return Box::pin(futures::future::err(Error::Serde(e))), + }; + {{/isArray}} + req = req.with_query_param("{{{baseName}}}".to_string(), query_value); + } + {{/required}} + {{/queryParams}} + {{#pathParams}} + {{#required}} + {{^isNullable}} + req = req.with_path_param("{{{baseName}}}".to_string(), {{{paramName}}}{{#isArray}}.join(","){{/isArray}}.to_string()); + {{/isNullable}} + {{#isNullable}} + match {{{paramName}}} { + Some(param_value) => { req = req.with_path_param("{{{baseName}}}".to_string(), param_value{{#isArray}}.join(","){{/isArray}}.to_string()); }, + None => { req = req.with_path_param("{{{baseName}}}".to_string(), "".to_string()); }, + } + {{/isNullable}} + {{/required}} + {{^required}} + if let Some(param_value) = {{{paramName}}} { + req = req.with_path_param("{{{baseName}}}".to_string(), param_value{{#isArray}}.join(","){{/isArray}}.to_string()); + } + {{/required}} + {{/pathParams}} + {{#hasHeaderParams}} + {{#headerParams}} + {{#required}} + {{^isNullable}} + req = req.with_header_param("{{{baseName}}}".to_string(), {{{paramName}}}{{#isArray}}.join(","){{/isArray}}.to_string()); + {{/isNullable}} + {{#isNullable}} + match {{{paramName}}} { + Some(param_value) => { req = req.with_header_param("{{{baseName}}}".to_string(), param_value{{#isArray}}.join(","){{/isArray}}.to_string()); }, + None => { req = req.with_header_param("{{{baseName}}}".to_string(), "".to_string()); }, + } + {{/isNullable}} + {{/required}} + {{^required}} + if let Some(param_value) = {{{paramName}}} { + req = req.with_header_param("{{{baseName}}}".to_string(), param_value{{#isArray}}.join(","){{/isArray}}.to_string()); + } + {{/required}} + {{/headerParams}} + {{/hasHeaderParams}} + {{#hasFormParams}} + {{#formParams}} + {{#isFile}} + {{#required}} + {{^isNullable}} + req = req.with_form_param("{{{baseName}}}".to_string(), unimplemented!()); + {{/isNullable}} + {{#isNullable}} + match {{{paramName}}} { + Some(param_value) => { req = req.with_form_param("{{{baseName}}}".to_string(), unimplemented!()); }, + None => { req = req.with_form_param("{{{baseName}}}".to_string(), unimplemented!()); }, + } + {{/isNullable}} + {{/required}} + {{^required}} + if let Some(param_value) = {{{paramName}}} { + req = req.with_form_param("{{{baseName}}}".to_string(), unimplemented!()); + } + {{/required}} + {{/isFile}} + {{^isFile}} + {{#required}} + {{^isNullable}} + req = req.with_form_param("{{{baseName}}}".to_string(), {{{paramName}}}{{#isArray}}.join(","){{/isArray}}.to_string()); + {{/isNullable}} + {{#isNullable}} + match {{{paramName}}} { + Some(param_value) => { req = req.with_form_param("{{{baseName}}}".to_string(), param_value{{#isArray}}.join(","){{/isArray}}.to_string()); }, + None => { req = req.with_form_param("{{{baseName}}}".to_string(), "".to_string()); }, + } + {{/isNullable}} + {{/required}} + {{^required}} + if let Some(param_value) = {{{paramName}}} { + req = req.with_form_param("{{{baseName}}}".to_string(), param_value{{#isArray}}.join(","){{/isArray}}.to_string()); + } + {{/required}} + {{/isFile}} + {{/formParams}} + {{/hasFormParams}} + {{#hasBodyParam}} + {{#bodyParams}} + req = req.with_body_param({{{paramName}}}); + {{/bodyParams}} + {{/hasBodyParam}} + {{^returnType}} + req = req.returns_nothing(); + {{/returnType}} + + req.execute(self.configuration.borrow()) + } + +{{/operation}} +{{/operations}} +} diff --git a/custom-templates/hyper0x/api_mod.mustache b/custom-templates/hyper0x/api_mod.mustache new file mode 100644 index 0000000..51a42ef --- /dev/null +++ b/custom-templates/hyper0x/api_mod.mustache @@ -0,0 +1,64 @@ +use http; +use hyper; +use serde_json; + +#[derive(Debug)] +pub enum Error { + Api(ApiError), + Header(hyper::http::header::InvalidHeaderValue), + Http(http::Error), + Hyper(hyper::Error), + Serde(serde_json::Error), + UriError(http::uri::InvalidUri), +} + +#[derive(Debug)] +pub struct ApiError { + pub code: hyper::StatusCode, + pub body: hyper::body::Body, +} + +impl From<(hyper::StatusCode, hyper::body::Body)> for Error { + fn from(e: (hyper::StatusCode, hyper::body::Body)) -> Self { + Error::Api(ApiError { + code: e.0, + body: e.1, + }) + } +} + +impl From for Error { + fn from(e: http::Error) -> Self { + Error::Http(e) + } +} + +impl From for Error { + fn from(e: hyper::Error) -> Self { + Error::Hyper(e) + } +} + +impl From for Error { + fn from(e: serde_json::Error) -> Self { + Error::Serde(e) + } +} + +mod request; + +{{#apiInfo}} +{{#apis}} +mod {{{classFilename}}}; +{{#operations}} +{{#operation}} +{{#-last}} +pub use self::{{{classFilename}}}::{ {{{classname}}}, {{{classname}}}Client }; +{{/-last}} +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + +pub mod configuration; +pub mod client; diff --git a/custom-templates/hyper0x/client.mustache b/custom-templates/hyper0x/client.mustache new file mode 100644 index 0000000..25124d9 --- /dev/null +++ b/custom-templates/hyper0x/client.mustache @@ -0,0 +1,54 @@ +use std::rc::Rc; + +use hyper; +use super::configuration::Configuration; + +pub struct APIClient { +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + {{#-last}} + {{{classFilename}}}: Box, + {{/-last}} +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} +} + +impl APIClient { + pub fn new(configuration: Configuration) -> APIClient + where C: Clone + std::marker::Send + Sync + 'static { + let rc = Rc::new(configuration); + + APIClient { +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + {{#-last}} + {{{classFilename}}}: Box::new(crate::apis::{{{classname}}}Client::new(rc.clone())), + {{/-last}} +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + } + } + +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} +{{#-last}} + pub fn {{{classFilename}}}(&self) -> &dyn crate::apis::{{{classname}}}{ + self.{{{classFilename}}}.as_ref() + } + +{{/-last}} +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} +} diff --git a/custom-templates/hyper0x/configuration.mustache b/custom-templates/hyper0x/configuration.mustache new file mode 100644 index 0000000..ee6f407 --- /dev/null +++ b/custom-templates/hyper0x/configuration.mustache @@ -0,0 +1,34 @@ +{{>partial_header}} +use hyper; + +pub struct Configuration + where C: Clone + std::marker::Send + Sync + 'static { + pub base_path: String, + pub user_agent: Option, + pub client: hyper::client::Client, + pub basic_auth: Option, + pub oauth_access_token: Option, + pub api_key: Option, + // TODO: take an oauth2 token source, similar to the go one +} + +pub type BasicAuth = (String, Option); + +pub struct ApiKey { + pub prefix: Option, + pub key: String, +} + +impl Configuration + where C: Clone + std::marker::Send + Sync { + pub fn new(client: hyper::client::Client) -> Configuration { + Configuration { + base_path: "{{{basePath}}}".to_owned(), + user_agent: {{#httpUserAgent}}Some("{{{.}}}".to_owned()){{/httpUserAgent}}{{^httpUserAgent}}Some("OpenAPI-Generator/{{{version}}}/rust".to_owned()){{/httpUserAgent}}, + client, + basic_auth: None, + oauth_access_token: None, + api_key: None, + } + } +} diff --git a/custom-templates/lib.mustache b/custom-templates/lib.mustache new file mode 100644 index 0000000..b51df2b --- /dev/null +++ b/custom-templates/lib.mustache @@ -0,0 +1,17 @@ +#![allow(unused_imports)] +#![allow(clippy::too_many_arguments)] + +extern crate serde_repr; +extern crate serde; +extern crate serde_json; +extern crate url; +{{#hyper}} +extern crate hyper; +extern crate futures; +{{/hyper}} +{{#reqwest}} +extern crate reqwest; +{{/reqwest}} + +pub mod apis; +pub mod models; diff --git a/custom-templates/model.mustache b/custom-templates/model.mustache new file mode 100644 index 0000000..a4970ab --- /dev/null +++ b/custom-templates/model.mustache @@ -0,0 +1,225 @@ +{{>partial_header}} +use crate::models; +use serde::{Deserialize, Serialize}; +{{#models}} +{{#model}} +{{^isEnum}}{{#vendorExtensions.x-rust-has-byte-array}} +use serde_with::serde_as; +{{/vendorExtensions.x-rust-has-byte-array}}{{/isEnum}} +{{#isEnum}} +{{#isInteger}} +use serde_repr::{Serialize_repr,Deserialize_repr}; +{{/isInteger}} +{{/isEnum}} +{{#description}} +/// {{{classname}}} : {{{description}}} +{{/description}} +{{!-- for repr(int) enum schemas --}} +{{#isEnum}} +{{#isInteger}} +/// {{{description}}} +#[repr(i64)] +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize_repr, Deserialize_repr)] +pub enum {{{classname}}} { +{{#allowableValues}} +{{#enumVars}} + {{{name}}} = {{{value}}}, +{{/enumVars}}{{/allowableValues}} +} + +impl std::fmt::Display for {{{classname}}} { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", match self { + {{#allowableValues}} + {{#enumVars}} + Self::{{{name}}} => "{{{value}}}", + {{/enumVars}} + {{/allowableValues}} + }) + } +} +{{/isInteger}} +{{/isEnum}} +{{!-- for enum schemas --}} +{{#isEnum}} +{{^isInteger}} +/// {{{description}}} +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum {{{classname}}} { +{{#allowableValues}} +{{#enumVars}} + #[serde(rename = "{{{value}}}")] + {{{name}}}, +{{/enumVars}}{{/allowableValues}} +} + +impl std::fmt::Display for {{{classname}}} { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + {{#allowableValues}} + {{#enumVars}} + Self::{{{name}}} => write!(f, "{{{value}}}"), + {{/enumVars}} + {{/allowableValues}} + } + } +} + +{{/isInteger}} +impl Default for {{{classname}}} { + fn default() -> {{{classname}}} { + {{#allowableValues}} + Self::{{ enumVars.0.name }} + {{/allowableValues}} + } +} +{{/isEnum}} +{{!-- for schemas that have a discriminator --}} +{{#discriminator}} +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "{{{propertyBaseName}}}")] +pub enum {{{classname}}} { + {{^oneOf}} + {{#mappedModels}} + #[serde(rename="{{mappingName}}")] + {{{modelName}}} { + {{#vars}} + {{#description}} + /// {{{.}}} + {{/description}} + #[serde(rename = "{{{baseName}}}"{{^required}}, skip_serializing_if = "Option::is_none"{{/required}})] + {{{name}}}: {{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{^required}}Option<{{/required}}{{#isEnum}}{{{enumName}}}{{/isEnum}}{{^isEnum}}{{#isModel}}{{^avoidBoxedModels}}Box<{{/avoidBoxedModels}}{{{dataType}}}{{^avoidBoxedModels}}>{{/avoidBoxedModels}}{{/isModel}}{{^isModel}}{{{dataType}}}{{/isModel}}{{/isEnum}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{^required}}>{{/required}}, + {{/vars}} + }, + {{/mappedModels}} + {{/oneOf}} + {{^oneOf.isEmpty}} + {{#composedSchemas.oneOf}} + {{#description}} + /// {{{.}}} + {{/description}} + {{#baseName}} + #[serde(rename="{{{.}}}")] + {{/baseName}} + {{{name}}}({{#isModel}}{{^avoidBoxedModels}}Box<{{/avoidBoxedModels}}{{/isModel}}{{{dataType}}}{{#isModel}}{{^avoidBoxedModels}}>{{/avoidBoxedModels}}{{/isModel}}), + {{/composedSchemas.oneOf}} + {{/oneOf.isEmpty}} +} + +impl Default for {{classname}} { + fn default() -> Self { + {{^oneOf}}{{#mappedModels}}{{#-first}}Self::{{modelName}} { + {{#vars}} + {{{name}}}: Default::default(), + {{/vars}} + }{{/-first}}{{/mappedModels}} + {{/oneOf}}{{^oneOf.isEmpty}}{{#composedSchemas.oneOf}}{{#-first}}Self::{{{name}}}(Default::default()){{/-first}}{{/composedSchemas.oneOf}}{{/oneOf.isEmpty}} + } +} + +{{/discriminator}} +{{!-- for non-enum schemas --}} +{{^isEnum}} +{{^discriminator}} +{{#vendorExtensions.x-rust-has-byte-array}}#[serde_as] +{{/vendorExtensions.x-rust-has-byte-array}}{{#oneOf.isEmpty}}#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct {{{classname}}} { +{{#vars}} + {{#description}} + /// {{{.}}} + {{/description}} + {{#isByteArray}} + {{#vendorExtensions.isMandatory}}#[serde_as(as = "serde_with::base64::Base64")]{{/vendorExtensions.isMandatory}}{{^vendorExtensions.isMandatory}}#[serde_as(as = "{{^serdeAsDoubleOption}}Option{{/serdeAsDoubleOption}}{{#serdeAsDoubleOption}}super::DoubleOption{{/serdeAsDoubleOption}}")]{{/vendorExtensions.isMandatory}} + {{/isByteArray}} + #[serde(rename = "{{{baseName}}}"{{^required}}{{#isNullable}}, default{{^isByteArray}}, with = "::serde_with::rust::double_option"{{/isByteArray}}{{/isNullable}}{{/required}}{{^required}}, skip_serializing_if = "Option::is_none"{{/required}}{{#required}}{{#isNullable}}, deserialize_with = "Option::deserialize"{{/isNullable}}{{/required}})] + pub {{{name}}}: {{! + ### Option Start + }}{{#isNullable}}Option<{{/isNullable}}{{^required}}Option<{{/required}}{{! + ### Enums + }}{{#isEnum}}{{#isArray}}{{#uniqueItems}}std::collections::HashSet<{{/uniqueItems}}{{^uniqueItems}}Vec<{{/uniqueItems}}{{/isArray}}{{{enumName}}}{{#isArray}}>{{/isArray}}{{/isEnum}}{{! + ### Non-Enums Start + }}{{^isEnum}}{{! + ### Models + }}{{#isModel}}{{^avoidBoxedModels}}Box<{{/avoidBoxedModels}}{{{dataType}}}{{^avoidBoxedModels}}>{{/avoidBoxedModels}}{{/isModel}}{{! + ### Primative datatypes + }}{{^isModel}}{{#isByteArray}}Vec{{/isByteArray}}{{^isByteArray}}{{{dataType}}}{{/isByteArray}}{{/isModel}}{{! + ### Non-Enums End + }}{{/isEnum}}{{! + ### Option End (and trailing comma) + }}{{#isNullable}}>{{/isNullable}}{{^required}}>{{/required}}, +{{/vars}} +} + +impl {{{classname}}} { + {{#description}} + /// {{{.}}} + {{/description}} + pub fn new({{#requiredVars}}{{{name}}}: {{! + ### Option Start + }}{{#isNullable}}Option<{{/isNullable}}{{! + ### Enums + }}{{#isEnum}}{{#isArray}}{{#uniqueItems}}std::collections::HashSet<{{/uniqueItems}}{{^uniqueItems}}Vec<{{/uniqueItems}}{{/isArray}}{{{enumName}}}{{#isArray}}>{{/isArray}}{{/isEnum}}{{! + ### Non-Enums + }}{{^isEnum}}{{#isByteArray}}Vec{{/isByteArray}}{{^isByteArray}}{{{dataType}}}{{/isByteArray}}{{/isEnum}}{{! + ### Option End + }}{{#isNullable}}>{{/isNullable}}{{! + ### Comma for next arguement + }}{{^-last}}, {{/-last}}{{/requiredVars}}) -> {{{classname}}} { + {{{classname}}} { + {{#vars}} + {{{name}}}{{^required}}: None{{/required}}{{#required}}{{#isModel}}{{^avoidBoxedModels}}: {{^isNullable}}Box::new({{{name}}}){{/isNullable}}{{#isNullable}}if let Some(x) = {{{name}}} {Some(Box::new(x))} else {None}{{/isNullable}}{{/avoidBoxedModels}}{{/isModel}}{{/required}}, + {{/vars}} + } + } +} +{{/oneOf.isEmpty}} +{{^oneOf.isEmpty}} +{{! TODO: add other vars that are not part of the oneOf}} +{{#description}} +/// {{{.}}} +{{/description}} +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum {{classname}} { +{{#composedSchemas.oneOf}} + {{#description}} + /// {{{.}}} + {{/description}} + {{{name}}}({{#isModel}}{{^avoidBoxedModels}}Box<{{/avoidBoxedModels}}{{/isModel}}{{{dataType}}}{{#isModel}}{{^avoidBoxedModels}}>{{/avoidBoxedModels}}{{/isModel}}), +{{/composedSchemas.oneOf}} +} + +impl Default for {{classname}} { + fn default() -> Self { + {{#composedSchemas.oneOf}}{{#-first}}Self::{{{name}}}(Default::default()){{/-first}}{{/composedSchemas.oneOf}} + } +} +{{/oneOf.isEmpty}} +{{/discriminator}} +{{/isEnum}} +{{!-- for properties that are of enum type --}} +{{#vars}} +{{#isEnum}} +/// {{{description}}} +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum {{{enumName}}} { +{{#allowableValues}} +{{#enumVars}} + #[serde(rename = "{{{value}}}")] + {{{name}}}, +{{/enumVars}} +{{/allowableValues}} +} + +impl Default for {{{enumName}}} { + fn default() -> {{{enumName}}} { + {{#allowableValues}} + Self::{{ enumVars.0.name }} + {{/allowableValues}} + } +} +{{/isEnum}} +{{/vars}} + +{{/model}} +{{/models}} diff --git a/custom-templates/model_doc.mustache b/custom-templates/model_doc.mustache new file mode 100644 index 0000000..2aba759 --- /dev/null +++ b/custom-templates/model_doc.mustache @@ -0,0 +1,54 @@ +{{#models}}{{#model}}# {{{classname}}} +{{#isEnum}} + +## Enum Variants + +| Name | Value | +|---- | -----|{{#allowableValues}}{{#enumVars}} +| {{name}} | {{value}} |{{/enumVars}}{{/allowableValues}} + +{{/isEnum}} +{{#discriminator}} + +## Enum Variants + +| Name | Value | +|---- | -----|{{#vendorExtensions}}{{#x-mapped-models}} +| {{modelName}} | {{mappingName}} |{{/x-mapped-models}}{{/vendorExtensions}} +{{#vendorExtensions}} +{{#x-mapped-models}} + +## {{modelName}} + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +{{#vars}}**{{{name}}}** | {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{{dataType}}}**]({{{complexType}}}.md){{/isPrimitiveType}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}} | {{{description}}} | {{^required}}[optional]{{/required}}{{#isReadOnly}}[readonly]{{/isReadOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} +{{/vars}} +{{/x-mapped-models}} +{{/vendorExtensions}} +{{/discriminator}} +{{^discriminator}} +{{^isEnum}} +{{#oneOf.isEmpty}} + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +{{#vars}}**{{{name}}}** | {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{{dataType}}}**]({{{complexType}}}.md){{/isPrimitiveType}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}} | {{{description}}} | {{^required}}[optional]{{/required}}{{#isReadOnly}}[readonly]{{/isReadOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} +{{/vars}} +{{/oneOf.isEmpty}} +{{^oneOf.isEmpty}} + +## Enum Variants + +| Name | Description | +|---- | -----|{{#oneOf}} +| {{{.}}} | {{description}} |{{/oneOf}} +{{/oneOf.isEmpty}} +{{/isEnum}} +{{/discriminator}} + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + +{{/model}}{{/models}} diff --git a/custom-templates/model_mod.mustache b/custom-templates/model_mod.mustache new file mode 100644 index 0000000..bdb080f --- /dev/null +++ b/custom-templates/model_mod.mustache @@ -0,0 +1,45 @@ +{{#models}} +{{#model}} +pub mod {{{classFilename}}}; +pub use self::{{{classFilename}}}::{{{classname}}}; +{{/model}} +{{/models}} +{{#serdeAsDoubleOption}} +use serde::{Deserialize, Deserializer, Serializer}; +use serde_with::{de::DeserializeAsWrap, ser::SerializeAsWrap, DeserializeAs, SerializeAs}; +use std::marker::PhantomData; + +pub(crate) struct DoubleOption(PhantomData); + +impl SerializeAs>> for DoubleOption +where + TAs: SerializeAs, +{ + fn serialize_as(values: &Option>, serializer: S) -> Result + where + S: Serializer, + { + match values { + None => serializer.serialize_unit(), + Some(None) => serializer.serialize_none(), + Some(Some(v)) => serializer.serialize_some(&SerializeAsWrap::::new(v)), + } + } +} + +impl<'de, T, TAs> DeserializeAs<'de, Option>> for DoubleOption +where + TAs: DeserializeAs<'de, T>, + T: std::fmt::Debug, +{ + fn deserialize_as(deserializer: D) -> Result>, D::Error> + where + D: Deserializer<'de>, + { + Ok(Some( + DeserializeAsWrap::, Option>::deserialize(deserializer)? + .into_inner(), + )) + } +} +{{/serdeAsDoubleOption}} \ No newline at end of file diff --git a/custom-templates/partial_header.mustache b/custom-templates/partial_header.mustache new file mode 100644 index 0000000..408d841 --- /dev/null +++ b/custom-templates/partial_header.mustache @@ -0,0 +1,13 @@ +/* + {{#appName}} + * {{{.}}} + * + {{/appName}} + {{#appDescription}} + * {{{.}}} + * + {{/appDescription}} + * {{#version}}The version of the OpenAPI document: {{{.}}}{{/version}} + * {{#infoEmail}}Contact: {{{.}}}{{/infoEmail}} + * Generated by: https://openapi-generator.tech + */ diff --git a/custom-templates/request.rs b/custom-templates/request.rs new file mode 100644 index 0000000..a6f7b74 --- /dev/null +++ b/custom-templates/request.rs @@ -0,0 +1,247 @@ +use std::collections::HashMap; +use std::pin::Pin; + +use futures; +use futures::Future; +use futures::future::*; +use http_body_util::BodyExt; +use hyper; +use hyper_util::client::legacy::connect::Connect; +use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, HeaderValue, USER_AGENT}; +use serde; +use serde_json; + +use super::{configuration, Error}; + +pub(crate) struct ApiKey { + pub in_header: bool, + pub in_query: bool, + pub param_name: String, +} + +impl ApiKey { + fn key(&self, prefix: &Option, key: &str) -> String { + match prefix { + None => key.to_owned(), + Some(ref prefix) => format!("{} {}", prefix, key), + } + } +} + +#[allow(dead_code)] +pub(crate) enum Auth { + None, + ApiKey(ApiKey), + Basic, + Oauth, +} + +/// If the authorization type is unspecified then it will be automatically detected based +/// on the configuration. This functionality is useful when the OpenAPI definition does not +/// include an authorization scheme. +pub(crate) struct Request { + auth: Option, + method: hyper::Method, + path: String, + query_params: HashMap, + no_return_type: bool, + path_params: HashMap, + form_params: HashMap, + header_params: HashMap, + // TODO: multiple body params are possible technically, but not supported here. + serialized_body: Option, +} + +#[allow(dead_code)] +impl Request { + pub fn new(method: hyper::Method, path: String) -> Self { + Request { + auth: None, + method, + path, + query_params: HashMap::new(), + path_params: HashMap::new(), + form_params: HashMap::new(), + header_params: HashMap::new(), + serialized_body: None, + no_return_type: false, + } + } + + pub fn with_body_param(mut self, param: T) -> Self { + self.serialized_body = Some(serde_json::to_string(¶m).unwrap()); + self + } + + pub fn with_header_param(mut self, basename: String, param: String) -> Self { + self.header_params.insert(basename, param); + self + } + + #[allow(unused)] + pub fn with_query_param(mut self, basename: String, param: String) -> Self { + self.query_params.insert(basename, param); + self + } + + #[allow(unused)] + pub fn with_path_param(mut self, basename: String, param: String) -> Self { + self.path_params.insert(basename, param); + self + } + + #[allow(unused)] + pub fn with_form_param(mut self, basename: String, param: String) -> Self { + self.form_params.insert(basename, param); + self + } + + pub fn returns_nothing(mut self) -> Self { + self.no_return_type = true; + self + } + + pub fn with_auth(mut self, auth: Auth) -> Self { + self.auth = Some(auth); + self + } + + pub fn execute<'a, C, U>( + self, + conf: &configuration::Configuration, + ) -> Pin> + 'a + Send>> + where + C: Connect + Clone + std::marker::Send + Sync, + U: Sized + std::marker::Send + 'a, + for<'de> U: serde::Deserialize<'de>, + { + let mut query_string = ::url::form_urlencoded::Serializer::new("".to_owned()); + + let mut path = self.path; + for (k, v) in self.path_params { + // replace {id} with the value of the id path param + path = path.replace(&format!("{{{}}}", k), &v); + } + + for (key, val) in self.query_params { + query_string.append_pair(&key, &val); + } + + let mut uri_str = format!("{}{}", conf.base_path, path); + + let query_string_str = query_string.finish(); + if !query_string_str.is_empty() { + uri_str += "?"; + uri_str += &query_string_str; + } + let uri: hyper::Uri = match uri_str.parse() { + Err(e) => return Box::pin(futures::future::err(Error::UriError(e))), + Ok(u) => u, + }; + + let mut req_builder = hyper::Request::builder() + .uri(uri) + .method(self.method); + + // Detect the authorization type if it hasn't been set. + let auth = self.auth.unwrap_or_else(|| + if conf.api_key.is_some() { + panic!("Cannot automatically set the API key from the configuration, it must be specified in the OpenAPI definition") + } else if conf.oauth_access_token.is_some() { + Auth::Oauth + } else if conf.basic_auth.is_some() { + Auth::Basic + } else { + Auth::None + } + ); + match auth { + Auth::ApiKey(apikey) => { + if let Some(ref key) = conf.api_key { + let val = apikey.key(&key.prefix, &key.key); + if apikey.in_query { + query_string.append_pair(&apikey.param_name, &val); + } + if apikey.in_header { + req_builder = req_builder.header(&apikey.param_name, val); + } + } + } + Auth::Basic => { + if let Some(ref auth_conf) = conf.basic_auth { + let mut text = auth_conf.0.clone(); + text.push(':'); + if let Some(ref pass) = auth_conf.1 { + text.push_str(&pass[..]); + } + let encoded = base64::encode(&text); + req_builder = req_builder.header(AUTHORIZATION, encoded); + } + } + Auth::Oauth => { + if let Some(ref token) = conf.oauth_access_token { + let text = "Bearer ".to_owned() + token; + req_builder = req_builder.header(AUTHORIZATION, text); + } + } + Auth::None => {} + } + + if let Some(ref user_agent) = conf.user_agent { + req_builder = req_builder.header(USER_AGENT, match HeaderValue::from_str(user_agent) { + Ok(header_value) => header_value, + Err(e) => return Box::pin(futures::future::err(super::Error::Header(e))) + }); + } + + for (k, v) in self.header_params { + req_builder = req_builder.header(&k, v); + } + + let req_headers = req_builder.headers_mut().unwrap(); + let request_result = if self.form_params.len() > 0 { + req_headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/x-www-form-urlencoded")); + let mut enc = ::url::form_urlencoded::Serializer::new("".to_owned()); + for (k, v) in self.form_params { + enc.append_pair(&k, &v); + } + req_builder.body(enc.finish()) + } else if let Some(body) = self.serialized_body { + req_headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); + req_headers.insert(CONTENT_LENGTH, body.len().into()); + req_builder.body(body) + } else { + req_builder.body(String::new()) + }; + let request = match request_result { + Ok(request) => request, + Err(e) => return Box::pin(futures::future::err(Error::from(e))) + }; + + let no_return_type = self.no_return_type; + Box::pin(conf.client + .request(request) + .map_err(|e| Error::from(e)) + .and_then(move |response| { + let status = response.status(); + if !status.is_success() { + futures::future::err::(Error::from((status, response.into_body()))).boxed() + } else if no_return_type { + // This is a hack; if there's no_ret_type, U is (), but serde_json gives an + // error when deserializing "" into (), so deserialize 'null' into it + // instead. + // An alternate option would be to require U: Default, and then return + // U::default() here instead since () implements that, but then we'd + // need to impl default for all models. + futures::future::ok::(serde_json::from_str("null").expect("serde null value")).boxed() + } else { + let collect = response.into_body().collect().map_err(Error::from); + collect.map(|collected| { + collected.and_then(|collected| { + serde_json::from_slice(&collected.to_bytes()).map_err(Error::from) + }) + }).boxed() + } + })) + } +} diff --git a/custom-templates/reqwest-trait/api.mustache b/custom-templates/reqwest-trait/api.mustache new file mode 100644 index 0000000..ae7ea7d --- /dev/null +++ b/custom-templates/reqwest-trait/api.mustache @@ -0,0 +1,558 @@ +{{>partial_header}} + +use async_trait::async_trait; +{{#mockall}} +#[cfg(feature = "mockall")] +use mockall::automock; +{{/mockall}} +use reqwest; +use std::sync::Arc; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration}; +use crate::apis::ContentType; + +{{#mockall}} +#[cfg_attr(feature = "mockall", automock)] +{{/mockall}} +#[async_trait] +pub trait {{{classname}}}: Send + Sync { +{{#operations}} +{{#operation}} + + /// {{{httpMethod}}} {{{path}}} + {{^notes.empty}} + /// + /// {{{notes}}} + {{/notes.empty}} +{{#vendorExtensions.x-group-parameters}} + async fn {{{operationId}}}(&self, {{#allParams}}{{#-first}} params: {{{operationIdCamelCase}}}Params {{/-first}}{{/allParams}}{{! + ### Function return type + }}) -> Result<{{! + ### Multi response support + }}{{#supportMultipleResponses}}ResponseContent<{{{operationIdCamelCase}}}Success>{{/supportMultipleResponses}}{{! + ### Regular return type + }}{{^supportMultipleResponses}}{{^returnType}}(){{/returnType}}{{{returnType}}}{{/supportMultipleResponses}}{{! + ### Error Type + }}, Error<{{{operationIdCamelCase}}}Error>>; +{{/vendorExtensions.x-group-parameters}} +{{^vendorExtensions.x-group-parameters}} + async fn {{{operationId}}}{{! + ### Lifetimes + }}<{{#allParams}}'{{#lambda.lifetimeName}}{{{paramName}}}{{/lambda.lifetimeName}}{{^-last}}, {{/-last}}{{/allParams}}>{{! + ### Function parameter names + }}(&self, {{#allParams}}{{{paramName}}}: {{! + ### Option Start + }}{{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{! + ### &str and Vec<&str> + }}{{#isString}}{{#isArray}}Vec<{{/isArray}}{{^isUuid}}&'{{#lambda.lifetimeName}}{{{paramName}}}{{/lambda.lifetimeName}} str{{/isUuid}}{{#isArray}}>{{/isArray}}{{/isString}}{{! + ### UUIDs + }}{{#isUuid}}{{#isArray}}Vec<{{/isArray}}&str{{#isArray}}>{{/isArray}}{{/isUuid}}{{! + ### Models and primative types + }}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{! + ### Option End + }}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{! + ### Comma for next arguement + }}{{^-last}}, {{/-last}}{{/allParams}}{{! + ### Function return type + }}) -> Result<{{! + ### Multi response support + }}{{#supportMultipleResponses}}ResponseContent<{{{operationIdCamelCase}}}Success>{{/supportMultipleResponses}}{{! + ### Regular return type + }}{{^supportMultipleResponses}}{{^returnType}}(){{/returnType}}{{{returnType}}}{{/supportMultipleResponses}}{{! + ### Error Type + }}, Error<{{{operationIdCamelCase}}}Error>>; +{{/vendorExtensions.x-group-parameters}} +{{/operation}} +{{/operations}} +} + +pub struct {{{classname}}}Client { + configuration: Arc +} + +impl {{classname}}Client { + pub fn new(configuration: Arc) -> Self { + Self { configuration } + } +} + + +{{#operations}} +{{#operation}} +{{#vendorExtensions.x-group-parameters}} +{{#allParams}} +{{#-first}} +/// struct for passing parameters to the method [`{{operationId}}`] +#[derive(Clone, Debug)] +{{#useBonBuilder}} +#[cfg_attr(feature = "bon", derive(::bon::Builder))] +{{/useBonBuilder}} +pub struct {{{operationIdCamelCase}}}Params { +{{/-first}} + {{#description}} + /// {{{.}}} + {{/description}} + pub {{{paramName}}}: {{! + ### Option Start + }}{{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{! + ### &str and Vec<&str> + }}{{^isUuid}}{{#isString}}{{#isArray}}Vec<{{/isArray}}String{{#isArray}}>{{/isArray}}{{/isString}}{{/isUuid}}{{! + ### UUIDs + }}{{#isUuid}}{{#isArray}}Vec<{{/isArray}}String{{#isArray}}>{{/isArray}}{{/isUuid}}{{! + ### Models and primative types + }}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{! + ### Option End + }}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{! + ### Comma for next field + }}{{^-last}},{{/-last}} +{{#-last}} +} + +{{/-last}} +{{/allParams}} +{{/vendorExtensions.x-group-parameters}} +{{/operation}} +{{/operations}} + +#[async_trait] +impl {{classname}} for {{classname}}Client { + {{#operations}} + {{#operation}} + {{#description}} + /// {{{.}}} + {{/description}} + {{#notes}} + /// {{{.}}} + {{/notes}} + {{#vendorExtensions.x-group-parameters}} + async fn {{{operationId}}}(&self, {{#allParams}}{{#-first}} params: {{{operationIdCamelCase}}}Params {{/-first}}{{/allParams}}{{! + ### Function return type + }}) -> Result<{{! + ### Multi response support + }}{{#supportMultipleResponses}}ResponseContent<{{{operationIdCamelCase}}}Success>{{/supportMultipleResponses}}{{! + ### Regular return type + }}{{^supportMultipleResponses}}{{^returnType}}(){{/returnType}}{{{returnType}}}{{/supportMultipleResponses}}{{! + ### Error Type + }}, Error<{{{operationIdCamelCase}}}Error>> { + {{#allParams}}{{#-first}} + let {{{operationIdCamelCase}}}Params { + {{#allParams}} + {{{paramName}}}, + {{/allParams}} + } = params; + {{/-first}}{{/allParams}} + + {{/vendorExtensions.x-group-parameters}} + {{^vendorExtensions.x-group-parameters}} + async fn {{{operationId}}}{{! + ### Lifetimes + }}<{{#allParams}}'{{#lambda.lifetimeName}}{{{paramName}}}{{/lambda.lifetimeName}}{{^-last}}, {{/-last}}{{/allParams}}>{{! + ### Function parameter names + }}(&self, {{#allParams}}{{{paramName}}}: {{! + ### Option Start + }}{{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{! + ### &str and Vec<&str> + }}{{#isString}}{{#isArray}}Vec<{{/isArray}}{{^isUuid}}&'{{#lambda.lifetimeName}}{{{paramName}}}{{/lambda.lifetimeName}} str{{/isUuid}}{{#isArray}}>{{/isArray}}{{/isString}}{{! + ### UUIDs + }}{{#isUuid}}{{#isArray}}Vec<{{/isArray}}&str{{#isArray}}>{{/isArray}}{{/isUuid}}{{! + ### Models and primative types + }}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{! + ### Option End + }}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{! + ### Comma for next arguement + }}{{^-last}}, {{/-last}}{{/allParams}}{{! + ### Function return type + }}) -> Result<{{! + ### Multi response support + }}{{#supportMultipleResponses}}ResponseContent<{{{operationIdCamelCase}}}Success>{{/supportMultipleResponses}}{{! + ### Regular return type + }}{{^supportMultipleResponses}}{{^returnType}}(){{/returnType}}{{{returnType}}}{{/supportMultipleResponses}}{{! + ### Regular return type + }}, Error<{{{operationIdCamelCase}}}Error>> { + {{/vendorExtensions.x-group-parameters}} + let local_var_configuration = &self.configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}{{{path}}}", local_var_configuration.base_path{{#pathParams}}, {{{baseName}}}={{#isString}}crate::apis::urlencode({{/isString}}{{{paramName}}}{{^required}}.unwrap(){{/required}}{{#required}}{{#isNullable}}.unwrap(){{/isNullable}}{{/required}}{{#isArray}}.join(",").as_ref(){{/isArray}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}.to_string(){{/isContainer}}{{/isPrimitiveType}}{{/isUuid}}{{/isString}}{{#isString}}){{/isString}}{{/pathParams}}); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::{{{httpMethod}}}, local_var_uri_str.as_str()); + + {{#queryParams}} + {{#required}} + {{#isArray}} + local_var_req_builder = match "{{collectionFormat}}" { + "multi" => local_var_req_builder.query(&{{{paramName}}}.into_iter().map(|p| ("{{{baseName}}}".to_owned(), p.to_string())).collect::>()), + _ => local_var_req_builder.query(&[("{{{baseName}}}", &{{{paramName}}}.into_iter().map(|p| p.to_string()).collect::>().join(",").to_string())]), + }; + {{/isArray}} + {{^isArray}} + {{^isNullable}} + local_var_req_builder = local_var_req_builder.query(&[("{{{baseName}}}", &{{{paramName}}}.to_string())]); + {{/isNullable}} + {{#isNullable}} + {{#isDeepObject}} + {{^isExplode}} + if let Some(ref param_value) = {{{paramName}}} { + let params = crate::apis::parse_deep_object("{{{baseName}}}", &serde_json::to_value(param_value)?); + local_var_req_builder = local_var_req_builder.query(¶ms); + } + {{/isExplode}} + {{#isExplode}} + {{#isModel}} + if let Some(ref param_value) = {{{paramName}}} { + local_var_req_builder = local_var_req_builder.query(¶m_value); + } + {{/isModel}} + {{#isMap}} + if let Some(ref param_value) = {{{paramName}}} { + let mut query_params = Vec::with_capacity(param_value.len()); + for (key, value) in param_value.iter() { + query_params.push((key.to_string(), serde_json::to_string(value)?)); + } + local_var_req_builder = local_var_req_builder.query(&query_params); + } + {{/isMap}} + {{/isExplode}} + {{/isDeepObject}} + {{^isDeepObject}} + {{#isObject}} + if let Some(ref param_value) = {{{paramName}}} { + local_var_req_builder = local_var_req_builder.query(&[("{{{baseName}}}", &serde_json::to_value(param_value)?)]); + }; + {{/isObject}} + {{#isModel}} + if let Some(ref param_value) = {{{paramName}}} { + local_var_req_builder = local_var_req_builder.query(&[("{{{baseName}}}", &serde_json::to_value(param_value)?)]); + }; + {{/isModel}} + {{^isObject}} + {{^isModel}} + if let Some(ref param_value) = {{{paramName}}} { + local_var_req_builder = local_var_req_builder.query(&[("{{{baseName}}}", ¶m_value.to_string())]); + }; + {{/isModel}} + {{/isObject}} + {{/isDeepObject}} + {{/isNullable}} + {{/isArray}} + {{/required}} + {{^required}} + if let Some(ref param_value) = {{{paramName}}} { + {{#isArray}} + local_var_req_builder = match "{{collectionFormat}}" { + "multi" => local_var_req_builder.query(¶m_value.into_iter().map(|p| ("{{{baseName}}}".to_owned(), p.to_string())).collect::>()), + _ => local_var_req_builder.query(&[("{{{baseName}}}", ¶m_value.into_iter().map(|p| p.to_string()).collect::>().join(",").to_string())]), + }; + {{/isArray}} + {{#isDeepObject}} + {{^isExplode}} + let params = crate::apis::parse_deep_object("{{{baseName}}}", &serde_json::to_value(param_value)?); + local_var_req_builder = local_var_req_builder.query(¶ms); + {{/isExplode}} + {{#isExplode}} + {{#isModel}} + local_var_req_builder = local_var_req_builder.query(¶m_value); + {{/isModel}} + {{#isMap}} + let mut query_params = Vec::with_capacity(param_value.len()); + for (key, value) in param_value.iter() { + query_params.push((key.to_string(), serde_json::to_string(value)?)); + } + local_var_req_builder = local_var_req_builder.query(&query_params); + {{/isMap}} + {{/isExplode}} + {{/isDeepObject}} + {{^isDeepObject}} + {{#isObject}} + local_var_req_builder = local_var_req_builder.query(&[("{{{baseName}}}", &serde_json::to_value(param_value)?)]); + {{/isObject}} + {{#isModel}} + local_var_req_builder = local_var_req_builder.query(&[("{{{baseName}}}", &serde_json::to_value(param_value)?)]); + {{/isModel}} + {{^isObject}} + {{^isModel}} + local_var_req_builder = local_var_req_builder.query(&[("{{{baseName}}}", ¶m_value.to_string())]); + {{/isModel}} + {{/isObject}} + {{/isDeepObject}} + } + {{/required}} + {{/queryParams}} + {{#hasAuthMethods}} + {{#authMethods}} + {{#isApiKey}} + {{#isKeyInQuery}} + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.query(&[("{{{keyParamName}}}", local_var_value)]); + } + {{/isKeyInQuery}} + {{/isApiKey}} + {{/authMethods}} + {{/hasAuthMethods}} + {{#hasAuthMethods}} + {{#withAWSV4Signature}} + if let Some(ref local_var_aws_v4_key) = local_var_configuration.aws_v4_key { + let local_var_new_headers = match local_var_aws_v4_key.sign( + &local_var_uri_str, + "{{{httpMethod}}}", + {{#hasBodyParam}} + {{#bodyParams}} + &serde_json::to_string(&{{{paramName}}}).expect("param should serialize to string"), + {{/bodyParams}} + {{/hasBodyParam}} + {{^hasBodyParam}} + "", + {{/hasBodyParam}} + ) { + Ok(new_headers) => new_headers, + Err(err) => return Err(Error::AWSV4SignatureError(err)), + }; + for (local_var_name, local_var_value) in local_var_new_headers.iter() { + local_var_req_builder = local_var_req_builder.header(local_var_name.as_str(), local_var_value.as_str()); + } + } + {{/withAWSV4Signature}} + {{/hasAuthMethods}} + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + {{#hasHeaderParams}} + {{#headerParams}} + {{#required}} + {{^isNullable}} + local_var_req_builder = local_var_req_builder.header("{{{baseName}}}", {{{paramName}}}{{#isArray}}.join(","){{/isArray}}.to_string()); + {{/isNullable}} + {{#isNullable}} + match {{{paramName}}} { + Some(local_var_param_value) => { local_var_req_builder = local_var_req_builder.header("{{{baseName}}}", local_var_param_value{{#isArray}}.join(","){{/isArray}}.to_string()); }, + None => { local_var_req_builder = local_var_req_builder.header("{{{baseName}}}", ""); }, + } + {{/isNullable}} + {{/required}} + {{^required}} + if let Some(local_var_param_value) = {{{paramName}}} { + local_var_req_builder = local_var_req_builder.header("{{{baseName}}}", local_var_param_value{{#isArray}}.join(","){{/isArray}}.to_string()); + } + {{/required}} + {{/headerParams}} + {{/hasHeaderParams}} + {{#hasAuthMethods}} + {{#authMethods}} + {{#supportTokenSource}} + // Obtain a token from source provider. + // Tokens can be Id or access tokens depending on the provider type and configuration. + let token = local_var_configuration.token_source.token().await.map_err(Error::TokenSource)?; + // The token format is the responsibility of the provider, thus we just set the authorization header with whatever is given. + local_var_req_builder = local_var_req_builder.header(reqwest::header::AUTHORIZATION, token); + {{/supportTokenSource}} + {{^supportTokenSource}} + {{#isApiKey}} + {{#isKeyInHeader}} + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("{{{keyParamName}}}", local_var_value); + }; + {{/isKeyInHeader}} + {{/isApiKey}} + {{#isBasic}} + {{#isBasicBasic}} + if let Some(ref local_var_auth_conf) = local_var_configuration.basic_auth { + local_var_req_builder = local_var_req_builder.basic_auth(local_var_auth_conf.0.to_owned(), local_var_auth_conf.1.to_owned()); + }; + {{/isBasicBasic}} + {{#isBasicBearer}} + if let Some(ref local_var_token) = local_var_configuration.bearer_access_token { + local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned()); + }; + {{/isBasicBearer}} + {{/isBasic}} + {{#isOAuth}} + if let Some(ref local_var_token) = local_var_configuration.oauth_access_token { + local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned()); + }; + {{/isOAuth}} + {{/supportTokenSource}} + {{/authMethods}} + {{/hasAuthMethods}} + {{#isMultipart}} + {{#hasFormParams}} + let mut local_var_form = reqwest::multipart::Form::new(); + {{#formParams}} + {{#isFile}} + // TODO: support file upload for '{{{baseName}}}' parameter + {{/isFile}} + {{^isFile}} + {{#required}} + {{^isNullable}} + local_var_form = local_var_form.text("{{{baseName}}}", {{{paramName}}}{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); + {{/isNullable}} + {{#isNullable}} + match {{{paramName}}} { + Some(local_var_param_value) => { local_var_form = local_var_form.text("{{{baseName}}}", local_var_param_value{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); }, + None => { local_var_form = local_var_form.text("{{{baseName}}}", ""); }, + } + {{/isNullable}} + {{/required}} + {{^required}} + if let Some(local_var_param_value) = {{{paramName}}} { + local_var_form = local_var_form.text("{{{baseName}}}", local_var_param_value{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); + } + {{/required}} + {{/isFile}} + {{/formParams}} + local_var_req_builder = local_var_req_builder.multipart(local_var_form); + {{/hasFormParams}} + {{/isMultipart}} + {{^isMultipart}} + {{#hasFormParams}} + let mut local_var_form_params = std::collections::HashMap::new(); + {{#formParams}} + {{#isFile}} + {{#required}} + {{^isNullable}} + local_var_form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); + {{/isNullable}} + {{#isNullable}} + match {{{paramName}}} { + Some(local_var_param_value) => { local_var_form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); }, + None => { unimplemented!("Required nullable file form param not supported with x-www-form-urlencoded content"); }, + } + {{/isNullable}} + {{/required}} + {{^required}} + if let Some(local_var_param_value) = {{{paramName}}} { + local_var_form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); + } + {{/required}} + {{/isFile}} + {{^isFile}} + {{#required}} + {{^isNullable}} + local_var_form_params.insert("{{{baseName}}}", {{{paramName}}}{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); + {{/isNullable}} + {{#isNullable}} + match {{{paramName}}} { + Some(local_var_param_value) => { local_var_form_params.insert("{{{baseName}}}", local_var_param_value{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); }, + None => { local_var_form_params.insert("{{{baseName}}}", ""); }, + } + {{/isNullable}} + {{/required}} + {{^required}} + if let Some(local_var_param_value) = {{{paramName}}} { + local_var_form_params.insert("{{{baseName}}}", local_var_param_value{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); + } + {{/required}} + {{/isFile}} + {{/formParams}} + local_var_req_builder = local_var_req_builder.form(&local_var_form_params); + {{/hasFormParams}} + {{/isMultipart}} + {{#hasBodyParam}} + {{#bodyParams}} + local_var_req_builder = local_var_req_builder.json(&{{{paramName}}}); + {{/bodyParams}} + {{/hasBodyParam}} + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + {{^supportMultipleResponses}} + {{#returnType}} + let local_var_content_type = local_var_resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let local_var_content_type = super::ContentType::from(local_var_content_type); + {{/returnType}} + {{/supportMultipleResponses}} + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + {{^supportMultipleResponses}} + {{^returnType}} + Ok(()) + {{/returnType}} + {{#returnType}} + match local_var_content_type { + ContentType::Json => serde_json::from_str(&local_var_content).map_err(Error::from), + {{#vendorExtensions.x-supports-plain-text}} + ContentType::Text => return Ok(local_var_content), + {{/vendorExtensions.x-supports-plain-text}} + {{^vendorExtensions.x-supports-plain-text}} + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `{{returnType}}`"))), + {{/vendorExtensions.x-supports-plain-text}} + ContentType::Unsupported(local_var_unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{local_var_unknown_type}` content type response that cannot be converted to `{{returnType}}`")))), + } + {{/returnType}} + {{/supportMultipleResponses}} + {{#supportMultipleResponses}} + let local_var_entity: Option<{{{operationIdCamelCase}}}Success> = serde_json::from_str(&local_var_content).ok(); + let local_var_result = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Ok(local_var_result) + {{/supportMultipleResponses}} + } else { + let local_var_entity: Option<{{{operationIdCamelCase}}}Error> = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) + } + } + + {{/operation}} + {{/operations}} +} + +{{#supportMultipleResponses}} +{{#operations}} +{{#operation}} +/// struct for typed successes of method [`{{operationId}}`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum {{{operationIdCamelCase}}}Success { + {{#responses}} + {{#is2xx}} + Status{{code}}({{#isEnum}}{{{enumName}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}), + {{/is2xx}} + {{#is3xx}} + Status{{code}}({{#isEnum}}{{{enumName}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}), + {{/is3xx}} + {{/responses}} + UnknownValue(serde_json::Value), +} + +{{/operation}} +{{/operations}} +{{/supportMultipleResponses}} +{{#operations}} +{{#operation}} +/// struct for typed errors of method [`{{operationId}}`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum {{{operationIdCamelCase}}}Error { + {{#responses}} + {{#is4xx}} + Status{{code}}({{#isEnum}}{{{enumName}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}), + {{/is4xx}} + {{#is5xx}} + Status{{code}}({{#isEnum}}{{{enumName}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}), + {{/is5xx}} + {{#isDefault}} + DefaultResponse({{#isEnum}}{{{enumName}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}), + {{/isDefault}} + {{/responses}} + UnknownValue(serde_json::Value), +} + +{{/operation}} +{{/operations}} diff --git a/custom-templates/reqwest-trait/api_mod.mustache b/custom-templates/reqwest-trait/api_mod.mustache new file mode 100644 index 0000000..41a4ba0 --- /dev/null +++ b/custom-templates/reqwest-trait/api_mod.mustache @@ -0,0 +1,236 @@ +use std::error; +use std::fmt; +{{#withAWSV4Signature}} +use aws_sigv4; +{{/withAWSV4Signature}} + +#[derive(Debug, Clone)] +pub struct ResponseContent { + pub status: reqwest::StatusCode, + pub content: String, + pub entity: Option, +} + +#[derive(Debug)] +pub enum Error { + Reqwest(reqwest::Error), + {{#supportMiddleware}} + ReqwestMiddleware(reqwest_middleware::Error), + {{/supportMiddleware}} + Serde(serde_json::Error), + Io(std::io::Error), + ResponseError(ResponseContent), + {{#withAWSV4Signature}} + AWSV4SignatureError(aws_sigv4::http_request::Error), + {{/withAWSV4Signature}} + {{#supportTokenSource}} + TokenSource(Box), + {{/supportTokenSource}} +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let (module, e) = match self { + Error::Reqwest(e) => ("reqwest", e.to_string()), + {{#supportMiddleware}} + Error::ReqwestMiddleware(e) => ("reqwest-middleware", e.to_string()), + {{/supportMiddleware}} + Error::Serde(e) => ("serde", e.to_string()), + Error::Io(e) => ("IO", e.to_string()), + Error::ResponseError(e) => ("response", format!("status code {}", e.status)), + {{#withAWSV4Signature}} + Error::AWSV4SignatureError(e) => ("aws v4 signature", e.to_string()), + {{/withAWSV4Signature}} + {{#supportTokenSource}} + Error::TokenSource(e) => ("token source failure", e.to_string()), + {{/supportTokenSource}} + }; + write!(f, "error in {}: {}", module, e) + } +} + +impl error::Error for Error { + fn source(&self) -> Option<&(dyn error::Error + 'static)> { + Some(match self { + Error::Reqwest(e) => e, + {{#supportMiddleware}} + Error::ReqwestMiddleware(e) => e, + {{/supportMiddleware}} + Error::Serde(e) => e, + Error::Io(e) => e, + Error::ResponseError(_) => return None, + {{#withAWSV4Signature}} + Error::AWSV4SignatureError(_) => return None, + {{/withAWSV4Signature}} + {{#supportTokenSource}} + Error::TokenSource(e) => &**e, + {{/supportTokenSource}} + }) + } +} + +impl From for Error { + fn from(e: reqwest::Error) -> Self { + Error::Reqwest(e) + } +} + +{{#supportMiddleware}} +impl From for Error { + fn from(e: reqwest_middleware::Error) -> Self { + Error::ReqwestMiddleware(e) + } +} + +{{/supportMiddleware}} +impl From for Error { + fn from(e: serde_json::Error) -> Self { + Error::Serde(e) + } +} + +impl From for Error { + fn from(e: std::io::Error) -> Self { + Error::Io(e) + } +} + +pub fn urlencode>(s: T) -> String { + ::url::form_urlencoded::byte_serialize(s.as_ref().as_bytes()).collect() +} + +pub fn parse_deep_object(prefix: &str, value: &serde_json::Value) -> Vec<(String, String)> { + if let serde_json::Value::Object(object) = value { + let mut params = vec![]; + + for (key, value) in object { + match value { + serde_json::Value::Object(_) => params.append(&mut parse_deep_object( + &format!("{}[{}]", prefix, key), + value, + )), + serde_json::Value::Array(array) => { + for (i, value) in array.iter().enumerate() { + params.append(&mut parse_deep_object( + &format!("{}[{}][{}]", prefix, key, i), + value, + )); + } + }, + serde_json::Value::String(s) => params.push((format!("{}[{}]", prefix, key), s.clone())), + _ => params.push((format!("{}[{}]", prefix, key), value.to_string())), + } + } + + return params; + } + + unimplemented!("Only objects are supported with style=deepObject") +} + +/// Internal use only +/// A content type supported by this client. +#[allow(dead_code)] +enum ContentType { + Json, + Text, + Unsupported(String) +} + +impl From<&str> for ContentType { + fn from(content_type: &str) -> Self { + if content_type.starts_with("application") && content_type.contains("json") { + return Self::Json; + } else if content_type.starts_with("text/plain") { + return Self::Text; + } else { + return Self::Unsupported(content_type.to_string()); + } + } +} + +{{#apiInfo}} +{{#apis}} +pub mod {{{classFilename}}}; +{{/apis}} +{{/apiInfo}} + +pub mod configuration; + +{{#topLevelApiClient}} +use std::sync::Arc; + +pub trait Api { + {{#apiInfo}} + {{#apis}} + fn {{{classFilename}}}(&self) -> &dyn {{{classFilename}}}::{{classname}}; + {{/apis}} + {{/apiInfo}} +} + +pub struct ApiClient { + {{#apiInfo}} + {{#apis}} + {{{classFilename}}}: Box, + {{/apis}} + {{/apiInfo}} +} + +impl ApiClient { + pub fn new(configuration: Arc) -> Self { + Self { + {{#apiInfo}} + {{#apis}} + {{{classFilename}}}: Box::new({{{classFilename}}}::{{classname}}Client::new(configuration.clone())), + {{/apis}} + {{/apiInfo}} + } + } +} + +impl Api for ApiClient { + {{#apiInfo}} + {{#apis}} + fn {{{classFilename}}}(&self) -> &dyn {{{classFilename}}}::{{classname}} { + self.{{{classFilename}}}.as_ref() + } + {{/apis}} + {{/apiInfo}} +} + +{{#mockall}} +#[cfg(feature = "mockall")] +pub struct MockApiClient { + {{#apiInfo}} + {{#apis}} + pub {{{classFilename}}}_mock: {{{classFilename}}}::Mock{{classname}}, + {{/apis}} + {{/apiInfo}} +} + +#[cfg(feature = "mockall")] +impl MockApiClient { + pub fn new() -> Self { + Self { + {{#apiInfo}} + {{#apis}} + {{{classFilename}}}_mock: {{{classFilename}}}::Mock{{classname}}::new(), + {{/apis}} + {{/apiInfo}} + } + } +} + +#[cfg(feature = "mockall")] +impl Api for MockApiClient { + {{#apiInfo}} + {{#apis}} + fn {{{classFilename}}}(&self) -> &dyn {{{classFilename}}}::{{classname}} { + &self.{{{classFilename}}}_mock + } + {{/apis}} + {{/apiInfo}} +} +{{/mockall}} + +{{/topLevelApiClient}} diff --git a/custom-templates/reqwest-trait/configuration.mustache b/custom-templates/reqwest-trait/configuration.mustache new file mode 100644 index 0000000..2536069 --- /dev/null +++ b/custom-templates/reqwest-trait/configuration.mustache @@ -0,0 +1,120 @@ +{{>partial_header}} + +{{#withAWSV4Signature}} +use std::time::SystemTime; +use aws_sigv4::http_request::{sign, SigningSettings, SigningParams, SignableRequest}; +use http; +use secrecy::{SecretString, ExposeSecret}; +{{/withAWSV4Signature}} +{{#supportTokenSource}} +use std::sync::Arc; +use google_cloud_token::TokenSource; +use async_trait::async_trait; +{{/supportTokenSource}} + +#[derive(Debug, Clone)] +pub struct Configuration { + pub base_path: String, + pub user_agent: Option, + pub client: {{#supportMiddleware}}reqwest_middleware::ClientWithMiddleware{{/supportMiddleware}}{{^supportMiddleware}}reqwest::Client{{/supportMiddleware}}, + {{^supportTokenSource}} + pub basic_auth: Option, + pub oauth_access_token: Option, + pub bearer_access_token: Option, + pub api_key: Option, + {{/supportTokenSource}} + {{#withAWSV4Signature}} + pub aws_v4_key: Option, + {{/withAWSV4Signature}} + {{#supportTokenSource}} + pub token_source: Arc, + {{/supportTokenSource}} +} +{{^supportTokenSource}} + +pub type BasicAuth = (String, Option); + +#[derive(Debug, Clone)] +pub struct ApiKey { + pub prefix: Option, + pub key: String, +} +{{/supportTokenSource}} + +{{#withAWSV4Signature}} +#[derive(Debug, Clone)] +pub struct AWSv4Key { + pub access_key: String, + pub secret_key: SecretString, + pub region: String, + pub service: String, +} + +impl AWSv4Key { + pub fn sign(&self, uri: &str, method: &str, body: &str) -> Result, aws_sigv4::http_request::Error> { + let request = http::Request::builder() + .uri(uri) + .method(method) + .body(body).unwrap(); + let signing_settings = SigningSettings::default(); + let signing_params = SigningParams::builder() + .access_key(self.access_key.as_str()) + .secret_key(self.secret_key.expose_secret().as_str()) + .region(self.region.as_str()) + .service_name(self.service.as_str()) + .time(SystemTime::now()) + .settings(signing_settings) + .build() + .unwrap(); + let signable_request = SignableRequest::from(&request); + let (mut signing_instructions, _signature) = sign(signable_request, &signing_params)?.into_parts(); + let mut additional_headers = Vec::<(String, String)>::new(); + if let Some(new_headers) = signing_instructions.take_headers() { + for (name, value) in new_headers.into_iter() { + additional_headers.push((name.expect("header should have name").to_string(), + value.to_str().expect("header value should be a string").to_string())); + } + } + Ok(additional_headers) + } +} +{{/withAWSV4Signature}} + +impl Configuration { + pub fn new() -> Configuration { + Configuration::default() + } +} + +impl Default for Configuration { + fn default() -> Self { + Configuration { + base_path: "{{{basePath}}}".to_owned(), + user_agent: {{#httpUserAgent}}Some("{{{.}}}".to_owned()){{/httpUserAgent}}{{^httpUserAgent}}Some("OpenAPI-Generator/{{{version}}}/rust".to_owned()){{/httpUserAgent}}, + client: {{#supportMiddleware}}reqwest_middleware::ClientBuilder::new(reqwest::Client::new()).build(){{/supportMiddleware}}{{^supportMiddleware}}reqwest::Client::new(){{/supportMiddleware}}, + {{^supportTokenSource}} + basic_auth: None, + oauth_access_token: None, + bearer_access_token: None, + api_key: None, + {{/supportTokenSource}} + {{#withAWSV4Signature}} + aws_v4_key: None, + {{/withAWSV4Signature}} + {{#supportTokenSource}} + token_source: Arc::new(NoopTokenSource{}), + {{/supportTokenSource}} + } + } +} +{{#supportTokenSource}} +#[derive(Debug)] +struct NoopTokenSource{} + +#[async_trait] +impl TokenSource for NoopTokenSource { + async fn token(&self) -> Result> { + panic!("This is dummy token source. You can use TokenSourceProvider from 'google_cloud_auth' crate, or any other compatible crate.") + } +} +{{/supportTokenSource}} diff --git a/custom-templates/reqwest/api.mustache b/custom-templates/reqwest/api.mustache new file mode 100644 index 0000000..e28ca3e --- /dev/null +++ b/custom-templates/reqwest/api.mustache @@ -0,0 +1,515 @@ +{{>partial_header}} + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + +{{#operations}} +{{#operation}} +{{#vendorExtensions.x-group-parameters}} +{{#allParams}} +{{#-first}} +/// struct for passing parameters to the method [`{{operationId}}`] +#[derive(Clone, Debug)] +pub struct {{{operationIdCamelCase}}}Params { +{{/-first}} + {{#description}} + /// {{{.}}} + {{/description}} + pub {{{paramName}}}: {{! + ### Option Start + }}{{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{! + ### &str and Vec<&str> + }}{{^isUuid}}{{#isString}}{{#isArray}}Vec<{{/isArray}}String{{#isArray}}>{{/isArray}}{{/isString}}{{/isUuid}}{{! + ### UUIDs + }}{{#isUuid}}{{#isArray}}Vec<{{/isArray}}String{{#isArray}}>{{/isArray}}{{/isUuid}}{{! + ### Models and primative types + }}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{! + ### Option End + }}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{! + ### Comma for next arguement + }}{{^-last}},{{/-last}} +{{#-last}} +} + +{{/-last}} +{{/allParams}} +{{/vendorExtensions.x-group-parameters}} +{{/operation}} +{{/operations}} + +{{#supportMultipleResponses}} +{{#operations}} +{{#operation}} +/// struct for typed successes of method [`{{operationId}}`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum {{{operationIdCamelCase}}}Success { + {{#responses}} + {{#is2xx}} + Status{{code}}({{#isEnum}}{{{enumName}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}), + {{/is2xx}} + {{#is3xx}} + Status{{code}}({{#isEnum}}{{{enumName}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}), + {{/is3xx}} + {{/responses}} + UnknownValue(serde_json::Value), +} + +{{/operation}} +{{/operations}} +{{/supportMultipleResponses}} +{{#operations}} +{{#operation}} +/// struct for typed errors of method [`{{operationId}}`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum {{{operationIdCamelCase}}}Error { + {{#responses}} + {{#is4xx}} + Status{{code}}({{#isEnum}}{{{enumName}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}), + {{/is4xx}} + {{#is5xx}} + Status{{code}}({{#isEnum}}{{{enumName}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}), + {{/is5xx}} + {{#isDefault}} + DefaultResponse({{#isEnum}}{{{enumName}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}), + {{/isDefault}} + {{/responses}} + UnknownValue(serde_json::Value), +} + +{{/operation}} +{{/operations}} + +{{#operations}} +{{#operation}} +{{#description}} +/// {{{.}}} +{{/description}} +{{#notes}} +/// {{{.}}} +{{/notes}} +{{#vendorExtensions.x-group-parameters}} +pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}(configuration: &configuration::Configuration{{#allParams}}{{#-first}}, {{! +### Params +}}params: {{{operationIdCamelCase}}}Params{{/-first}}{{/allParams}}{{! +### Function return type +}}) -> Result<{{! +### Response File Support +}}{{#isResponseFile}}{{#supportAsync}}reqwest::Response{{/supportAsync}}{{^supportAsync}}reqwest::blocking::Response{{/supportAsync}}{{/isResponseFile}}{{! +### Regular Responses +}}{{^isResponseFile}}{{! +### Multi response support +}}{{#supportMultipleResponses}}ResponseContent<{{{operationIdCamelCase}}}Success>{{/supportMultipleResponses}}{{! +### Regular return type +}}{{^supportMultipleResponses}}{{^returnType}}(){{/returnType}}{{{returnType}}}{{/supportMultipleResponses}}{{/isResponseFile}}{{! +### Error Type +}}, Error<{{{operationIdCamelCase}}}Error>> { +{{/vendorExtensions.x-group-parameters}} +{{^vendorExtensions.x-group-parameters}} +pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}(configuration: &configuration::Configuration, {{#allParams}}{{{paramName}}}: {{! +### Option Start +}}{{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{! +### &str and Vec<&str> +}}{{#isString}}{{#isArray}}Vec<{{/isArray}}{{^isUuid}}&str{{/isUuid}}{{#isArray}}>{{/isArray}}{{/isString}}{{! +### UUIDs +}}{{#isUuid}}{{#isArray}}Vec<{{/isArray}}&str{{#isArray}}>{{/isArray}}{{/isUuid}}{{! +### Models and primative types +}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{! +### Option End +}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{! +### Comma for next arguement +}}{{^-last}}, {{/-last}}{{/allParams}}{{! +### Function return type +}}) -> Result<{{! +### Response File Support +}}{{#isResponseFile}}{{#supportAsync}}reqwest::Response{{/supportAsync}}{{^supportAsync}}reqwest::blocking::Response{{/supportAsync}}{{/isResponseFile}}{{! +### Regular Responses +}}{{^isResponseFile}}{{! +### Multi response support +}}{{#supportMultipleResponses}}ResponseContent<{{{operationIdCamelCase}}}Success>{{/supportMultipleResponses}}{{! +### Regular return type +}}{{^supportMultipleResponses}}{{^returnType}}(){{/returnType}}{{{returnType}}}{{/supportMultipleResponses}}{{/isResponseFile}}{{! +### Error Type +}}, Error<{{{operationIdCamelCase}}}Error>> { + {{#allParams.0}} + // add a prefix to parameters to efficiently prevent name collisions + {{/allParams.0}} + {{#allParams}} + let {{{vendorExtensions.x-rust-param-identifier}}} = {{{paramName}}}; + {{/allParams}} +{{/vendorExtensions.x-group-parameters}} + + let uri_str = format!("{}{{{path}}}", configuration.base_path{{#pathParams}}, {{{baseName}}}={{#isString}}crate::apis::urlencode({{/isString}}{{{vendorExtensions.x-rust-param-identifier}}}{{^required}}.unwrap(){{/required}}{{#required}}{{#isNullable}}.unwrap(){{/isNullable}}{{/required}}{{#isArray}}.join(",").as_ref(){{/isArray}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}.to_string(){{/isContainer}}{{/isPrimitiveType}}{{/isUuid}}{{/isString}}{{#isString}}){{/isString}}{{/pathParams}}); + let mut req_builder = configuration.client.request(reqwest::Method::{{{httpMethod}}}, &uri_str); + + {{#queryParams}} + {{#required}} + {{#isArray}} + req_builder = match "{{collectionFormat}}" { + "multi" => req_builder.query(&{{{vendorExtensions.x-rust-param-identifier}}}.into_iter().map(|p| ("{{{baseName}}}".to_owned(), p.to_string())).collect::>()), + _ => req_builder.query(&[("{{{baseName}}}", &{{{vendorExtensions.x-rust-param-identifier}}}.into_iter().map(|p| p.to_string()).collect::>().join(",").to_string())]), + }; + {{/isArray}} + {{^isArray}} + {{^isNullable}} + req_builder = req_builder.query(&[("{{{baseName}}}", &{{{vendorExtensions.x-rust-param-identifier}}}.to_string())]); + {{/isNullable}} + {{#isNullable}} + {{#isDeepObject}} + if let Some(ref param_value) = {{{vendorExtensions.x-rust-param-identifier}}} { + {{^isExplode}} + let params = crate::apis::parse_deep_object("{{{baseName}}}", &serde_json::to_value(param_value)?); + req_builder = req_builder.query(¶ms); + {{/isExplode}} + {{#isExplode}} + {{#isModel}} + req_builder = req_builder.query(¶m_value); + {{/isModel}} + {{#isMap}} + let mut query_params = Vec::with_capacity(param_value.len()); + for (key, value) in param_value.iter() { + query_params.push((key.to_string(), serde_json::to_string(value)?)); + } + req_builder = req_builder.query(&query_params); + {{/isMap}} + {{/isExplode}} + }; + {{/isDeepObject}} + {{^isDeepObject}} + {{#isObject}} + if let Some(ref param_value) = {{{vendorExtensions.x-rust-param-identifier}}} { + req_builder = req_builder.query(&[("{{{baseName}}}", &serde_json::to_string(param_value)?)]); + }; + {{/isObject}} + {{#isModel}} + if let Some(ref param_value) = {{{vendorExtensions.x-rust-param-identifier}}} { + req_builder = req_builder.query(&[("{{{baseName}}}", &serde_json::to_string(param_value)?)]); + }; + {{/isModel}} + {{/isDeepObject}} + {{^isObject}} + {{^isModel}} + if let Some(ref param_value) = {{{vendorExtensions.x-rust-param-identifier}}} { + req_builder = req_builder.query(&[("{{{baseName}}}", ¶m_value.to_string())]); + }; + {{/isModel}} + {{/isObject}} + {{/isNullable}} + {{/isArray}} + {{/required}} + {{^required}} + if let Some(ref param_value) = {{{vendorExtensions.x-rust-param-identifier}}} { + {{#isArray}} + req_builder = match "{{collectionFormat}}" { + "multi" => req_builder.query(¶m_value.into_iter().map(|p| ("{{{baseName}}}".to_owned(), p.to_string())).collect::>()), + _ => req_builder.query(&[("{{{baseName}}}", ¶m_value.into_iter().map(|p| p.to_string()).collect::>().join(",").to_string())]), + }; + {{/isArray}} + {{^isArray}} + {{#isDeepObject}} + {{^isExplode}} + let params = crate::apis::parse_deep_object("{{{baseName}}}", &serde_json::to_value(param_value)?); + req_builder = req_builder.query(¶ms); + {{/isExplode}} + {{#isExplode}} + {{#isModel}} + req_builder = req_builder.query(¶m_value); + {{/isModel}} + {{#isMap}} + let mut query_params = Vec::with_capacity(param_value.len()); + for (key, value) in param_value.iter() { + query_params.push((key.to_string(), serde_json::to_string(value)?)); + } + req_builder = req_builder.query(&query_params); + {{/isMap}} + {{/isExplode}} + {{/isDeepObject}} + {{^isDeepObject}} + {{#isObject}} + req_builder = req_builder.query(&[("{{{baseName}}}", &serde_json::to_string(param_value)?)]); + {{/isObject}} + {{#isModel}} + req_builder = req_builder.query(&[("{{{baseName}}}", &serde_json::to_string(param_value)?)]); + {{/isModel}} + {{^isObject}} + {{^isModel}} + req_builder = req_builder.query(&[("{{{baseName}}}", ¶m_value.to_string())]); + {{/isModel}} + {{/isObject}} + {{/isDeepObject}} + {{/isArray}} + } + {{/required}} + {{/queryParams}} + {{#hasAuthMethods}} + {{#authMethods}} + {{#isApiKey}} + {{#isKeyInQuery}} + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.query(&[("{{{keyParamName}}}", value)]); + } + {{/isKeyInQuery}} + {{/isApiKey}} + {{/authMethods}} + {{/hasAuthMethods}} + {{#hasAuthMethods}} + {{#withAWSV4Signature}} + if let Some(ref aws_v4_key) = configuration.aws_v4_key { + let new_headers = match aws_v4_key.sign( + &uri_str, + "{{{httpMethod}}}", + {{#hasBodyParam}} + {{#bodyParams}} + &serde_json::to_string(&{{{vendorExtensions.x-rust-param-identifier}}}).expect("param should serialize to string"), + {{/bodyParams}} + {{/hasBodyParam}} + {{^hasBodyParam}} + "", + {{/hasBodyParam}} + ) { + Ok(new_headers) => new_headers, + Err(err) => return Err(Error::AWSV4SignatureError(err)), + }; + for (name, value) in new_headers.iter() { + req_builder = req_builder.header(name.as_str(), value.as_str()); + } + } + {{/withAWSV4Signature}} + {{/hasAuthMethods}} + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + {{#hasHeaderParams}} + {{#headerParams}} + {{#required}} + {{^isNullable}} + req_builder = req_builder.header("{{{baseName}}}", {{{vendorExtensions.x-rust-param-identifier}}}{{#isArray}}.join(","){{/isArray}}.to_string()); + {{/isNullable}} + {{#isNullable}} + match {{{vendorExtensions.x-rust-param-identifier}}} { + Some(param_value) => { req_builder = req_builder.header("{{{baseName}}}", param_value{{#isArray}}.join(","){{/isArray}}.to_string()); }, + None => { req_builder = req_builder.header("{{{baseName}}}", ""); }, + } + {{/isNullable}} + {{/required}} + {{^required}} + if let Some(param_value) = {{{vendorExtensions.x-rust-param-identifier}}} { + req_builder = req_builder.header("{{{baseName}}}", param_value{{#isArray}}.join(","){{/isArray}}.to_string()); + } + {{/required}} + {{/headerParams}} + {{/hasHeaderParams}} + {{#hasAuthMethods}} + {{#authMethods}} + {{#supportTokenSource}} + // Obtain a token from source provider. + // Tokens can be Id or access tokens depending on the provider type and configuration. + let token = configuration.token_source.token().await.map_err(Error::TokenSource)?; + // The token format is the responsibility of the provider, thus we just set the authorization header with whatever is given. + req_builder = req_builder.header(reqwest::header::AUTHORIZATION, token); + {{/supportTokenSource}} + {{^supportTokenSource}} + {{#isApiKey}} + {{#isKeyInHeader}} + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("{{{keyParamName}}}", value); + }; + {{/isKeyInHeader}} + {{/isApiKey}} + {{#isBasic}} + {{#isBasicBasic}} + if let Some(ref auth_conf) = configuration.basic_auth { + req_builder = req_builder.basic_auth(auth_conf.0.to_owned(), auth_conf.1.to_owned()); + }; + {{/isBasicBasic}} + {{#isBasicBearer}} + if let Some(ref token) = configuration.bearer_access_token { + req_builder = req_builder.bearer_auth(token.to_owned()); + }; + {{/isBasicBearer}} + {{/isBasic}} + {{#isOAuth}} + if let Some(ref token) = configuration.oauth_access_token { + req_builder = req_builder.bearer_auth(token.to_owned()); + }; + {{/isOAuth}} + {{/supportTokenSource}} + {{/authMethods}} + {{/hasAuthMethods}} + {{#isMultipart}} + {{#hasFormParams}} + let mut multipart_form = reqwest{{^supportAsync}}::blocking{{/supportAsync}}::multipart::Form::new(); + {{#formParams}} + {{#isFile}} + {{^supportAsync}} + {{#required}} + {{^isNullable}} + multipart_form = multipart_form.file("{{{baseName}}}", {{{vendorExtensions.x-rust-param-identifier}}})?; + {{/isNullable}} + {{#isNullable}} + match {{{vendorExtensions.x-rust-param-identifier}}} { + Some(param_value) => { multipart_form = multipart_form.file("{{{baseName}}}", param_value)?; }, + None => { unimplemented!("Required nullable form file param not supported"); }, + } + {{/isNullable}} + {{/required}} + {{^required}} + if let Some(param_value) = {{{vendorExtensions.x-rust-param-identifier}}} { + multipart_form = multipart_form.file("{{{baseName}}}", param_value)?; + } + {{/required}} + {{/supportAsync}} + {{#supportAsync}} + // TODO: support file upload for '{{{baseName}}}' parameter + {{/supportAsync}} + {{/isFile}} + {{^isFile}} + {{#required}} + {{^isNullable}} + multipart_form = multipart_form.text("{{{baseName}}}", {{{vendorExtensions.x-rust-param-identifier}}}{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); + {{/isNullable}} + {{#isNullable}} + match {{{vendorExtensions.x-rust-param-identifier}}} { + Some(param_value) => { multipart_form = multipart_form.text("{{{baseName}}}", param_value{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); }, + None => { multipart_form = multipart_form.text("{{{baseName}}}", ""); }, + } + {{/isNullable}} + {{/required}} + {{^required}} + if let Some(param_value) = {{{vendorExtensions.x-rust-param-identifier}}} { + multipart_form = multipart_form.text("{{{baseName}}}", param_value{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); + } + {{/required}} + {{/isFile}} + {{/formParams}} + req_builder = req_builder.multipart(multipart_form); + {{/hasFormParams}} + {{/isMultipart}} + {{^isMultipart}} + {{#hasFormParams}} + let mut multipart_form_params = std::collections::HashMap::new(); + {{#formParams}} + {{#isFile}} + {{#required}} + {{^isNullable}} + multipart_form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); + {{/isNullable}} + {{#isNullable}} + match {{{vendorExtensions.x-rust-param-identifier}}} { + Some(param_value) => { multipart_form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); }, + None => { unimplemented!("Required nullable file form param not supported with x-www-form-urlencoded content"); }, + } + {{/isNullable}} + {{/required}} + {{^required}} + if let Some(param_value) = {{{vendorExtensions.x-rust-param-identifier}}} { + multipart_form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); + } + {{/required}} + {{/isFile}} + {{^isFile}} + {{#required}} + {{^isNullable}} + multipart_form_params.insert("{{{baseName}}}", {{{vendorExtensions.x-rust-param-identifier}}}{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); + {{/isNullable}} + {{#isNullable}} + match {{{vendorExtensions.x-rust-param-identifier}}} { + Some(param_value) => { multipart_form_params.insert("{{{baseName}}}", param_value{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); }, + None => { multipart_form_params.insert("{{{baseName}}}", ""); }, + } + {{/isNullable}} + {{/required}} + {{^required}} + if let Some(param_value) = {{{vendorExtensions.x-rust-param-identifier}}} { + multipart_form_params.insert("{{{baseName}}}", param_value{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); + } + {{/required}} + {{/isFile}} + {{/formParams}} + req_builder = req_builder.form(&multipart_form_params); + {{/hasFormParams}} + {{/isMultipart}} + {{#hasBodyParam}} + {{#bodyParams}} + {{#isFile}} + req_builder = req_builder.body({{{vendorExtensions.x-rust-param-identifier}}}); + {{/isFile}} + {{^isFile}} + req_builder = req_builder.json(&{{{vendorExtensions.x-rust-param-identifier}}}); + {{/isFile}} + {{/bodyParams}} + {{/hasBodyParam}} + + let req = req_builder.build()?; + let resp = configuration.client.execute(req){{#supportAsync}}.await{{/supportAsync}}?; + + let status = resp.status(); + {{^supportMultipleResponses}} + {{^isResponseFile}} + {{#returnType}} + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + {{/returnType}} + {{/isResponseFile}} + {{/supportMultipleResponses}} + + if !status.is_client_error() && !status.is_server_error() { + {{^supportMultipleResponses}} + {{#isResponseFile}} + Ok(resp) + {{/isResponseFile}} + {{^isResponseFile}} + {{^returnType}} + Ok(()) + {{/returnType}} + {{#returnType}} + let content = resp.text(){{#supportAsync}}.await{{/supportAsync}}?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + {{#vendorExtensions.x-supports-plain-text}} + ContentType::Text => return Ok(content), + {{/vendorExtensions.x-supports-plain-text}} + {{^vendorExtensions.x-supports-plain-text}} + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `{{returnType}}`"))), + {{/vendorExtensions.x-supports-plain-text}} + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `{{returnType}}`")))), + } + {{/returnType}} + {{/isResponseFile}} + {{/supportMultipleResponses}} + {{#supportMultipleResponses}} + {{#isResponseFile}} + Ok(resp) + {{/isResponseFile}} + {{^isResponseFile}} + let content = resp.text(){{#supportAsync}}.await{{/supportAsync}}?; + let entity: Option<{{{operationIdCamelCase}}}Success> = serde_json::from_str(&content).ok(); + Ok(ResponseContent { status, content, entity }) + {{/isResponseFile}} + {{/supportMultipleResponses}} + } else { + let content = resp.text(){{#supportAsync}}.await{{/supportAsync}}?; + let entity: Option<{{{operationIdCamelCase}}}Error> = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +{{/operation}} +{{/operations}} diff --git a/custom-templates/reqwest/api_mod.mustache b/custom-templates/reqwest/api_mod.mustache new file mode 100644 index 0000000..4d5df28 --- /dev/null +++ b/custom-templates/reqwest/api_mod.mustache @@ -0,0 +1,164 @@ +use std::error; +use std::fmt; +{{#withAWSV4Signature}} +use aws_sigv4; +{{/withAWSV4Signature}} + +#[derive(Debug, Clone)] +pub struct ResponseContent { + pub status: reqwest::StatusCode, + pub content: String, + pub entity: Option, +} + +#[derive(Debug)] +pub enum Error { + Reqwest(reqwest::Error), + {{#supportMiddleware}} + ReqwestMiddleware(reqwest_middleware::Error), + {{/supportMiddleware}} + Serde(serde_json::Error), + Io(std::io::Error), + ResponseError(ResponseContent), + {{#withAWSV4Signature}} + AWSV4SignatureError(aws_sigv4::http_request::Error), + {{/withAWSV4Signature}} + {{#supportAsync}} + {{#supportTokenSource}} + TokenSource(Box), + {{/supportTokenSource}} + {{/supportAsync}} +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let (module, e) = match self { + Error::Reqwest(e) => ("reqwest", e.to_string()), + {{#supportMiddleware}} + Error::ReqwestMiddleware(e) => ("reqwest-middleware", e.to_string()), + {{/supportMiddleware}} + Error::Serde(e) => ("serde", e.to_string()), + Error::Io(e) => ("IO", e.to_string()), + Error::ResponseError(e) => ("response", format!("status code {}", e.status)), + {{#withAWSV4Signature}} + Error::AWSV4SignatureError(e) => ("aws v4 signature", e.to_string()), + {{/withAWSV4Signature}} + {{#supportAsync}} + {{#supportTokenSource}} + Error::TokenSource(e) => ("token source failure", e.to_string()), + {{/supportTokenSource}} + {{/supportAsync}} + }; + write!(f, "error in {}: {}", module, e) + } +} + +impl error::Error for Error { + fn source(&self) -> Option<&(dyn error::Error + 'static)> { + Some(match self { + Error::Reqwest(e) => e, + {{#supportMiddleware}} + Error::ReqwestMiddleware(e) => e, + {{/supportMiddleware}} + Error::Serde(e) => e, + Error::Io(e) => e, + Error::ResponseError(_) => return None, + {{#withAWSV4Signature}} + Error::AWSV4SignatureError(_) => return None, + {{/withAWSV4Signature}} + {{#supportAsync}} + {{#supportTokenSource}} + Error::TokenSource(e) => &**e, + {{/supportTokenSource}} + {{/supportAsync}} + }) + } +} + +impl From for Error { + fn from(e: reqwest::Error) -> Self { + Error::Reqwest(e) + } +} + +{{#supportMiddleware}} +impl From for Error { + fn from(e: reqwest_middleware::Error) -> Self { + Error::ReqwestMiddleware(e) + } +} + +{{/supportMiddleware}} +impl From for Error { + fn from(e: serde_json::Error) -> Self { + Error::Serde(e) + } +} + +impl From for Error { + fn from(e: std::io::Error) -> Self { + Error::Io(e) + } +} + +pub fn urlencode>(s: T) -> String { + ::url::form_urlencoded::byte_serialize(s.as_ref().as_bytes()).collect() +} + +pub fn parse_deep_object(prefix: &str, value: &serde_json::Value) -> Vec<(String, String)> { + if let serde_json::Value::Object(object) = value { + let mut params = vec![]; + + for (key, value) in object { + match value { + serde_json::Value::Object(_) => params.append(&mut parse_deep_object( + &format!("{}[{}]", prefix, key), + value, + )), + serde_json::Value::Array(array) => { + for (i, value) in array.iter().enumerate() { + params.append(&mut parse_deep_object( + &format!("{}[{}][{}]", prefix, key, i), + value, + )); + } + }, + serde_json::Value::String(s) => params.push((format!("{}[{}]", prefix, key), s.clone())), + _ => params.push((format!("{}[{}]", prefix, key), value.to_string())), + } + } + + return params; + } + + unimplemented!("Only objects are supported with style=deepObject") +} + +/// Internal use only +/// A content type supported by this client. +#[allow(dead_code)] +enum ContentType { + Json, + Text, + Unsupported(String) +} + +impl From<&str> for ContentType { + fn from(content_type: &str) -> Self { + if content_type.starts_with("application") && content_type.contains("json") { + return Self::Json; + } else if content_type.starts_with("text/plain") { + return Self::Text; + } else { + return Self::Unsupported(content_type.to_string()); + } + } +} + +{{#apiInfo}} +{{#apis}} +pub mod {{{classFilename}}}; +{{/apis}} +{{/apiInfo}} + +pub mod configuration; diff --git a/custom-templates/reqwest/configuration.mustache b/custom-templates/reqwest/configuration.mustache new file mode 100644 index 0000000..e29c73b --- /dev/null +++ b/custom-templates/reqwest/configuration.mustache @@ -0,0 +1,122 @@ +{{>partial_header}} + +{{#withAWSV4Signature}} +use std::time::SystemTime; +use aws_sigv4::http_request::{sign, SigningSettings, SigningParams, SignableRequest}; +use http; +use secrecy::{SecretString, ExposeSecret}; +{{/withAWSV4Signature}} +{{#supportTokenSource}} +use std::sync::Arc; +use google_cloud_token::TokenSource; +use async_trait::async_trait; +{{/supportTokenSource}} + +#[derive(Debug, Clone)] +pub struct Configuration { + pub base_path: String, + pub user_agent: Option, + pub client: {{#supportMiddleware}}reqwest_middleware::ClientWithMiddleware{{/supportMiddleware}}{{^supportMiddleware}}reqwest{{^supportAsync}}::blocking{{/supportAsync}}::Client{{/supportMiddleware}}, + {{^supportTokenSource}} + pub basic_auth: Option, + pub oauth_access_token: Option, + pub bearer_access_token: Option, + pub api_key: Option, + {{/supportTokenSource}} + {{#withAWSV4Signature}} + pub aws_v4_key: Option, + {{/withAWSV4Signature}} + {{#supportAsync}} + {{#supportTokenSource}} + pub token_source: Arc, + {{/supportTokenSource}} + {{/supportAsync}} +} +{{^supportTokenSource}} + +pub type BasicAuth = (String, Option); + +#[derive(Debug, Clone)] +pub struct ApiKey { + pub prefix: Option, + pub key: String, +} +{{/supportTokenSource}} + +{{#withAWSV4Signature}} +#[derive(Debug, Clone)] +pub struct AWSv4Key { + pub access_key: String, + pub secret_key: SecretString, + pub region: String, + pub service: String, +} + +impl AWSv4Key { + pub fn sign(&self, uri: &str, method: &str, body: &str) -> Result, aws_sigv4::http_request::Error> { + let request = http::Request::builder() + .uri(uri) + .method(method) + .body(body).unwrap(); + let signing_settings = SigningSettings::default(); + let signing_params = SigningParams::builder() + .access_key(self.access_key.as_str()) + .secret_key(self.secret_key.expose_secret().as_str()) + .region(self.region.as_str()) + .service_name(self.service.as_str()) + .time(SystemTime::now()) + .settings(signing_settings) + .build() + .unwrap(); + let signable_request = SignableRequest::from(&request); + let (mut signing_instructions, _signature) = sign(signable_request, &signing_params)?.into_parts(); + let mut additional_headers = Vec::<(String, String)>::new(); + if let Some(new_headers) = signing_instructions.take_headers() { + for (name, value) in new_headers.into_iter() { + additional_headers.push((name.expect("header should have name").to_string(), + value.to_str().expect("header value should be a string").to_string())); + } + } + Ok(additional_headers) + } +} +{{/withAWSV4Signature}} + +impl Configuration { + pub fn new() -> Configuration { + Configuration::default() + } +} + +impl Default for Configuration { + fn default() -> Self { + Configuration { + base_path: "{{{basePath}}}".to_owned(), + user_agent: {{#httpUserAgent}}Some("{{{.}}}".to_owned()){{/httpUserAgent}}{{^httpUserAgent}}Some("OpenAPI-Generator/{{{version}}}/rust".to_owned()){{/httpUserAgent}}, + client: {{#supportMiddleware}}reqwest_middleware::ClientBuilder::new(reqwest{{^supportAsync}}::blocking{{/supportAsync}}::Client::new()).build(){{/supportMiddleware}}{{^supportMiddleware}}reqwest{{^supportAsync}}::blocking{{/supportAsync}}::Client::new(){{/supportMiddleware}}, + {{^supportTokenSource}} + basic_auth: None, + oauth_access_token: None, + bearer_access_token: None, + api_key: None, + {{/supportTokenSource}} + {{#withAWSV4Signature}} + aws_v4_key: None, + {{/withAWSV4Signature}} + {{#supportTokenSource}} + token_source: Arc::new(NoopTokenSource{}), + {{/supportTokenSource}} + } + } +} +{{#supportTokenSource}} +#[derive(Debug)] +struct NoopTokenSource{} + +#[async_trait] +impl TokenSource for NoopTokenSource { + async fn token(&self) -> Result> { + panic!("This is dummy token source. You can use TokenSourceProvider from 'google_cloud_auth' crate, or any other compatible crate.") + } +} +{{/supportTokenSource}} diff --git a/openapi.yml b/openapi.yml index 3bac4f6..9a878ed 100644 --- a/openapi.yml +++ b/openapi.yml @@ -2,7 +2,23 @@ openapi: 3.0.3 info: title: Typesense API description: "An open source search engine for building delightful search experiences." - version: 0.25.0 + version: '30.0' + license: + name: GPL-3.0 + url: https://opensource.org/licenses/GPL-3.0 +servers: + - url: "{protocol}://{hostname}:{port}" + description: Typesense Server + variables: + protocol: + default: http + description: The protocol of your Typesense server + hostname: + default: localhost + description: The hostname of your Typesense server + port: + default: "8108" + description: The port of your Typesense server externalDocs: description: Find out more about Typsesense url: https://typesense.org @@ -19,8 +35,8 @@ tags: externalDocs: description: Find out more url: https://typesense.org/api/#index-document - - name: promote - description: Promote certain documents over others + - name: curation + description: Hand-curate search results based on conditional business rules externalDocs: description: Find out more url: https://typesense.org/docs/0.23.0/api/#curation @@ -28,7 +44,7 @@ tags: description: Typesense can aggregate search queries for both analytics purposes and for query suggestions. externalDocs: description: Find out more - url: https://typesense.org/docs/0.25.0/api/analytics-query-suggestions.html + url: https://typesense.org/docs/28.0/api/analytics-query-suggestions.html - name: keys description: Manage API Keys with fine-grain access control externalDocs: @@ -40,7 +56,37 @@ tags: description: Manage Typesense cluster externalDocs: description: Find out more - url: https://typesense.org/docs/0.23.0/api/#cluster-operations + url: https://typesense.org/docs/28.0/api/cluster-operations.html + - name: stopwords + description: Manage stopwords sets + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/stopwords.html + - name: presets + description: Store and reference search parameters + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/search.html#presets + - name: conversations + description: Conversational Search (RAG) + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/conversational-search-rag.html + - name: synonyms + description: Manage synonyms + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/synonyms.html + - name: stemming + description: Manage stemming dictionaries + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/stemming.html + - name: nl_search_models + description: Manage NL search models + externalDocs: + description: Find out more + url: https://typesense.org/docs/29.0/api/natural-language-search.html paths: /collections: @@ -53,8 +99,25 @@ paths: returned sorted by creation date, with the most recent collections appearing first. operationId: getCollections + parameters: + - name: getCollectionsParameters + in: query + schema: + type: object + properties: + exclude_fields: + description: Comma-separated list of fields from the collection to exclude from the response + type: string + limit: + description: > + Number of collections to fetch. + Default: returns all collections. + type: integer + offset: + description: Identifies the starting point to return collections when paginating. + type: integer responses: - 200: + '200': description: List of all collections content: application/json: @@ -79,19 +142,19 @@ paths: $ref: "#/components/schemas/CollectionSchema" required: true responses: - 201: + '201': description: Collection successfully created content: application/json: schema: $ref: "#/components/schemas/CollectionResponse" - 400: + '400': description: Bad request, see error message for details content: application/json: schema: $ref: "#/components/schemas/ApiResponse" - 409: + '409': description: Collection already exists content: application/json: @@ -112,13 +175,13 @@ paths: schema: type: string responses: - 200: + '200': description: Collection fetched content: application/json: schema: $ref: "#/components/schemas/CollectionResponse" - 404: + '404': description: Collection not found content: application/json: @@ -146,19 +209,19 @@ paths: $ref: "#/components/schemas/CollectionUpdateSchema" required: true responses: - 200: + '200': description: The updated partial collection schema content: application/json: schema: $ref: "#/components/schemas/CollectionUpdateSchema" - 400: + '400': description: Bad request, see error message for details content: application/json: schema: $ref: "#/components/schemas/ApiResponse" - 404: + '404': description: The collection was not found content: application/json: @@ -180,13 +243,13 @@ paths: schema: type: string responses: - 200: + '200': description: Collection deleted content: application/json: schema: $ref: "#/components/schemas/CollectionResponse" - 404: + '404': description: Collection not found content: application/json: @@ -214,8 +277,12 @@ paths: schema: type: string example: upsert - enum: - - upsert + $ref: "#/components/schemas/IndexAction" + - name: dirty_values + in: query + description: Dealing with Dirty Data + schema: + $ref: "#/components/schemas/DirtyValues" requestBody: description: The document object to be indexed content: @@ -226,14 +293,14 @@ paths: x-go-type: "interface{}" required: true responses: - 201: + '201': description: Document successfully created/indexed content: application/json: schema: type: object description: Can be any key-value pair - 404: + '404': description: Collection not found content: application/json: @@ -320,6 +387,8 @@ paths: in: query schema: type: object + required: + - filter_by properties: filter_by: type: string @@ -330,8 +399,13 @@ paths: at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. type: integer + ignore_not_found: + type: boolean + truncate: + description: When true, removes all documents from the collection while preserving the collection and its schema. + type: boolean responses: - 200: + '200': description: Documents successfully deleted content: application/json: @@ -342,7 +416,7 @@ paths: properties: num_deleted: type: integer - 404: + '404': description: Collection not found content: application/json: @@ -368,19 +442,19 @@ paths: schema: $ref: "#/components/schemas/SearchParameters" responses: - 200: + '200': description: Search results content: application/json: schema: $ref: "#/components/schemas/SearchResult" - 400: + '400': description: Bad request, see error message for details content: application/json: schema: $ref: "#/components/schemas/ApiResponse" - 404: + '404': description: The collection or field was not found content: application/json: @@ -390,7 +464,7 @@ paths: get: tags: - documents - - promote + - curation summary: List all collection overrides operationId: getSearchOverrides parameters: @@ -401,7 +475,7 @@ paths: schema: type: string responses: - 200: + '200': description: List of all search overrides content: application/json: @@ -429,7 +503,7 @@ paths: schema: type: string responses: - 200: + '200': description: Search override fetched content: application/json: @@ -438,7 +512,7 @@ paths: put: tags: - documents - - promote + - curation summary: Create or update an override to promote certain documents over others description: Create or update an override to promote certain documents over others. @@ -465,13 +539,13 @@ paths: $ref: "#/components/schemas/SearchOverrideSchema" required: true responses: - 200: + '200': description: Created/updated search override content: application/json: schema: $ref: "#/components/schemas/SearchOverride" - 404: + '404': description: Search override not found content: application/json: @@ -480,7 +554,7 @@ paths: delete: tags: - documents - - promote + - curation summary: Delete an override associated with a collection operationId: deleteSearchOverride parameters: @@ -497,143 +571,118 @@ paths: schema: type: string responses: - 200: + '200': description: The ID of the deleted search override content: application/json: schema: - $ref: "#/components/schemas/SearchOverride" - 404: + $ref: "#/components/schemas/SearchOverrideDeleteResponse" + '404': description: Search override not found content: application/json: schema: $ref: "#/components/schemas/ApiResponse" - /collections/{collectionName}/synonyms: + + /synonym_sets: get: tags: - - documents - summary: List all collection synonyms - operationId: getSearchSynonyms - parameters: - - name: collectionName - in: path - description: The name of the collection - required: true - schema: - type: string + - synonyms + summary: List all synonym sets + description: Retrieve all synonym sets + operationId: retrieveSynonymSets responses: - 200: - description: List of all search synonyms + "200": + description: List of all synonym sets content: application/json: schema: - $ref: "#/components/schemas/SearchSynonymsResponse" - 404: - description: Search synonyms was not found - content: - application/json: - schema: - $ref: "#/components/schemas/ApiResponse" - /collections/{collectionName}/synonyms/{synonymId}: + type: array + items: + $ref: "#/components/schemas/SynonymSetSchema" + + /synonym_sets/{synonymSetName}: get: tags: - - documents - summary: Retrieve a single search synonym - description: Retrieve the details of a search synonym, given its id. - operationId: getSearchSynonym + - synonyms + summary: Retrieve a synonym set + description: Retrieve a specific synonym set by its name + operationId: retrieveSynonymSet parameters: - - name: collectionName - in: path - description: The name of the collection - required: true - schema: - type: string - - name: synonymId + - name: synonymSetName in: path - description: The id of the search synonym + description: The name of the synonym set to retrieve required: true schema: type: string responses: - 200: - description: Search synonym fetched + "200": + description: Synonym set fetched content: application/json: schema: - $ref: "#/components/schemas/SearchSynonym" - 404: - description: Search synonym was not found + $ref: "#/components/schemas/SynonymSetRetrieveSchema" + "404": + description: Synonym set not found content: application/json: schema: $ref: "#/components/schemas/ApiResponse" put: tags: - - documents - summary: Create or update a synonym - description: Create or update a synonym to define search terms that should be considered equivalent. - operationId: upsertSearchSynonym + - synonyms + summary: Create or update a synonym set + description: Create or update a synonym set with the given name + operationId: upsertSynonymSet parameters: - - name: collectionName - in: path - description: The name of the collection - required: true - schema: - type: string - - name: synonymId + - name: synonymSetName in: path - description: The ID of the search synonym to create/update + description: The name of the synonym set to create/update required: true schema: type: string requestBody: - description: The search synonym object to be created/updated + description: The synonym set to be created/updated content: application/json: schema: - $ref: "#/components/schemas/SearchSynonymSchema" + $ref: "#/components/schemas/SynonymSetCreateSchema" required: true responses: - 200: - description: Created/updated search synonym + "200": + description: Synonym set successfully created/updated content: application/json: schema: - $ref: "#/components/schemas/SearchSynonym" - 404: - description: Search synonym was not found + $ref: "#/components/schemas/SynonymSetSchema" + "400": + description: Bad request, see error message for details content: application/json: schema: $ref: "#/components/schemas/ApiResponse" delete: tags: - - documents - summary: Delete a synonym associated with a collection - operationId: deleteSearchSynonym + - synonyms + summary: Delete a synonym set + description: Delete a specific synonym set by its name + operationId: deleteSynonymSet parameters: - - name: collectionName - in: path - description: The name of the collection - required: true - schema: - type: string - - name: synonymId + - name: synonymSetName in: path - description: The ID of the search synonym to delete + description: The name of the synonym set to delete required: true schema: type: string responses: - 200: - description: The ID of the deleted search synonym + "200": + description: Synonym set successfully deleted content: application/json: schema: - $ref: "#/components/schemas/SearchSynonym" - 404: - description: Search synonym not found + $ref: "#/components/schemas/SynonymSetDeleteSchema" + "404": + description: Synonym set not found content: application/json: schema: @@ -657,9 +706,6 @@ paths: in: query schema: type: object - required: - - include_fields - - exclude_fields properties: filter_by: description: @@ -674,7 +720,7 @@ paths: type: string responses: - 200: + '200': description: Exports all the documents in a given collection. content: application/octet-stream: @@ -684,7 +730,7 @@ paths: {"id": "124", "company_name": "Stark Industries", "num_employees": 5215, "country": "US"} {"id": "125", "company_name": "Future Technology", "num_employees": 1232,"country": "UK"} {"id": "126", "company_name": "Random Corp.", "num_employees": 531,"country": "AU"} - 404: + '404': description: The collection was not found content: application/json: @@ -707,24 +753,28 @@ paths: required: true schema: type: string + # Do not change the index position of this param - name: importDocumentsParameters in: query schema: type: object properties: - action: - type: string batch_size: type: integer - dirty_values: - type: string - enum: - - coerce_or_reject - - coerce_or_drop - - drop - - reject + return_id: + type: boolean + description: + Returning the id of the imported documents. If you want the + import response to return the ingested document's id in the + response, you can use the return_id parameter. remote_embedding_batch_size: type: integer + return_doc: + type: boolean + action: + $ref: "#/components/schemas/IndexAction" + dirty_values: + $ref: "#/components/schemas/DirtyValues" requestBody: description: The json array of documents or the JSONL file to import content: @@ -734,7 +784,7 @@ paths: description: The JSONL file to import required: true responses: - 200: + '200': description: Result of the import operation. Each line of the response indicates the result of each document present in the request body (in the same order). If the import @@ -748,13 +798,13 @@ paths: example: | {"success": true} {"success": false, "error": "Bad JSON.", "document": "[bad doc"} - 400: + '400': description: Bad request, see error message for details content: application/json: schema: $ref: "#/components/schemas/ApiResponse" - 404: + '404': description: The collection was not found content: application/json: @@ -764,7 +814,7 @@ paths: get: tags: - documents - summary: Retreive a document + summary: Retrieve a document description: Fetch an individual document from a collection by using its ID. operationId: getDocument parameters: @@ -781,14 +831,14 @@ paths: schema: type: string responses: - 200: + '200': description: The document referenced by the ID content: application/json: schema: type: object description: Can be any key-value pair - 404: + '404': description: The document or collection was not found content: application/json: @@ -815,6 +865,11 @@ paths: required: true schema: type: string + - name: dirty_values + in: query + description: Dealing with Dirty Data + schema: + $ref: "#/components/schemas/DirtyValues" requestBody: description: The document object with fields to be updated content: @@ -825,14 +880,14 @@ paths: x-go-type: "interface{}" required: true responses: - 200: + '200': description: The document referenced by the ID was updated content: application/json: schema: type: object description: Can be any key-value pair - 404: + '404': description: The document or collection was not found content: application/json: @@ -858,19 +913,128 @@ paths: schema: type: string responses: - 200: + '200': description: The document referenced by the ID was deleted content: application/json: schema: type: object description: Can be any key-value pair - 404: + '404': description: The document or collection was not found content: application/json: schema: $ref: "#/components/schemas/ApiResponse" + /conversations/models: + get: + description: Retrieve all conversation models + operationId: retrieveAllConversationModels + responses: + '200': + content: + application/json: + schema: + items: + $ref: '#/components/schemas/ConversationModelSchema' + type: array + x-go-type: '[]*ConversationModelSchema' + description: List of all conversation models + summary: List all conversation models + tags: + - conversations + post: + summary: Create a conversation model + description: Create a Conversation Model + operationId: createConversationModel + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelCreateSchema' + required: true + responses: + '201': + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelSchema' + description: Created Conversation Model + '400': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Bad request, see error message for details + tags: + - conversations + /conversations/models/{modelId}: + get: + description: Retrieve a conversation model + operationId: retrieveConversationModel + parameters: + - name: modelId + in: path + description: The id of the conversation model to retrieve + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelSchema' + description: A conversation model + summary: Retrieve a conversation model + tags: + - conversations + put: + description: Update a conversation model + operationId: updateConversationModel + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelUpdateSchema' + required: true + parameters: + - name: modelId + in: path + description: The id of the conversation model to update + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelSchema' + description: The conversation model was successfully updated + summary: Update a conversation model + tags: + - conversations + delete: + description: Delete a conversation model + operationId: deleteConversationModel + parameters: + - name: modelId + in: path + description: The id of the conversation model to delete + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelSchema' + description: The conversation model was successfully deleted + summary: Delete a conversation model + tags: + - conversations /keys: get: tags: @@ -878,7 +1042,7 @@ paths: summary: Retrieve (metadata about) all keys. operationId: getKeys responses: - 200: + '200': description: List of all keys content: application/json: @@ -901,19 +1065,19 @@ paths: schema: $ref: "#/components/schemas/ApiKeySchema" responses: - 201: + '201': description: Created API key content: application/json: schema: $ref: "#/components/schemas/ApiKey" - 400: + '400': description: Bad request, see error message for details content: application/json: schema: $ref: "#/components/schemas/ApiResponse" - 409: + '409': description: API key generation conflict content: application/json: @@ -938,13 +1102,13 @@ paths: type: integer format: int64 responses: - 200: + '200': description: The key referenced by the ID content: application/json: schema: $ref: "#/components/schemas/ApiKey" - 404: + '404': description: The key was not found content: application/json: @@ -964,19 +1128,19 @@ paths: type: integer format: int64 responses: - 200: + '200': description: The key referenced by the ID content: application/json: schema: - $ref: "#/components/schemas/ApiKey" - 400: + $ref: "#/components/schemas/ApiKeyDeleteResponse" + '400': description: Bad request, see error message for details content: application/json: schema: $ref: "#/components/schemas/ApiResponse" - 404: + '404': description: Key not found content: application/json: @@ -990,7 +1154,7 @@ paths: description: List all aliases and the corresponding collections that they map to. operationId: getAliases responses: - 200: + '200': description: List of all collection aliases content: application/json: @@ -1022,19 +1186,19 @@ paths: schema: $ref: "#/components/schemas/CollectionAliasSchema" responses: - 200: + '200': description: The collection alias was created/updated content: application/json: schema: $ref: "#/components/schemas/CollectionAlias" - 400: + '400': description: Bad request, see error message for details content: application/json: schema: $ref: "#/components/schemas/ApiResponse" - 404: + '404': description: Alias not found content: application/json: @@ -1054,13 +1218,13 @@ paths: schema: type: string responses: - 200: + '200': description: Collection alias fetched content: application/json: schema: $ref: "#/components/schemas/CollectionAlias" - 404: + '404': description: The alias was not found content: application/json: @@ -1079,13 +1243,13 @@ paths: schema: type: string responses: - 200: + '200': description: Collection alias was deleted content: application/json: schema: $ref: "#/components/schemas/CollectionAlias" - 404: + '404': description: Alias not found content: application/json: @@ -1099,7 +1263,7 @@ paths: description: Print debugging information operationId: debug responses: - 200: + '200': description: Debugging information content: application/json: @@ -1116,12 +1280,28 @@ paths: description: Checks if Typesense server is ready to accept requests. operationId: health responses: - 200: + '200': description: Search service is ready for requests. content: application/json: schema: $ref: "#/components/schemas/HealthStatus" + /operations/schema_changes: + get: + tags: + - operations + summary: Get the status of in-progress schema change operations + description: Returns the status of any ongoing schema change operations. If no schema changes are in progress, returns an empty response. + operationId: getSchemaChanges + responses: + '200': + description: List of schema changes in progress + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/SchemaChangeStatus" /operations/snapshot: post: tags: @@ -1140,7 +1320,7 @@ paths: schema: type: string responses: - 201: + '201': description: Snapshot is created. content: application/json: @@ -1157,12 +1337,72 @@ paths: once this command succeeds. operationId: vote responses: - 200: + '200': description: Re-election is performed. content: application/json: schema: $ref: "#/components/schemas/SuccessStatus" + /operations/cache/clear: + post: + tags: + - operations + summary: Clear the cached responses of search requests in the LRU cache. + description: + Clear the cached responses of search requests that are sent with `use_cache` parameter in the LRU cache. + operationId: clearCache + responses: + '200': + description: Clear cache succeeded. + content: + application/json: + schema: + $ref: "#/components/schemas/SuccessStatus" + /operations/db/compact: + post: + tags: + - operations + summary: Compacting the on-disk database + description: + Typesense uses RocksDB to store your documents on the disk. If you do frequent writes or updates, you could benefit from running a compaction of the underlying RocksDB database. + This could reduce the size of the database and decrease read latency. While the database will not block during this operation, we recommend running it during off-peak hours. + operationId: compactDb + responses: + '200': + description: Compacting the on-disk database succeeded. + content: + application/json: + schema: + $ref: "#/components/schemas/SuccessStatus" + /config: + post: + tags: + - operations + summary: Toggle Slow Request Log + description: + Enable logging of requests that take over a defined threshold of time. + Default is `-1` which disables slow request logging. + Slow requests are logged to the primary log file, with the prefix SLOW REQUEST. + operationId: toggleSlowRequestLog + requestBody: + content: + application/json: + schema: + type: object + properties: + log-slow-requests-time-ms: + type: integer + required: + - log-slow-requests-time-ms + example: | + {"log-slow-requests-time-ms": 2000} + responses: + '200': + description: Compacting the on-disk database succeeded. + content: + application/json: + schema: + $ref: "#/components/schemas/SuccessStatus" /multi_search: post: operationId: multiSearch @@ -1184,61 +1424,207 @@ paths: schema: $ref: "#/components/schemas/MultiSearchSearchesParameter" responses: - 200: + '200': description: Search results content: application/json: schema: $ref: "#/components/schemas/MultiSearchResult" - 400: + '400': description: Bad request, see error message for details content: application/json: schema: $ref: "#/components/schemas/ApiResponse" - /analytics/rules: + /analytics/events: post: tags: - analytics - summary: Creates an analytics rule - description: - When an analytics rule is created, we give it a name and describe the type, the source collections and the destination collection. - operationId: createAnalyticsRule + summary: Create an analytics event + description: Submit a single analytics event. The event must correspond to an existing analytics rule by name. + operationId: createAnalyticsEvent requestBody: - description: The Analytics rule to be created + description: The analytics event to be created content: application/json: schema: - $ref: "#/components/schemas/AnalyticsRuleSchema" + $ref: '#/components/schemas/AnalyticsEvent' required: true responses: - 201: - description: Analytics rule successfully created + '200': + description: Analytics event successfully created content: application/json: schema: - $ref: "#/components/schemas/AnalyticsRuleSchema" - 400: + $ref: '#/components/schemas/AnalyticsEventCreateResponse' + '400': description: Bad request, see error message for details content: application/json: schema: - $ref: "#/components/schemas/ApiResponse" + $ref: '#/components/schemas/ApiResponse' get: tags: - analytics - summary: Retrieves all analytics rules - description: - Retrieve the details of all analytics rules - operationId: retrieveAnalyticsRules - responses: - 200: - description: Analytics rules fetched + summary: Retrieve analytics events + description: Retrieve the most recent events for a user and rule. + operationId: getAnalyticsEvents + parameters: + - name: user_id + in: query + required: true + schema: + type: string + - name: name + in: query + description: Analytics rule name + required: true + schema: + type: string + - name: n + in: query + description: Number of events to return (max 1000) + required: true + schema: + type: integer + responses: + '200': + description: Events fetched + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsEventsResponse' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /analytics/flush: + post: + tags: + - analytics + summary: Flush in-memory analytics to disk + description: Triggers a flush of analytics data to persistent storage. + operationId: flushAnalytics + responses: + '200': + description: Flush triggered + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsEventCreateResponse' + /analytics/status: + get: + tags: + - analytics + summary: Get analytics subsystem status + description: Returns sizes of internal analytics buffers and queues. + operationId: getAnalyticsStatus + responses: + '200': + description: Status fetched content: application/json: schema: - $ref: "#/components/schemas/AnalyticsRulesRetrieveSchema" + $ref: '#/components/schemas/AnalyticsStatus' + /analytics/rules: + post: + tags: + - analytics + summary: Create analytics rule(s) + description: Create one or more analytics rules. You can send a single rule object or an array of rule objects. + operationId: createAnalyticsRule + requestBody: + description: The analytics rule(s) to be created + content: + application/json: + schema: + oneOf: + - $ref: "#/components/schemas/AnalyticsRuleCreate" + - type: array + items: + $ref: "#/components/schemas/AnalyticsRuleCreate" + required: true + responses: + '200': + description: Analytics rule(s) successfully created + content: + application/json: + schema: + oneOf: + - $ref: "#/components/schemas/AnalyticsRule" + - type: array + items: + anyOf: + - $ref: "#/components/schemas/AnalyticsRule" + - type: object + properties: + error: + type: string + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + get: + tags: + - analytics + summary: Retrieve analytics rules + description: Retrieve all analytics rules. Use the optional rule_tag filter to narrow down results. + operationId: retrieveAnalyticsRules + parameters: + - in: query + name: rule_tag + schema: + type: string + required: false + description: Filter rules by rule_tag + responses: + '200': + description: Analytics rules fetched + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/AnalyticsRule" /analytics/rules/{ruleName}: + put: + tags: + - analytics + summary: Upserts an analytics rule + description: + Upserts an analytics rule with the given name. + operationId: upsertAnalyticsRule + parameters: + - in: path + name: ruleName + description: The name of the analytics rule to upsert + schema: + type: string + required: true + requestBody: + description: The Analytics rule to be upserted + content: + application/json: + schema: + $ref: "#/components/schemas/AnalyticsRuleUpdate" + required: true + responses: + '200': + description: Analytics rule successfully upserted + content: + application/json: + schema: + $ref: "#/components/schemas/AnalyticsRule" + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" get: tags: - analytics @@ -1254,13 +1640,13 @@ paths: type: string required: true responses: - 200: + '200': description: Analytics rule fetched content: application/json: schema: - $ref: "#/components/schemas/AnalyticsRuleSchema" - 404: + $ref: "#/components/schemas/AnalyticsRule" + '404': description: Analytics rule not found content: application/json: @@ -1281,18 +1667,491 @@ paths: type: string required: true responses: - 200: + '200': description: Analytics rule deleted content: application/json: schema: - $ref: "#/components/schemas/AnalyticsRuleSchema" - 404: + $ref: "#/components/schemas/AnalyticsRule" + '404': description: Analytics rule not found content: application/json: schema: $ref: "#/components/schemas/ApiResponse" + /metrics.json: + get: + tags: + - operations + summary: Get current RAM, CPU, Disk & Network usage metrics. + description: + Retrieve the metrics. + operationId: retrieveMetrics + responses: + '200': + description: Metrics fetched. + content: + application/json: + schema: + type: object + /stats.json: + get: + tags: + - operations + summary: Get stats about API endpoints. + description: + Retrieve the stats about API endpoints. + operationId: retrieveAPIStats + responses: + '200': + description: Stats fetched. + content: + application/json: + schema: + $ref: "#/components/schemas/APIStatsResponse" + /stopwords: + get: + tags: + - stopwords + summary: Retrieves all stopwords sets. + description: + Retrieve the details of all stopwords sets + operationId: retrieveStopwordsSets + responses: + '200': + description: Stopwords sets fetched. + content: + application/json: + schema: + $ref: "#/components/schemas/StopwordsSetsRetrieveAllSchema" + /stopwords/{setId}: + put: + tags: + - stopwords + summary: Upserts a stopwords set. + description: + When an analytics rule is created, we give it a name and describe the type, the source collections and the destination collection. + operationId: upsertStopwordsSet + parameters: + - in: path + name: setId + description: The ID of the stopwords set to upsert. + schema: + type: string + required: true + example: countries + requestBody: + description: The stopwords set to upsert. + content: + application/json: + schema: + $ref: "#/components/schemas/StopwordsSetUpsertSchema" + required: true + responses: + '200': + description: Stopwords set successfully upserted. + content: + application/json: + schema: + $ref: "#/components/schemas/StopwordsSetSchema" + '400': + description: Bad request, see error message for details. + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + get: + tags: + - stopwords + summary: Retrieves a stopwords set. + description: + Retrieve the details of a stopwords set, given it's name. + operationId: retrieveStopwordsSet + parameters: + - in: path + name: setId + description: The ID of the stopwords set to retrieve. + schema: + type: string + required: true + example: countries + responses: + '200': + description: Stopwords set fetched. + content: + application/json: + schema: + $ref: "#/components/schemas/StopwordsSetRetrieveSchema" + '404': + description: Stopwords set not found. + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + delete: + tags: + - stopwords + summary: Delete a stopwords set. + description: + Permanently deletes a stopwords set, given it's name. + operationId: deleteStopwordsSet + parameters: + - in: path + name: setId + description: The ID of the stopwords set to delete. + schema: + type: string + required: true + example: countries + responses: + '200': + description: Stopwords set rule deleted. + content: + application/json: + schema: + type: object + properties: + id: + type: string + required: + - id + example: | + {"id": "countries"} + '404': + description: Stopwords set not found. + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + /presets: + get: + tags: + - presets + summary: Retrieves all presets. + description: Retrieve the details of all presets + operationId: retrieveAllPresets + responses: + '200': + description: Presets fetched. + content: + application/json: + schema: + $ref: '#/components/schemas/PresetsRetrieveSchema' + /presets/{presetId}: + get: + tags: + - presets + summary: Retrieves a preset. + description: Retrieve the details of a preset, given it's name. + operationId: retrievePreset + parameters: + - in: path + name: presetId + description: The ID of the preset to retrieve. + schema: + type: string + required: true + example: listing_view + responses: + '200': + description: Preset fetched. + content: + application/json: + schema: + $ref: '#/components/schemas/PresetSchema' + '404': + description: Preset not found. + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + put: + tags: + - presets + summary: Upserts a preset. + description: Create or update an existing preset. + operationId: upsertPreset + parameters: + - in: path + name: presetId + description: The name of the preset set to upsert. + schema: + type: string + required: true + example: listing_view + requestBody: + description: The stopwords set to upsert. + content: + application/json: + schema: + $ref: '#/components/schemas/PresetUpsertSchema' + required: true + responses: + '200': + description: Preset successfully upserted. + content: + application/json: + schema: + $ref: '#/components/schemas/PresetSchema' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - presets + summary: Delete a preset. + description: Permanently deletes a preset, given it's name. + operationId: deletePreset + parameters: + - in: path + name: presetId + description: The ID of the preset to delete. + schema: + type: string + required: true + example: listing_view + responses: + '200': + description: Preset deleted. + content: + application/json: + schema: + $ref: '#/components/schemas/PresetDeleteSchema' + '404': + description: Preset not found. + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /stemming/dictionaries: + get: + tags: + - stemming + summary: List all stemming dictionaries + description: Retrieve a list of all available stemming dictionaries. + operationId: listStemmingDictionaries + responses: + '200': + description: List of all dictionaries + content: + application/json: + schema: + type: object + properties: + dictionaries: + type: array + items: + type: string + example: ["irregular-plurals", "company-terms"] + + /stemming/dictionaries/{dictionaryId}: + get: + tags: + - stemming + summary: Retrieve a stemming dictionary + description: Fetch details of a specific stemming dictionary. + operationId: getStemmingDictionary + parameters: + - name: dictionaryId + in: path + description: The ID of the dictionary to retrieve + required: true + schema: + type: string + example: irregular-plurals + responses: + '200': + description: Stemming dictionary details + content: + application/json: + schema: + $ref: "#/components/schemas/StemmingDictionary" + '404': + description: Dictionary not found + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + + /stemming/dictionaries/import: + post: + tags: + - stemming + summary: Import a stemming dictionary + description: Upload a JSONL file containing word mappings to create or update a stemming dictionary. + operationId: importStemmingDictionary + parameters: + - name: id + in: query + description: The ID to assign to the dictionary + required: true + schema: + type: string + example: irregular-plurals + requestBody: + description: The JSONL file containing word mappings + required: true + content: + application/json: + schema: + type: string + example: | + {"word": "people", "root": "person"} + {"word": "children", "root": "child"} + responses: + '200': + description: Dictionary successfully imported + content: + application/octet-stream: + schema: + type: string + example: > + {"word": "people", "root": "person"} + {"word": "children", "root": "child"} + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + /nl_search_models: + get: + tags: + - nl_search_models + summary: List all NL search models + description: Retrieve all NL search models. + operationId: retrieveAllNLSearchModels + responses: + '200': + description: List of all NL search models + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/NLSearchModelSchema' + post: + tags: + - nl_search_models + summary: Create a NL search model + description: Create a new NL search model. + operationId: createNLSearchModel + requestBody: + description: The NL search model to be created + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelCreateSchema' + required: true + responses: + '201': + description: NL search model successfully created + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelSchema' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /nl_search_models/{modelId}: + get: + tags: + - nl_search_models + summary: Retrieve a NL search model + description: Retrieve a specific NL search model by its ID. + operationId: retrieveNLSearchModel + parameters: + - name: modelId + in: path + description: The ID of the NL search model to retrieve + required: true + schema: + type: string + responses: + '200': + description: NL search model fetched + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelSchema' + '404': + description: NL search model not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + put: + tags: + - nl_search_models + summary: Update a NL search model + description: Update an existing NL search model. + operationId: updateNLSearchModel + parameters: + - name: modelId + in: path + description: The ID of the NL search model to update + required: true + schema: + type: string + requestBody: + description: The NL search model fields to update + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelUpdateSchema' + required: true + responses: + '200': + description: NL search model successfully updated + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelSchema' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + '404': + description: NL search model not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - nl_search_models + summary: Delete a NL search model + description: Delete a specific NL search model by its ID. + operationId: deleteNLSearchModel + parameters: + - name: modelId + in: path + description: The ID of the NL search model to delete + required: true + schema: + type: string + responses: + '200': + description: NL search model successfully deleted + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelDeleteSchema' + '404': + description: NL search model not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + components: schemas: CollectionSchema: @@ -1331,7 +2190,7 @@ components: token_separators: type: array description: > - List of symbols or special characters to be used for + List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. items: type: string # characters only @@ -1340,13 +2199,19 @@ components: minLength: 1 maxLength: 1 default: [] + synonym_sets: + type: array + description: List of synonym set names to associate with this collection + items: + type: string + example: "synonym_set_1" enable_nested_fields: - type: boolean - description: - Enables experimental support at a collection level for nested object or object array fields. - This field is only available if the Typesense server is version `0.24.0.rcn34` or later. - default: false - example: true + type: boolean + description: + Enables experimental support at a collection level for nested object or object array fields. + This field is only available if the Typesense server is version `0.24.0.rcn34` or later. + default: false + example: true symbols_to_index: type: array description: > @@ -1358,6 +2223,12 @@ components: minLength: 1 maxLength: 1 default: [] + voice_query_model: + $ref: "#/components/schemas/VoiceQueryModelCollectionConfig" + metadata: + type: object + description: > + Optional details about the collection, e.g., when it was created, who created it etc. CollectionUpdateSchema: required: - fields @@ -1378,6 +2249,16 @@ components: facet: true items: $ref: "#/components/schemas/Field" + synonym_sets: + type: array + description: List of synonym set names to associate with this collection + items: + type: string + example: "synonym_set_1" + metadata: + type: object + description: > + Optional details about the collection, e.g., when it was created, who created it etc. CollectionResponse: allOf: - $ref: "#/components/schemas/CollectionSchema" @@ -1428,6 +2309,10 @@ components: type: boolean example: true default: false + reference: + type: string + description: > + Name of a field in another collection that should be linked to this collection so that it can be joined during query. num_dim: type: integer example: 256 @@ -1435,6 +2320,49 @@ components: type: boolean example: true # omitting default value since we want it to be null + store: + type: boolean + description: > + When set to false, the field value will not be stored on disk. Default: true. + vec_dist: + type: string + description: > + The distance metric to be used for vector search. Default: `cosine`. You can also use `ip` for inner product. + range_index: + type: boolean + description: > + Enables an index optimized for range filtering on numerical fields (e.g. rating:>3.5). Default: false. + stem: + type: boolean + description: > + Values are stemmed before indexing in-memory. Default: false. + stem_dictionary: + type: string + description: Name of the stemming dictionary to use for this field + example: irregular-plurals + token_separators: + type: array + description: > + List of symbols or special characters to be used for + splitting the text into individual words in addition to space and new-line characters. + items: + type: string # characters only + # Could `enum` be used instead, given it's symbols/special *characters*, e.g.: + # enum: ["@", "!", ".", "/", ","] + minLength: 1 + maxLength: 1 + default: [] + symbols_to_index: + type: array + description: > + List of symbols or special characters to be indexed. + items: + type: string # characters only + # Could `enum` be used instead, given it's symbols/special *characters*, e.g.: + # enum: ["@", "!", ".", "/", ","] + minLength: 1 + maxLength: 1 + default: [] embed: type: object required: @@ -1454,14 +2382,30 @@ components: type: string api_key: type: string + url: + type: string access_token: type: string + refresh_token: + type: string client_id: type: string client_secret: type: string project_id: type: string + indexing_prefix: + type: string + query_prefix: + type: string + VoiceQueryModelCollectionConfig: + type: object + description: > + Configuration for the voice query model + properties: + model_name: + type: string + example: "ts/whisper/base.en" CollectionAliasSchema: type: object required: @@ -1495,6 +2439,7 @@ components: $ref: "#/components/schemas/CollectionAlias" SearchResult: type: object + x-rust-generic-parameter: "" properties: facet_counts: type: array @@ -1503,6 +2448,8 @@ components: found: type: integer description: The number of documents found + found_docs: + type: integer search_time_ms: type: integer description: The number of milliseconds the search took @@ -1524,20 +2471,52 @@ components: description: The documents that matched the search query items: $ref: "#/components/schemas/SearchResultHit" + x-rust-type: "Option>>" request_params: + $ref: "#/components/schemas/SearchRequestParams" + conversation: + $ref: "#/components/schemas/SearchResultConversation" + union_request_params: + type: array + description: Returned only for union query response. + items: + $ref: "#/components/schemas/SearchRequestParams" + SearchRequestParams: + type: object + required: + - collection_name + - q + - per_page + properties: + collection_name: + type: string + q: + type: string + per_page: + type: integer + voice_query: type: object - required: - - collection_name - - q - - per_page properties: - collection_name: + transcribed_query: type: string - q: - type: string - per_page: - type: integer - + SearchResultConversation: + type: object + required: + - answer + - conversation_history + - conversation_id + - query + properties: + answer: + type: string + conversation_history: + type: array + items: + type: object + conversation_id: + type: string + query: + type: string SearchGroupedHit: type: object required: @@ -1556,6 +2535,7 @@ components: $ref: "#/components/schemas/SearchResultHit" SearchResultHit: type: object + x-rust-generic-parameter: "" properties: highlights: type: array @@ -1568,12 +2548,32 @@ components: additionalProperties: true document: type: object + x-rust-type: "Option" description: Can be any key-value pair additionalProperties: type: object text_match: type: integer format: int64 + text_match_info: + type: object + properties: + best_field_score: + type: string + best_field_weight: + type: integer + fields_matched: + type: integer + num_tokens_dropped: + type: integer + format: int64 + x-go-type: uint64 + score: + type: string + tokens_matched: + type: integer + typo_prefix_score: + type: integer geo_distance_meters: type: object description: Can be any key-value pair @@ -1583,6 +2583,17 @@ components: type: number format: float description: Distance between the query vector and matching document's vector value + hybrid_search_info: + type: object + description: Information about hybrid search scoring + properties: + rank_fusion_score: + type: number + format: float + description: Combined score from rank fusion of text and vector search + search_index: + type: integer + description: Returned only for union query response. Indicates the index of the query which this document matched to. example: highlights: company_name: @@ -1664,6 +2675,37 @@ components: type: boolean description: > Indicates whether search query tokens that exist in the override's rule should be removed from the search query. + metadata: + type: object + description: > + Return a custom JSON object in the Search API response, when this rule is triggered. This can can be used to display a pre-defined message (eg: a promotion banner) on the front-end when a particular rule is triggered. + sort_by: + type: string + description: > + A sort by clause that is applied to any search query that matches the override rule. + replace_query: + type: string + description: > + Replaces the current search query with this value, when the search query matches the override rule. + filter_curated_hits: + type: boolean + description: > + When set to true, the filter conditions of the query is applied to the curated records as well. + Default: false. + effective_from_ts: + type: integer + description: > + A Unix timestamp that indicates the date/time from which the override will be active. You can use this to create override rules that start applying from a future point in time. + effective_to_ts: + type: integer + description: > + A Unix timestamp that indicates the date/time until which the override will be active. You can use this to create override rules that stop applying after a period of time. + stop_processing: + type: boolean + description: > + When set to true, override processing will stop at the first matching rule. When set to false override processing will continue and multiple override actions will be triggered in sequence. + Overrides are processed in the lexical sort order of their id field. + Default: true. SearchOverride: allOf: - $ref: "#/components/schemas/SearchOverrideSchema" @@ -1674,12 +2716,22 @@ components: id: type: string readOnly: true - SearchOverrideRule: + SearchOverrideDeleteResponse: type: object required: - - query - - match + - id + properties: + id: + type: string + description: The id of the override that was deleted + SearchOverrideRule: + type: object properties: + tags: + type: array + description: List of tag values to associate with this override rule. + items: + type: string query: type: string description: Indicates what search queries should be overridden @@ -1692,6 +2744,10 @@ components: enum: - exact - contains + filter_by: + type: string + description: > + Indicates that the override should apply when the filter_by parameter in a search query exactly matches the string specified here (including backticks, spaces, brackets, etc). SearchOverrideInclude: type: object required: @@ -1735,6 +2791,14 @@ components: description: Array of words that should be considered as synonyms. items: type: string + locale: + type: string + description: Locale for the synonym, leave blank to use the standard tokenizer. + symbols_to_index: + type: array + description: By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is. + items: + type: string SearchSynonym: allOf: - $ref: "#/components/schemas/SearchSynonymSchema" @@ -1745,6 +2809,14 @@ components: id: type: string readOnly: true + SearchSynonymDeleteResponse: + type: object + required: + - id + properties: + id: + type: string + description: The id of the synonym that was deleted SearchSynonymsResponse: type: object required: @@ -1762,6 +2834,18 @@ components: properties: ok: type: boolean + SchemaChangeStatus: + type: object + properties: + collection: + type: string + description: Name of the collection being modified + validated_docs: + type: integer + description: Number of documents that have been validated + altered_docs: + type: integer + description: Number of documents that have been altered SuccessStatus: type: object required: @@ -1810,6 +2894,15 @@ components: value_prefix: type: string readOnly: true + ApiKeyDeleteResponse: + type: object + required: + - id + properties: + id: + type: integer + format: int64 + description: The id of the API key that was deleted ApiKeysResponse: type: object required: @@ -1820,24 +2913,6 @@ components: x-go-type: "[]*ApiKey" items: $ref: "#/components/schemas/ApiKey" - ScopedKeyParameters: - type: object - properties: - filter_by: - type: string - expires_at: - type: integer - format: int64 - SnapshotParameters: - type: object - properties: - snapshot_path: - type: string - ErrorResponse: - type: object - properties: - message: - type: string MultiSearchResult: type: object required: @@ -1846,13 +2921,23 @@ components: results: type: array items: - $ref: "#/components/schemas/SearchResult" + $ref: "#/components/schemas/MultiSearchResultItem" + conversation: + $ref: "#/components/schemas/SearchResultConversation" + MultiSearchResultItem: + allOf: + - $ref: "#/components/schemas/SearchResult" + - type: object + properties: + code: + type: integer + description: HTTP error code + format: int64 + error: + type: string + description: Error description SearchParameters: type: object - required: - - q - - query_by - properties: q: description: The query text to search for in the collection. @@ -1865,6 +2950,14 @@ components: against. Multiple fields are separated with a comma. type: string + nl_query: + description: Whether to use natural language processing to parse the query. + type: boolean + + nl_model_id: + description: The ID of the natural language model to use. + type: string + query_by_weights: description: The relative weight to give each `query_by` field when ranking results. @@ -1874,7 +2967,7 @@ components: text_match_type: description: - In a multi-field matching context, this parameter determines how the representative text match + In a multi-field matching context, this parameter determines how the representative text match score of a record is calculated. Possible values are max_score (default) or max_weight. type: string @@ -1887,36 +2980,42 @@ components: infix: description: - If infix index is enabled for this field, infix searching can be done on a per-field - basis by sending a comma separated string parameter called infix to the search query. + If infix index is enabled for this field, infix searching can be done on a per-field + basis by sending a comma separated string parameter called infix to the search query. This parameter can have 3 values; `off` infix search is disabled, which is default - `always` infix search is performed along with regular search - `fallback` infix search is performed if regular search does not produce results + `always` infix search is performed along with regular search + `fallback` infix search is performed if regular search does not produce results type: string max_extra_prefix: description: - There are also 2 parameters that allow you to control the extent of infix searching - max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before - or after the query that can be present in the token. For example query "K2100" has 2 extra + There are also 2 parameters that allow you to control the extent of infix searching + max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before + or after the query that can be present in the token. For example query "K2100" has 2 extra symbols in "6PK2100". By default, any number of prefixes/suffixes can be present for a match. type: integer max_extra_suffix: description: - There are also 2 parameters that allow you to control the extent of infix searching - max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before - or after the query that can be present in the token. For example query "K2100" has 2 extra + There are also 2 parameters that allow you to control the extent of infix searching + max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before + or after the query that can be present in the token. For example query "K2100" has 2 extra symbols in "6PK2100". By default, any number of prefixes/suffixes can be present for a match. type: integer filter_by: description: - Filter conditions for refining youropen api validator search results. Separate + Filter conditions for refining your open api validator search results. Separate multiple conditions with &&. type: string example: "num_employees:>100 && country: [USA, UK]" + max_filter_by_candidates: + description: + Controls the number of similar words that Typesense considers during fuzzy search + on filter_by values. Useful for controlling prefix matches like company_name:Acm*. + type: integer + sort_by: description: A list of numerical fields and their corresponding sort orders @@ -1963,7 +3062,7 @@ components: limit: description: > - Number of hits to fetch. Can be used as an alternative to the per_page parameter. + Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. type: integer @@ -1985,6 +3084,13 @@ components: Default: 3 type: integer + group_missing_values: + description: > + Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. + Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. + Default: true + type: boolean + include_fields: description: List of fields from the document to include in the search result type: string @@ -2021,12 +3127,24 @@ components: type: boolean default: true + enable_analytics: + description: > + Flag for enabling/disabling analytics aggregation for specific search + queries (for e.g. those originating from a test script). + type: boolean + default: true + snippet_threshold: description: > Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 type: integer + synonym_sets: + type: string + description: List of synonym set names to associate with this search query + example: "synonym_set_1,synonym_set_2" + drop_tokens_threshold: description: > If the number of results found for a specific query is less than @@ -2034,12 +3152,35 @@ components: enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 type: integer + drop_tokens_mode: + $ref: "#/components/schemas/DropTokensMode" typo_tokens_threshold: description: > If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 type: integer + enable_typos_for_alpha_numerical_tokens: + type: boolean + description: > + Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + + filter_curated_hits: + type: boolean + description: > + Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + enable_synonyms: + type: boolean + description: > + If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + synonym_prefix: + type: boolean + description: > + Allow synonym resolution on word prefixes in the query. Default: false + synonym_num_typos: + type: integer + description: > + Allow synonym resolution on typo-corrected words in the query. Default: 0 pinned_hits: description: > @@ -2051,7 +3192,7 @@ components: you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based - on rules. Overrides are applied first, followed by `pinned_hits` and + on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. type: string @@ -2066,9 +3207,13 @@ components: finally `hidden_hits`. type: string + override_tags: + description: Comma separated list of tags to trigger the curations rules that match the tags. + type: string + highlight_fields: description: > - A list of custom fields that must be highlighted even if you don't query + A list of custom fields that must be highlighted even if you don't query for them type: string @@ -2083,7 +3228,7 @@ components: pre_segmented_query: description: > You can index content from any logographic language into Typesense if you - are able to segment / split the text into space-separated words yourself + are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same @@ -2100,12 +3245,14 @@ components: If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false type: boolean + default: false prioritize_exact_match: description: > Set this parameter to true to ensure that an exact match is ranked above the others type: boolean + default: true max_candidates: description: > Control the number of words that Typesense considers for typo and prefix searching. @@ -2114,15 +3261,26 @@ components: description: > Make Typesense prioritize documents where the query words appear earlier in the text. type: boolean + default: false + prioritize_num_matching_fields: + description: > + Make Typesense prioritize documents where the query words appear in more number of fields. + type: boolean + default: true + enable_typos_for_numerical_tokens: + description: > + Make Typesense disable typos for numerical tokens. + type: boolean + default: true exhaustive_search: description: > - Setting this to true will make Typesense consider all prefixes and typo - corrections of the words in the query without stopping early when enough results are found + Setting this to true will make Typesense consider all prefixes and typo + corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). type: boolean search_cutoff_ms: description: > - Typesense will attempt to return results early if the cutoff time has elapsed. + Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. type: integer use_cache: @@ -2131,17 +3289,17 @@ components: type: boolean cache_ttl: description: > - The duration (in seconds) that determines how long the search query is cached. + The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. type: integer min_len_1typo: description: > - Minimum word length for 1-typo correction to be applied. + Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. type: integer min_len_2typo: description: > - Minimum word length for 2-typo correction to be applied. + Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. type: integer vector_query: @@ -2156,6 +3314,36 @@ components: description: > Number of times to retry fetching remote embeddings. type: integer + facet_strategy: + description: > + Choose the underlying faceting strategy used. Comma separated string of allows values: + exhaustive, top_values or automatic (default). + type: string + stopwords: + description: > + Name of the stopwords set to apply for this search, + the keywords present in the set will be removed from the search query. + type: string + facet_return_parent: + description: > + Comma separated string of nested facet fields whose parent object should be returned in facet response. + type: string + voice_query: + description: > + The base64 encoded audio file in 16 khz 16-bit WAV format. + type: string + conversation: + description: > + Enable conversational search. + type: boolean + conversation_model_id: + description: > + The Id of Conversation Model to be used. + type: string + conversation_id: + description: > + The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + type: string MultiSearchParameters: description: > @@ -2195,26 +3383,26 @@ components: infix: description: - If infix index is enabled for this field, infix searching can be done on a per-field - basis by sending a comma separated string parameter called infix to the search query. + If infix index is enabled for this field, infix searching can be done on a per-field + basis by sending a comma separated string parameter called infix to the search query. This parameter can have 3 values; `off` infix search is disabled, which is default - `always` infix search is performed along with regular search - `fallback` infix search is performed if regular search does not produce results + `always` infix search is performed along with regular search + `fallback` infix search is performed if regular search does not produce results type: string max_extra_prefix: description: - There are also 2 parameters that allow you to control the extent of infix searching - max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before - or after the query that can be present in the token. For example query "K2100" has 2 extra + There are also 2 parameters that allow you to control the extent of infix searching + max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before + or after the query that can be present in the token. For example query "K2100" has 2 extra symbols in "6PK2100". By default, any number of prefixes/suffixes can be present for a match. type: integer max_extra_suffix: description: - There are also 2 parameters that allow you to control the extent of infix searching - max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before - or after the query that can be present in the token. For example query "K2100" has 2 extra + There are also 2 parameters that allow you to control the extent of infix searching + max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before + or after the query that can be present in the token. For example query "K2100" has 2 extra symbols in "6PK2100". By default, any number of prefixes/suffixes can be present for a match. type: integer @@ -2270,7 +3458,7 @@ components: limit: description: > - Number of hits to fetch. Can be used as an alternative to the per_page parameter. + Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. type: integer @@ -2292,6 +3480,13 @@ components: Default: 3 type: integer + group_missing_values: + description: > + Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. + Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. + Default: true + type: boolean + include_fields: description: List of fields from the document to include in the search result type: string @@ -2334,12 +3529,43 @@ components: enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 type: integer + drop_tokens_mode: + $ref: "#/components/schemas/DropTokensMode" typo_tokens_threshold: description: > If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 type: integer + enable_typos_for_alpha_numerical_tokens: + type: boolean + description: > + Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + + filter_curated_hits: + type: boolean + description: > + Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + enable_synonyms: + type: boolean + description: > + If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + + enable_analytics: + description: > + Flag for enabling/disabling analytics aggregation for specific search + queries (for e.g. those originating from a test script). + type: boolean + default: true + + synonym_prefix: + type: boolean + description: > + Allow synonym resolution on word prefixes in the query. Default: false + synonym_num_typos: + type: integer + description: > + Allow synonym resolution on typo-corrected words in the query. Default: 0 pinned_hits: description: > @@ -2351,7 +3577,7 @@ components: you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based - on rules. Overrides are applied first, followed by `pinned_hits` and + on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. type: string @@ -2366,20 +3592,25 @@ components: finally `hidden_hits`. type: string + override_tags: + description: Comma separated list of tags to trigger the curations rules that match the tags. + type: string + highlight_fields: description: > - A list of custom fields that must be highlighted even if you don't query + A list of custom fields that must be highlighted even if you don't query for them type: string pre_segmented_query: description: > You can index content from any logographic language into Typesense if you - are able to segment / split the text into space-separated words yourself + are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same type: boolean + default: false preset: description: > @@ -2392,21 +3623,42 @@ components: If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false type: boolean + default: false prioritize_exact_match: description: > Set this parameter to true to ensure that an exact match is ranked above the others type: boolean + default: true + + prioritize_token_position: + description: > + Make Typesense prioritize documents where the query words appear earlier in the text. + type: boolean + default: false + + prioritize_num_matching_fields: + description: > + Make Typesense prioritize documents where the query words appear in more number of fields. + type: boolean + default: true + + enable_typos_for_numerical_tokens: + description: > + Make Typesense disable typos for numerical tokens. + type: boolean + default: true + exhaustive_search: description: > - Setting this to true will make Typesense consider all prefixes and typo - corrections of the words in the query without stopping early when enough results are found + Setting this to true will make Typesense consider all prefixes and typo + corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). type: boolean search_cutoff_ms: description: > - Typesense will attempt to return results early if the cutoff time has elapsed. + Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. type: integer use_cache: @@ -2415,17 +3667,17 @@ components: type: boolean cache_ttl: description: > - The duration (in seconds) that determines how long the search query is cached. + The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. type: integer min_len_1typo: description: > - Minimum word length for 1-typo correction to be applied. + Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. type: integer min_len_2typo: description: > - Minimum word length for 2-typo correction to be applied. + Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. type: integer vector_query: @@ -2438,13 +3690,47 @@ components: type: integer remote_embedding_num_tries: description: > - Number of times to retry fetching remote embeddings. - type: integer + Number of times to retry fetching remote embeddings. + type: integer + facet_strategy: + description: > + Choose the underlying faceting strategy used. Comma separated string of allows values: + exhaustive, top_values or automatic (default). + type: string + stopwords: + description: > + Name of the stopwords set to apply for this search, + the keywords present in the set will be removed from the search query. + type: string + facet_return_parent: + description: > + Comma separated string of nested facet fields whose parent object should be returned in facet response. + type: string + voice_query: + description: > + The base64 encoded audio file in 16 khz 16-bit WAV format. + type: string + conversation: + description: > + Enable conversational search. + type: boolean + conversation_model_id: + description: > + The Id of Conversation Model to be used. + type: string + conversation_id: + description: > + The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + type: string MultiSearchSearchesParameter: type: object required: - searches properties: + union: + type: boolean + default: false + description: When true, merges the search results from each search query into a single ordered set of hits. searches: type: array items: @@ -2453,13 +3739,21 @@ components: allOf: - $ref: "#/components/schemas/MultiSearchParameters" - type: object - required: - - collection properties: collection: type: string description: > The collection to search in. + x-typesense-api-key: + type: string + description: A separate search API key for each search within a multi_search request + rerank_hybrid_matches: + type: boolean + description: > + When true, computes both text match and vector distance scores for all matches in hybrid search. + Documents found only through keyword search will get a vector distance score, and + documents found only through vector search will get a text match score. + default: false FacetCounts: type: object properties: @@ -2474,6 +3768,8 @@ components: type: string value: type: string + parent: + type: object field_name: type: string stats: @@ -2493,49 +3789,535 @@ components: avg: type: number format: double - AnalyticsRuleSchema: + AnalyticsEventCreateResponse: + type: object + required: + - ok + properties: + ok: + type: boolean + AnalyticsEvent: + type: object + required: + - name + - event_type + - data + properties: + name: + type: string + description: Name of the analytics rule this event corresponds to + event_type: + type: string + description: Type of event (e.g., click, conversion, query, visit) + data: + type: object + description: Event payload + properties: + user_id: + type: string + doc_id: + type: string + doc_ids: + type: array + items: + type: string + q: + type: string + analytics_tag: + type: string + AnalyticsEventsResponse: + type: object + required: + - events + properties: + events: + type: array + items: + type: object + properties: + name: { type: string } + event_type: { type: string } + collection: { type: string } + timestamp: { type: integer, format: int64 } + user_id: { type: string } + doc_id: { type: string } + doc_ids: + type: array + items: { type: string } + query: { type: string } + AnalyticsRuleCreate: type: object required: - name - type - - params + - collection + - event_type properties: name: type: string type: type: string + enum: [popular_queries, nohits_queries, counter, log] + collection: + type: string + event_type: + type: string + rule_tag: + type: string params: - $ref: "#/components/schemas/AnalyticsRuleParameters" - AnalyticsRuleParameters: + type: object + properties: + destination_collection: + type: string + limit: + type: integer + capture_search_requests: + type: boolean + meta_fields: + type: array + items: { type: string } + expand_query: + type: boolean + counter_field: + type: string + weight: + type: integer + AnalyticsRuleUpdate: type: object - required: - - source - - destination - - limit + description: Fields allowed to update on an analytics rule properties: - source: + name: + type: string + rule_tag: + type: string + params: type: object properties: - collections: + destination_collection: + type: string + limit: + type: integer + capture_search_requests: + type: boolean + meta_fields: type: array - items: - type: string - destination: + items: { type: string } + expand_query: + type: boolean + counter_field: + type: string + weight: + type: integer + AnalyticsRule: + allOf: + - $ref: '#/components/schemas/AnalyticsRuleCreate' + - type: object + AnalyticsStatus: + type: object + properties: + popular_prefix_queries: { type: integer } + nohits_prefix_queries: { type: integer } + log_prefix_queries: { type: integer } + query_log_events: { type: integer } + query_counter_events: { type: integer } + doc_log_events: { type: integer } + doc_counter_events: { type: integer } + + APIStatsResponse: + type: object + properties: + delete_latency_ms: + type: number + format: double + delete_requests_per_second: + type: number + format: double + import_latency_ms: + type: number + format: double + import_requests_per_second: + type: number + format: double + latency_ms: + type: object + x-go-type: "map[string]float64" + overloaded_requests_per_second: + type: number + format: double + pending_write_batches: + type: number + format: double + requests_per_second: type: object + x-go-type: "map[string]float64" + search_latency_ms: + type: number + format: double + search_requests_per_second: + type: number + format: double + total_requests_per_second: + type: number + format: double + write_latency_ms: + type: number + format: double + write_requests_per_second: + type: number + format: double + StopwordsSetUpsertSchema: + type: object + properties: + stopwords: + type: array + items: + type: string + locale: + type: string + required: + - stopwords + example: | + {"stopwords": ["Germany", "France", "Italy"], "locale": "en"} + StopwordsSetSchema: + type: object + properties: + id: + type: string + stopwords: + type: array + items: + type: string + locale: + type: string + required: + - id + - stopwords + example: | + {"id": "countries", "stopwords": ["Germany", "France", "Italy"], "locale": "en"} + StopwordsSetRetrieveSchema: + type: object + properties: + stopwords: + $ref: "#/components/schemas/StopwordsSetSchema" + required: + - stopwords + example: | + {"stopwords": {"id": "countries", "stopwords": ["Germany", "France", "Italy"], "locale": "en"}} + StopwordsSetsRetrieveAllSchema: + type: object + properties: + stopwords: + type: array + items: + $ref: "#/components/schemas/StopwordsSetSchema" + required: + - stopwords + example: | + {"stopwords": [{"id": "countries", "stopwords": ["Germany", "France", "Italy"], "locale": "en"}]} + PresetUpsertSchema: + properties: + value: + oneOf: + - $ref: '#/components/schemas/SearchParameters' + - $ref: '#/components/schemas/MultiSearchSearchesParameter' + required: + - value + PresetSchema: + allOf: + - $ref: '#/components/schemas/PresetUpsertSchema' + - type: object + required: + - name properties: - collection: + name: type: string - limit: + PresetsRetrieveSchema: + type: object + required: + - presets + properties: + presets: + type: array + items: + $ref: '#/components/schemas/PresetSchema' + x-go-type: '[]*PresetSchema' + PresetDeleteSchema: + type: object + required: + - name + properties: + name: + type: string + DirtyValues: + type: string + enum: [coerce_or_reject, coerce_or_drop, drop, reject] + IndexAction: + type: string + enum: [create, update, upsert, emplace] + DropTokensMode: + type: string + enum: [right_to_left, left_to_right, both_sides:3] + description: > + Dictates the direction in which the words in the query must be dropped when the original words in the query do not appear in any document. + Values: right_to_left (default), left_to_right, both_sides:3 + A note on both_sides:3 - for queries up to 3 tokens (words) in length, this mode will drop tokens from both sides and exhaustively rank all matching results. + If query length is greater than 3 words, Typesense will just fallback to default behavior of right_to_left + ConversationModelCreateSchema: + required: + - model_name + - max_bytes + allOf: + - $ref: '#/components/schemas/ConversationModelUpdateSchema' + - type: object + required: + - model_name + - max_bytes + - history_collection + properties: + model_name: + description: Name of the LLM model offered by OpenAI, Cloudflare or vLLM + type: string + max_bytes: + description: | + The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. + type: integer + history_collection: + type: string + description: Typesense collection that stores the historical conversations + ConversationModelUpdateSchema: + type: object + properties: + id: + type: string + description: An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. + model_name: + description: Name of the LLM model offered by OpenAI, Cloudflare or vLLM + type: string + api_key: + description: The LLM service's API Key + type: string + history_collection: + type: string + description: Typesense collection that stores the historical conversations + account_id: + description: LLM service's account ID (only applicable for Cloudflare) + type: string + system_prompt: + description: The system prompt that contains special instructions to the LLM + type: string + ttl: + type: integer + description: | + Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) + max_bytes: + description: | + The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. + type: integer + vllm_url: + description: URL of vLLM service + type: string + ConversationModelSchema: + allOf: + - $ref: '#/components/schemas/ConversationModelCreateSchema' + - type: object + required: + - id + properties: + id: + type: string + description: An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. + StemmingDictionary: + type: object + required: + - id + - words + properties: + id: + type: string + description: Unique identifier for the dictionary + example: irregular-plurals + words: + type: array + description: List of word mappings in the dictionary + items: + type: object + required: + - word + - root + properties: + word: + type: string + description: The word form to be stemmed + example: people + root: + type: string + description: The root form of the word + example: person + NLSearchModelBase: + type: object + properties: + model_name: + type: string + description: Name of the NL model to use + api_key: + type: string + description: API key for the NL model service + api_url: + type: string + description: Custom API URL for the NL model service + max_bytes: + type: integer + description: Maximum number of bytes to process + temperature: + type: number + description: Temperature parameter for the NL model + system_prompt: + type: string + description: System prompt for the NL model + top_p: + type: number + description: Top-p parameter for the NL model (Google-specific) + top_k: + type: integer + description: Top-k parameter for the NL model (Google-specific) + stop_sequences: + type: array + items: + type: string + description: Stop sequences for the NL model (Google-specific) + api_version: + type: string + description: API version for the NL model service + project_id: + type: string + description: Project ID for GCP Vertex AI + access_token: + type: string + description: Access token for GCP Vertex AI + refresh_token: + type: string + description: Refresh token for GCP Vertex AI + client_id: + type: string + description: Client ID for GCP Vertex AI + client_secret: + type: string + description: Client secret for GCP Vertex AI + region: + type: string + description: Region for GCP Vertex AI + max_output_tokens: type: integer - AnalyticsRulesRetrieveSchema: + description: Maximum output tokens for GCP Vertex AI + account_id: + type: string + description: Account ID for Cloudflare-specific models + + NLSearchModelCreateSchema: + allOf: + - $ref: '#/components/schemas/NLSearchModelBase' + - type: object + properties: + id: + type: string + description: Optional ID for the NL search model + + NLSearchModelSchema: + allOf: + - $ref: '#/components/schemas/NLSearchModelCreateSchema' + - type: object + required: + - id + properties: + id: + type: string + description: ID of the NL search model + + NLSearchModelUpdateSchema: + $ref: '#/components/schemas/NLSearchModelCreateSchema' + + NLSearchModelDeleteSchema: + type: object + required: + - id + properties: + id: + type: string + description: ID of the deleted NL search model + + SynonymItemSchema: + type: object + required: + - id + - synonyms + properties: + id: + type: string + description: Unique identifier for the synonym item + synonyms: + type: array + description: Array of words that should be considered as synonyms + items: + type: string + root: + type: string + description: For 1-way synonyms, indicates the root word that words in the synonyms parameter map to + locale: + type: string + description: Locale for the synonym, leave blank to use the standard tokenizer + symbols_to_index: + type: array + description: By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is + items: + type: string + + SynonymSetCreateSchema: + type: object + required: + - items + properties: + items: + type: array + description: Array of synonym items + items: + $ref: "#/components/schemas/SynonymItemSchema" + + SynonymSetSchema: + allOf: + - $ref: "#/components/schemas/SynonymSetCreateSchema" + - type: object + required: + - name + properties: + name: + type: string + description: Name of the synonym set + + SynonymSetsRetrieveSchema: type: object + required: + - synonym_sets properties: - rules: + synonym_sets: type: array + description: Array of synonym sets items: - $ref: "#/components/schemas/AnalyticsRuleSchema" + $ref: "#/components/schemas/SynonymSetSchema" + + SynonymSetRetrieveSchema: + $ref: "#/components/schemas/SynonymSetCreateSchema" + + SynonymSetDeleteSchema: + type: object + required: + - name + properties: + name: + type: string + description: Name of the deleted synonym set + securitySchemes: api_key_header: type: apiKey name: X-TYPESENSE-API-KEY - in: header + in: header \ No newline at end of file diff --git a/preprocessed_openapi.yml b/preprocessed_openapi.yml new file mode 100644 index 0000000..c20d1c5 --- /dev/null +++ b/preprocessed_openapi.yml @@ -0,0 +1,4812 @@ +openapi: 3.0.3 +info: + title: Typesense API + description: An open source search engine for building delightful search experiences. + version: '30.0' + license: + name: GPL-3.0 + url: https://opensource.org/licenses/GPL-3.0 +servers: +- url: '{protocol}://{hostname}:{port}' + description: Typesense Server + variables: + protocol: + default: http + description: The protocol of your Typesense server + hostname: + default: localhost + description: The hostname of your Typesense server + port: + default: '8108' + description: The port of your Typesense server +externalDocs: + description: Find out more about Typsesense + url: https://typesense.org +security: +- api_key_header: [] +tags: +- name: collections + description: A collection is defined by a schema + externalDocs: + description: Find out more + url: https://typesense.org/api/#create-collection +- name: documents + description: A document is an individual record to be indexed and belongs to a collection + externalDocs: + description: Find out more + url: https://typesense.org/api/#index-document +- name: curation + description: Hand-curate search results based on conditional business rules + externalDocs: + description: Find out more + url: https://typesense.org/docs/0.23.0/api/#curation +- name: analytics + description: Typesense can aggregate search queries for both analytics purposes and for query suggestions. + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/analytics-query-suggestions.html +- name: keys + description: Manage API Keys with fine-grain access control + externalDocs: + description: Find out more + url: https://typesense.org/docs/0.23.0/api/#api-keys +- name: debug + description: Debugging information +- name: operations + description: Manage Typesense cluster + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/cluster-operations.html +- name: stopwords + description: Manage stopwords sets + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/stopwords.html +- name: presets + description: Store and reference search parameters + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/search.html#presets +- name: conversations + description: Conversational Search (RAG) + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/conversational-search-rag.html +- name: synonyms + description: Manage synonyms + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/synonyms.html +- name: stemming + description: Manage stemming dictionaries + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/stemming.html +- name: nl_search_models + description: Manage NL search models + externalDocs: + description: Find out more + url: https://typesense.org/docs/29.0/api/natural-language-search.html +paths: + /collections: + get: + tags: + - collections + summary: List all collections + description: Returns a summary of all your collections. The collections are returned sorted by creation date, with the most recent collections appearing first. + operationId: getCollections + parameters: + - name: exclude_fields + in: query + schema: + description: Comma-separated list of fields from the collection to exclude from the response + type: string + - name: limit + in: query + schema: + description: | + Number of collections to fetch. Default: returns all collections. + type: integer + - name: offset + in: query + schema: + description: Identifies the starting point to return collections when paginating. + type: integer + responses: + '200': + description: List of all collections + content: + application/json: + schema: + type: array + x-go-type: '[]*CollectionResponse' + items: + $ref: '#/components/schemas/CollectionResponse' + post: + tags: + - collections + summary: Create a new collection + description: When a collection is created, we give it a name and describe the fields that will be indexed from the documents added to the collection. + operationId: createCollection + requestBody: + description: The collection object to be created + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionSchema' + required: true + responses: + '201': + description: Collection successfully created + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionResponse' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + '409': + description: Collection already exists + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /collections/{collectionName}: + get: + tags: + - collections + summary: Retrieve a single collection + description: Retrieve the details of a collection, given its name. + operationId: getCollection + parameters: + - name: collectionName + in: path + description: The name of the collection to retrieve + required: true + schema: + type: string + responses: + '200': + description: Collection fetched + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionResponse' + '404': + description: Collection not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + patch: + tags: + - collections + summary: Update a collection + description: Update a collection's schema to modify the fields and their types. + operationId: updateCollection + parameters: + - name: collectionName + in: path + description: The name of the collection to update + required: true + schema: + type: string + requestBody: + description: The document object with fields to be updated + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionUpdateSchema' + required: true + responses: + '200': + description: The updated partial collection schema + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionUpdateSchema' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + '404': + description: The collection was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - collections + summary: Delete a collection + description: Permanently drops a collection. This action cannot be undone. For large collections, this might have an impact on read latencies. + operationId: deleteCollection + parameters: + - name: collectionName + in: path + description: The name of the collection to delete + required: true + schema: + type: string + responses: + '200': + description: Collection deleted + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionResponse' + '404': + description: Collection not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /collections/{collectionName}/documents: + post: + tags: + - documents + summary: Index a document + description: A document to be indexed in a given collection must conform to the schema of the collection. + operationId: indexDocument + parameters: + - name: collectionName + in: path + description: The name of the collection to add the document to + required: true + schema: + type: string + - name: action + in: query + description: Additional action to perform + schema: + type: string + example: upsert + $ref: '#/components/schemas/IndexAction' + - name: dirty_values + in: query + description: Dealing with Dirty Data + schema: + $ref: '#/components/schemas/DirtyValues' + requestBody: + description: The document object to be indexed + content: + application/json: + schema: + type: object + description: Can be any key-value pair + x-go-type: interface{} + required: true + responses: + '201': + description: Document successfully created/indexed + content: + application/json: + schema: + type: object + description: Can be any key-value pair + '404': + description: Collection not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + patch: + tags: + - documents + summary: Update documents with conditional query + description: The filter_by query parameter is used to filter to specify a condition against which the documents are matched. The request body contains the fields that should be updated for any documents that match the filter condition. This endpoint is only available if the Typesense server is version `0.25.0.rc12` or later. + operationId: updateDocuments + parameters: + - name: collectionName + in: path + description: The name of the collection to update documents in + required: true + schema: + type: string + - name: filter_by + in: query + schema: + type: string + example: 'num_employees:>100 && country: [USA, UK]' + responses: + '200': + description: The response contains a single field, `num_updated`, indicating the number of documents affected. + content: + application/json: + schema: + type: object + required: + - num_updated + properties: + num_updated: + type: integer + description: The number of documents that have been updated + example: 1 + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + '404': + description: The collection was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + requestBody: + description: The document fields to be updated + content: + application/json: + schema: + type: object + description: Can be any key-value pair + x-go-type: interface{} + required: true + delete: + tags: + - documents + summary: Delete a bunch of documents + description: Delete a bunch of documents that match a specific filter condition. Use the `batch_size` parameter to control the number of documents that should deleted at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. + operationId: deleteDocuments + parameters: + - name: collectionName + in: path + description: The name of the collection to delete documents from + required: true + schema: + type: string + - name: filter_by + in: query + schema: + type: string + example: 'num_employees:>100 && country: [USA, UK]' + - name: batch_size + in: query + schema: + description: Batch size parameter controls the number of documents that should be deleted at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. + type: integer + - name: ignore_not_found + in: query + schema: + type: boolean + - name: truncate + in: query + schema: + description: When true, removes all documents from the collection while preserving the collection and its schema. + type: boolean + responses: + '200': + description: Documents successfully deleted + content: + application/json: + schema: + type: object + required: + - num_deleted + properties: + num_deleted: + type: integer + '404': + description: Collection not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /collections/{collectionName}/documents/search: + get: + tags: + - documents + summary: Search for documents in a collection + description: Search for documents in a collection that match the search criteria. + operationId: searchCollection + parameters: + - name: collectionName + in: path + description: The name of the collection to search for the document under + required: true + schema: + type: string + - name: q + in: query + schema: + description: The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. + type: string + - name: query_by + in: query + schema: + description: A list of `string` fields that should be queried against. Multiple fields are separated with a comma. + type: string + - name: nl_query + in: query + schema: + description: Whether to use natural language processing to parse the query. + type: boolean + - name: nl_model_id + in: query + schema: + description: The ID of the natural language model to use. + type: string + - name: query_by_weights + in: query + schema: + description: The relative weight to give each `query_by` field when ranking results. This can be used to boost fields in priority, when looking for matches. Multiple fields are separated with a comma. + type: string + - name: text_match_type + in: query + schema: + description: In a multi-field matching context, this parameter determines how the representative text match score of a record is calculated. Possible values are max_score (default) or max_weight. + type: string + - name: prefix + in: query + schema: + description: Boolean field to indicate that the last word in the query should be treated as a prefix, and not as a whole word. This is used for building autocomplete and instant search interfaces. Defaults to true. + type: string + - name: infix + in: query + schema: + description: If infix index is enabled for this field, infix searching can be done on a per-field basis by sending a comma separated string parameter called infix to the search query. This parameter can have 3 values; `off` infix search is disabled, which is default `always` infix search is performed along with regular search `fallback` infix search is performed if regular search does not produce results + type: string + - name: max_extra_prefix + in: query + schema: + description: There are also 2 parameters that allow you to control the extent of infix searching max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before or after the query that can be present in the token. For example query "K2100" has 2 extra symbols in "6PK2100". By default, any number of prefixes/suffixes can be present for a match. + type: integer + - name: max_extra_suffix + in: query + schema: + description: There are also 2 parameters that allow you to control the extent of infix searching max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before or after the query that can be present in the token. For example query "K2100" has 2 extra symbols in "6PK2100". By default, any number of prefixes/suffixes can be present for a match. + type: integer + - name: filter_by + in: query + schema: + description: Filter conditions for refining your open api validator search results. Separate multiple conditions with &&. + type: string + example: 'num_employees:>100 && country: [USA, UK]' + - name: max_filter_by_candidates + in: query + schema: + description: Controls the number of similar words that Typesense considers during fuzzy search on filter_by values. Useful for controlling prefix matches like company_name:Acm*. + type: integer + - name: sort_by + in: query + schema: + description: A list of numerical fields and their corresponding sort orders that will be used for ordering your results. Up to 3 sort fields can be specified. The text similarity score is exposed as a special `_text_match` field that you can use in the list of sorting fields. If no `sort_by` parameter is specified, results are sorted by `_text_match:desc,default_sorting_field:desc` + type: string + example: num_employees:desc + - name: facet_by + in: query + schema: + description: A list of fields that will be used for faceting your results on. Separate multiple fields with a comma. + type: string + - name: max_facet_values + in: query + schema: + description: Maximum number of facet values to be returned. + type: integer + - name: facet_query + in: query + schema: + description: Facet values that are returned can now be filtered via this parameter. The matching facet text is also highlighted. For example, when faceting by `category`, you can set `facet_query=category:shoe` to return only facet values that contain the prefix "shoe". + type: string + - name: num_typos + in: query + schema: + description: | + The number of typographical errors (1 or 2) that would be tolerated. Default: 2 + type: string + - name: page + in: query + schema: + description: Results from this specific page number would be fetched. + type: integer + - name: per_page + in: query + schema: + description: 'Number of results to fetch per page. Default: 10' + type: integer + - name: limit + in: query + schema: + description: | + Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. + type: integer + - name: offset + in: query + schema: + description: Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. + type: integer + - name: group_by + in: query + schema: + description: You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. + type: string + - name: group_limit + in: query + schema: + description: | + Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 + type: integer + - name: group_missing_values + in: query + schema: + description: | + Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true + type: boolean + - name: include_fields + in: query + schema: + description: List of fields from the document to include in the search result + type: string + - name: exclude_fields + in: query + schema: + description: List of fields from the document to exclude in the search result + type: string + - name: highlight_full_fields + in: query + schema: + description: List of fields which should be highlighted fully without snippeting + type: string + - name: highlight_affix_num_tokens + in: query + schema: + description: | + The number of tokens that should surround the highlighted text on each side. Default: 4 + type: integer + - name: highlight_start_tag + in: query + schema: + description: | + The start tag used for the highlighted snippets. Default: `` + type: string + - name: highlight_end_tag + in: query + schema: + description: | + The end tag used for the highlighted snippets. Default: `` + type: string + - name: enable_highlight_v1 + in: query + schema: + description: | + Flag for enabling/disabling the deprecated, old highlight structure in the response. Default: true + type: boolean + default: true + - name: enable_analytics + in: query + schema: + description: | + Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). + type: boolean + default: true + - name: snippet_threshold + in: query + schema: + description: | + Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 + type: integer + - name: synonym_sets + in: query + schema: + type: string + description: List of synonym set names to associate with this search query + example: synonym_set_1,synonym_set_2 + - name: drop_tokens_threshold + in: query + schema: + description: | + If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 + type: integer + - name: drop_tokens_mode + in: query + schema: + $ref: '#/components/schemas/DropTokensMode' + - name: typo_tokens_threshold + in: query + schema: + description: | + If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 + type: integer + - name: enable_typos_for_alpha_numerical_tokens + in: query + schema: + type: boolean + description: | + Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + - name: filter_curated_hits + in: query + schema: + type: boolean + description: | + Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + - name: enable_synonyms + in: query + schema: + type: boolean + description: | + If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + - name: synonym_prefix + in: query + schema: + type: boolean + description: | + Allow synonym resolution on word prefixes in the query. Default: false + - name: synonym_num_typos + in: query + schema: + type: integer + description: | + Allow synonym resolution on typo-corrected words in the query. Default: 0 + - name: pinned_hits + in: query + schema: + description: | + A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. + You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + type: string + - name: hidden_hits + in: query + schema: + description: | + A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. + You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + type: string + - name: override_tags + in: query + schema: + description: Comma separated list of tags to trigger the curations rules that match the tags. + type: string + - name: highlight_fields + in: query + schema: + description: | + A list of custom fields that must be highlighted even if you don't query for them + type: string + - name: split_join_tokens + in: query + schema: + description: | + Treat space as typo: search for q=basket ball if q=basketball is not found or vice-versa. Splitting/joining of tokens will only be attempted if the original query produces no results. To always trigger this behavior, set value to `always``. To disable, set value to `off`. Default is `fallback`. + type: string + - name: pre_segmented_query + in: query + schema: + description: | + You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. + Set this parameter to true to do the same + type: boolean + - name: preset + in: query + schema: + description: | + Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. + type: string + - name: enable_overrides + in: query + schema: + description: | + If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false + type: boolean + default: false + - name: prioritize_exact_match + in: query + schema: + description: | + Set this parameter to true to ensure that an exact match is ranked above the others + type: boolean + default: true + - name: max_candidates + in: query + schema: + description: | + Control the number of words that Typesense considers for typo and prefix searching. + type: integer + - name: prioritize_token_position + in: query + schema: + description: | + Make Typesense prioritize documents where the query words appear earlier in the text. + type: boolean + default: false + - name: prioritize_num_matching_fields + in: query + schema: + description: | + Make Typesense prioritize documents where the query words appear in more number of fields. + type: boolean + default: true + - name: enable_typos_for_numerical_tokens + in: query + schema: + description: | + Make Typesense disable typos for numerical tokens. + type: boolean + default: true + - name: exhaustive_search + in: query + schema: + description: | + Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). + type: boolean + - name: search_cutoff_ms + in: query + schema: + description: | + Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. + type: integer + - name: use_cache + in: query + schema: + description: | + Enable server side caching of search query results. By default, caching is disabled. + type: boolean + - name: cache_ttl + in: query + schema: + description: | + The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. + type: integer + - name: min_len_1typo + in: query + schema: + description: | + Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + type: integer + - name: min_len_2typo + in: query + schema: + description: | + Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + type: integer + - name: vector_query + in: query + schema: + description: | + Vector query expression for fetching documents "closest" to a given query/document vector. + type: string + - name: remote_embedding_timeout_ms + in: query + schema: + description: | + Timeout (in milliseconds) for fetching remote embeddings. + type: integer + - name: remote_embedding_num_tries + in: query + schema: + description: | + Number of times to retry fetching remote embeddings. + type: integer + - name: facet_strategy + in: query + schema: + description: | + Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). + type: string + - name: stopwords + in: query + schema: + description: | + Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. + type: string + - name: facet_return_parent + in: query + schema: + description: | + Comma separated string of nested facet fields whose parent object should be returned in facet response. + type: string + - name: voice_query + in: query + schema: + description: | + The base64 encoded audio file in 16 khz 16-bit WAV format. + type: string + - name: conversation + in: query + schema: + description: | + Enable conversational search. + type: boolean + - name: conversation_model_id + in: query + schema: + description: | + The Id of Conversation Model to be used. + type: string + - name: conversation_id + in: query + schema: + description: | + The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + type: string + responses: + '200': + description: Search results + content: + application/json: + schema: + $ref: '#/components/schemas/SearchResult' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + '404': + description: The collection or field was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /collections/{collectionName}/overrides: + get: + tags: + - documents + - curation + summary: List all collection overrides + operationId: getSearchOverrides + parameters: + - name: collectionName + in: path + description: The name of the collection + required: true + schema: + type: string + responses: + '200': + description: List of all search overrides + content: + application/json: + schema: + $ref: '#/components/schemas/SearchOverridesResponse' + /collections/{collectionName}/overrides/{overrideId}: + get: + tags: + - documents + - override + summary: Retrieve a single search override + description: Retrieve the details of a search override, given its id. + operationId: getSearchOverride + parameters: + - name: collectionName + in: path + description: The name of the collection + required: true + schema: + type: string + - name: overrideId + in: path + description: The id of the search override + required: true + schema: + type: string + responses: + '200': + description: Search override fetched + content: + application/json: + schema: + $ref: '#/components/schemas/SearchOverride' + put: + tags: + - documents + - curation + summary: Create or update an override to promote certain documents over others + description: Create or update an override to promote certain documents over others. Using overrides, you can include or exclude specific documents for a given query. + operationId: upsertSearchOverride + parameters: + - name: collectionName + in: path + description: The name of the collection + required: true + schema: + type: string + - name: overrideId + in: path + description: The ID of the search override to create/update + required: true + schema: + type: string + requestBody: + description: The search override object to be created/updated + content: + application/json: + schema: + $ref: '#/components/schemas/SearchOverrideSchema' + required: true + responses: + '200': + description: Created/updated search override + content: + application/json: + schema: + $ref: '#/components/schemas/SearchOverride' + '404': + description: Search override not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - documents + - curation + summary: Delete an override associated with a collection + operationId: deleteSearchOverride + parameters: + - name: collectionName + in: path + description: The name of the collection + required: true + schema: + type: string + - name: overrideId + in: path + description: The ID of the search override to delete + required: true + schema: + type: string + responses: + '200': + description: The ID of the deleted search override + content: + application/json: + schema: + $ref: '#/components/schemas/SearchOverrideDeleteResponse' + '404': + description: Search override not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /synonym_sets: + get: + tags: + - synonyms + summary: List all synonym sets + description: Retrieve all synonym sets + operationId: retrieveSynonymSets + responses: + '200': + description: List of all synonym sets + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SynonymSetSchema' + /synonym_sets/{synonymSetName}: + get: + tags: + - synonyms + summary: Retrieve a synonym set + description: Retrieve a specific synonym set by its name + operationId: retrieveSynonymSet + parameters: + - name: synonymSetName + in: path + description: The name of the synonym set to retrieve + required: true + schema: + type: string + responses: + '200': + description: Synonym set fetched + content: + application/json: + schema: + $ref: '#/components/schemas/SynonymSetRetrieveSchema' + '404': + description: Synonym set not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + put: + tags: + - synonyms + summary: Create or update a synonym set + description: Create or update a synonym set with the given name + operationId: upsertSynonymSet + parameters: + - name: synonymSetName + in: path + description: The name of the synonym set to create/update + required: true + schema: + type: string + requestBody: + description: The synonym set to be created/updated + content: + application/json: + schema: + $ref: '#/components/schemas/SynonymSetCreateSchema' + required: true + responses: + '200': + description: Synonym set successfully created/updated + content: + application/json: + schema: + $ref: '#/components/schemas/SynonymSetSchema' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - synonyms + summary: Delete a synonym set + description: Delete a specific synonym set by its name + operationId: deleteSynonymSet + parameters: + - name: synonymSetName + in: path + description: The name of the synonym set to delete + required: true + schema: + type: string + responses: + '200': + description: Synonym set successfully deleted + content: + application/json: + schema: + $ref: '#/components/schemas/SynonymSetDeleteSchema' + '404': + description: Synonym set not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /collections/{collectionName}/documents/export: + get: + tags: + - documents + summary: Export all documents in a collection + description: Export all documents in a collection in JSON lines format. + operationId: exportDocuments + parameters: + - name: collectionName + in: path + description: The name of the collection + required: true + schema: + type: string + - name: filter_by + in: query + schema: + description: Filter conditions for refining your search results. Separate multiple conditions with &&. + type: string + - name: include_fields + in: query + schema: + description: List of fields from the document to include in the search result + type: string + - name: exclude_fields + in: query + schema: + description: List of fields from the document to exclude in the search result + type: string + responses: + '200': + description: Exports all the documents in a given collection. + content: + application/octet-stream: + schema: + type: string + example: | + {"id": "124", "company_name": "Stark Industries", "num_employees": 5215, "country": "US"} + {"id": "125", "company_name": "Future Technology", "num_employees": 1232,"country": "UK"} + {"id": "126", "company_name": "Random Corp.", "num_employees": 531,"country": "AU"} + '404': + description: The collection was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /collections/{collectionName}/documents/import: + post: + tags: + - documents + summary: Import documents into a collection + description: The documents to be imported must be formatted in a newline delimited JSON structure. You can feed the output file from a Typesense export operation directly as import. + operationId: importDocuments + parameters: + - name: collectionName + in: path + description: The name of the collection + required: true + schema: + type: string + - name: batch_size + in: query + schema: + type: integer + - name: return_id + in: query + schema: + type: boolean + description: Returning the id of the imported documents. If you want the import response to return the ingested document's id in the response, you can use the return_id parameter. + - name: remote_embedding_batch_size + in: query + schema: + type: integer + - name: return_doc + in: query + schema: + type: boolean + - name: action + in: query + schema: + $ref: '#/components/schemas/IndexAction' + - name: dirty_values + in: query + schema: + $ref: '#/components/schemas/DirtyValues' + requestBody: + description: The json array of documents or the JSONL file to import + content: + application/octet-stream: + schema: + type: string + description: The JSONL file to import + required: true + responses: + '200': + description: Result of the import operation. Each line of the response indicates the result of each document present in the request body (in the same order). If the import of a single document fails, it does not affect the other documents. If there is a failure, the response line will include a corresponding error message and as well as the actual document content. + content: + application/octet-stream: + schema: + type: string + example: | + {"success": true} + {"success": false, "error": "Bad JSON.", "document": "[bad doc"} + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + '404': + description: The collection was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /collections/{collectionName}/documents/{documentId}: + get: + tags: + - documents + summary: Retrieve a document + description: Fetch an individual document from a collection by using its ID. + operationId: getDocument + parameters: + - name: collectionName + in: path + description: The name of the collection to search for the document under + required: true + schema: + type: string + - name: documentId + in: path + description: The Document ID + required: true + schema: + type: string + responses: + '200': + description: The document referenced by the ID + content: + application/json: + schema: + type: object + description: Can be any key-value pair + '404': + description: The document or collection was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + patch: + tags: + - documents + summary: Update a document + description: Update an individual document from a collection by using its ID. The update can be partial. + operationId: updateDocument + parameters: + - name: collectionName + in: path + description: The name of the collection to search for the document under + required: true + schema: + type: string + - name: documentId + in: path + description: The Document ID + required: true + schema: + type: string + - name: dirty_values + in: query + description: Dealing with Dirty Data + schema: + $ref: '#/components/schemas/DirtyValues' + requestBody: + description: The document object with fields to be updated + content: + application/json: + schema: + type: object + description: Can be any key-value pair + x-go-type: interface{} + required: true + responses: + '200': + description: The document referenced by the ID was updated + content: + application/json: + schema: + type: object + description: Can be any key-value pair + '404': + description: The document or collection was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - documents + summary: Delete a document + description: Delete an individual document from a collection by using its ID. + operationId: deleteDocument + parameters: + - name: collectionName + in: path + description: The name of the collection to search for the document under + required: true + schema: + type: string + - name: documentId + in: path + description: The Document ID + required: true + schema: + type: string + responses: + '200': + description: The document referenced by the ID was deleted + content: + application/json: + schema: + type: object + description: Can be any key-value pair + '404': + description: The document or collection was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /conversations/models: + get: + description: Retrieve all conversation models + operationId: retrieveAllConversationModels + responses: + '200': + content: + application/json: + schema: + items: + $ref: '#/components/schemas/ConversationModelSchema' + type: array + x-go-type: '[]*ConversationModelSchema' + description: List of all conversation models + summary: List all conversation models + tags: + - conversations + post: + summary: Create a conversation model + description: Create a Conversation Model + operationId: createConversationModel + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelCreateSchema' + required: true + responses: + '201': + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelSchema' + description: Created Conversation Model + '400': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Bad request, see error message for details + tags: + - conversations + /conversations/models/{modelId}: + get: + description: Retrieve a conversation model + operationId: retrieveConversationModel + parameters: + - name: modelId + in: path + description: The id of the conversation model to retrieve + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelSchema' + description: A conversation model + summary: Retrieve a conversation model + tags: + - conversations + put: + description: Update a conversation model + operationId: updateConversationModel + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelUpdateSchema' + required: true + parameters: + - name: modelId + in: path + description: The id of the conversation model to update + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelSchema' + description: The conversation model was successfully updated + summary: Update a conversation model + tags: + - conversations + delete: + description: Delete a conversation model + operationId: deleteConversationModel + parameters: + - name: modelId + in: path + description: The id of the conversation model to delete + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelSchema' + description: The conversation model was successfully deleted + summary: Delete a conversation model + tags: + - conversations + /keys: + get: + tags: + - keys + summary: Retrieve (metadata about) all keys. + operationId: getKeys + responses: + '200': + description: List of all keys + content: + application/json: + schema: + $ref: '#/components/schemas/ApiKeysResponse' + post: + tags: + - keys + summary: Create an API Key + description: Create an API Key with fine-grain access control. You can restrict access on both a per-collection and per-action level. The generated key is returned only during creation. You want to store this key carefully in a secure place. + operationId: createKey + requestBody: + description: The object that describes API key scope + content: + application/json: + schema: + $ref: '#/components/schemas/ApiKeySchema' + responses: + '201': + description: Created API key + content: + application/json: + schema: + $ref: '#/components/schemas/ApiKey' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + '409': + description: API key generation conflict + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /keys/{keyId}: + get: + tags: + - keys + summary: Retrieve (metadata about) a key + description: Retrieve (metadata about) a key. Only the key prefix is returned when you retrieve a key. Due to security reasons, only the create endpoint returns the full API key. + operationId: getKey + parameters: + - name: keyId + in: path + description: The ID of the key to retrieve + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: The key referenced by the ID + content: + application/json: + schema: + $ref: '#/components/schemas/ApiKey' + '404': + description: The key was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - keys + summary: Delete an API key given its ID. + operationId: deleteKey + parameters: + - name: keyId + in: path + description: The ID of the key to delete + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: The key referenced by the ID + content: + application/json: + schema: + $ref: '#/components/schemas/ApiKeyDeleteResponse' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + '404': + description: Key not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /aliases: + get: + tags: + - collections + summary: List all aliases + description: List all aliases and the corresponding collections that they map to. + operationId: getAliases + responses: + '200': + description: List of all collection aliases + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionAliasesResponse' + /aliases/{aliasName}: + put: + tags: + - collections + summary: Create or update a collection alias + description: Create or update a collection alias. An alias is a virtual collection name that points to a real collection. If you're familiar with symbolic links on Linux, it's very similar to that. Aliases are useful when you want to reindex your data in the background on a new collection and switch your application to it without any changes to your code. + operationId: upsertAlias + parameters: + - name: aliasName + in: path + description: The name of the alias to create/update + required: true + schema: + type: string + requestBody: + description: Collection alias to be created/updated + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionAliasSchema' + responses: + '200': + description: The collection alias was created/updated + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionAlias' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + '404': + description: Alias not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + get: + tags: + - collections + summary: Retrieve an alias + description: Find out which collection an alias points to by fetching it + operationId: getAlias + parameters: + - name: aliasName + in: path + description: The name of the alias to retrieve + required: true + schema: + type: string + responses: + '200': + description: Collection alias fetched + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionAlias' + '404': + description: The alias was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - collections + summary: Delete an alias + operationId: deleteAlias + parameters: + - name: aliasName + in: path + description: The name of the alias to delete + required: true + schema: + type: string + responses: + '200': + description: Collection alias was deleted + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionAlias' + '404': + description: Alias not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /debug: + get: + tags: + - debug + summary: Print debugging information + description: Print debugging information + operationId: debug + responses: + '200': + description: Debugging information + content: + application/json: + schema: + type: object + properties: + version: + type: string + /health: + get: + tags: + - health + summary: Checks if Typesense server is ready to accept requests. + description: Checks if Typesense server is ready to accept requests. + operationId: health + responses: + '200': + description: Search service is ready for requests. + content: + application/json: + schema: + $ref: '#/components/schemas/HealthStatus' + /operations/schema_changes: + get: + tags: + - operations + summary: Get the status of in-progress schema change operations + description: Returns the status of any ongoing schema change operations. If no schema changes are in progress, returns an empty response. + operationId: getSchemaChanges + responses: + '200': + description: List of schema changes in progress + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SchemaChangeStatus' + /operations/snapshot: + post: + tags: + - operations + summary: Creates a point-in-time snapshot of a Typesense node's state and data in the specified directory. + description: Creates a point-in-time snapshot of a Typesense node's state and data in the specified directory. You can then backup the snapshot directory that gets created and later restore it as a data directory, as needed. + operationId: takeSnapshot + parameters: + - name: snapshot_path + in: query + description: The directory on the server where the snapshot should be saved. + required: true + schema: + type: string + responses: + '201': + description: Snapshot is created. + content: + application/json: + schema: + $ref: '#/components/schemas/SuccessStatus' + /operations/vote: + post: + tags: + - operations + summary: Triggers a follower node to initiate the raft voting process, which triggers leader re-election. + description: Triggers a follower node to initiate the raft voting process, which triggers leader re-election. The follower node that you run this operation against will become the new leader, once this command succeeds. + operationId: vote + responses: + '200': + description: Re-election is performed. + content: + application/json: + schema: + $ref: '#/components/schemas/SuccessStatus' + /operations/cache/clear: + post: + tags: + - operations + summary: Clear the cached responses of search requests in the LRU cache. + description: Clear the cached responses of search requests that are sent with `use_cache` parameter in the LRU cache. + operationId: clearCache + responses: + '200': + description: Clear cache succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/SuccessStatus' + /operations/db/compact: + post: + tags: + - operations + summary: Compacting the on-disk database + description: Typesense uses RocksDB to store your documents on the disk. If you do frequent writes or updates, you could benefit from running a compaction of the underlying RocksDB database. This could reduce the size of the database and decrease read latency. While the database will not block during this operation, we recommend running it during off-peak hours. + operationId: compactDb + responses: + '200': + description: Compacting the on-disk database succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/SuccessStatus' + /config: + post: + tags: + - operations + summary: Toggle Slow Request Log + description: Enable logging of requests that take over a defined threshold of time. Default is `-1` which disables slow request logging. Slow requests are logged to the primary log file, with the prefix SLOW REQUEST. + operationId: toggleSlowRequestLog + requestBody: + content: + application/json: + schema: + type: object + properties: + log-slow-requests-time-ms: + type: integer + required: + - log-slow-requests-time-ms + example: | + {"log-slow-requests-time-ms": 2000} + responses: + '200': + description: Compacting the on-disk database succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/SuccessStatus' + /multi_search: + post: + operationId: multiSearch + tags: + - documents + summary: send multiple search requests in a single HTTP request + description: This is especially useful to avoid round-trip network latencies incurred otherwise if each of these requests are sent in separate HTTP requests. You can also use this feature to do a federated search across multiple collections in a single HTTP request. + parameters: + - name: q + in: query + schema: + description: The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. + type: string + - name: query_by + in: query + schema: + description: A list of `string` fields that should be queried against. Multiple fields are separated with a comma. + type: string + - name: query_by_weights + in: query + schema: + description: The relative weight to give each `query_by` field when ranking results. This can be used to boost fields in priority, when looking for matches. Multiple fields are separated with a comma. + type: string + - name: text_match_type + in: query + schema: + description: In a multi-field matching context, this parameter determines how the representative text match score of a record is calculated. Possible values are max_score (default) or max_weight. + type: string + - name: prefix + in: query + schema: + description: Boolean field to indicate that the last word in the query should be treated as a prefix, and not as a whole word. This is used for building autocomplete and instant search interfaces. Defaults to true. + type: string + - name: infix + in: query + schema: + description: If infix index is enabled for this field, infix searching can be done on a per-field basis by sending a comma separated string parameter called infix to the search query. This parameter can have 3 values; `off` infix search is disabled, which is default `always` infix search is performed along with regular search `fallback` infix search is performed if regular search does not produce results + type: string + - name: max_extra_prefix + in: query + schema: + description: There are also 2 parameters that allow you to control the extent of infix searching max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before or after the query that can be present in the token. For example query "K2100" has 2 extra symbols in "6PK2100". By default, any number of prefixes/suffixes can be present for a match. + type: integer + - name: max_extra_suffix + in: query + schema: + description: There are also 2 parameters that allow you to control the extent of infix searching max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before or after the query that can be present in the token. For example query "K2100" has 2 extra symbols in "6PK2100". By default, any number of prefixes/suffixes can be present for a match. + type: integer + - name: filter_by + in: query + schema: + description: Filter conditions for refining youropen api validator search results. Separate multiple conditions with &&. + type: string + example: 'num_employees:>100 && country: [USA, UK]' + - name: sort_by + in: query + schema: + description: A list of numerical fields and their corresponding sort orders that will be used for ordering your results. Up to 3 sort fields can be specified. The text similarity score is exposed as a special `_text_match` field that you can use in the list of sorting fields. If no `sort_by` parameter is specified, results are sorted by `_text_match:desc,default_sorting_field:desc` + type: string + - name: facet_by + in: query + schema: + description: A list of fields that will be used for faceting your results on. Separate multiple fields with a comma. + type: string + - name: max_facet_values + in: query + schema: + description: Maximum number of facet values to be returned. + type: integer + - name: facet_query + in: query + schema: + description: Facet values that are returned can now be filtered via this parameter. The matching facet text is also highlighted. For example, when faceting by `category`, you can set `facet_query=category:shoe` to return only facet values that contain the prefix "shoe". + type: string + - name: num_typos + in: query + schema: + description: | + The number of typographical errors (1 or 2) that would be tolerated. Default: 2 + type: string + - name: page + in: query + schema: + description: Results from this specific page number would be fetched. + type: integer + - name: per_page + in: query + schema: + description: 'Number of results to fetch per page. Default: 10' + type: integer + - name: limit + in: query + schema: + description: | + Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. + type: integer + - name: offset + in: query + schema: + description: Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. + type: integer + - name: group_by + in: query + schema: + description: You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. + type: string + - name: group_limit + in: query + schema: + description: | + Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 + type: integer + - name: group_missing_values + in: query + schema: + description: | + Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true + type: boolean + - name: include_fields + in: query + schema: + description: List of fields from the document to include in the search result + type: string + - name: exclude_fields + in: query + schema: + description: List of fields from the document to exclude in the search result + type: string + - name: highlight_full_fields + in: query + schema: + description: List of fields which should be highlighted fully without snippeting + type: string + - name: highlight_affix_num_tokens + in: query + schema: + description: | + The number of tokens that should surround the highlighted text on each side. Default: 4 + type: integer + - name: highlight_start_tag + in: query + schema: + description: | + The start tag used for the highlighted snippets. Default: `` + type: string + - name: highlight_end_tag + in: query + schema: + description: | + The end tag used for the highlighted snippets. Default: `` + type: string + - name: snippet_threshold + in: query + schema: + description: | + Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 + type: integer + - name: drop_tokens_threshold + in: query + schema: + description: | + If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 + type: integer + - name: drop_tokens_mode + in: query + schema: + $ref: '#/components/schemas/DropTokensMode' + - name: typo_tokens_threshold + in: query + schema: + description: | + If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 + type: integer + - name: enable_typos_for_alpha_numerical_tokens + in: query + schema: + type: boolean + description: | + Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + - name: filter_curated_hits + in: query + schema: + type: boolean + description: | + Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + - name: enable_synonyms + in: query + schema: + type: boolean + description: | + If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + - name: enable_analytics + in: query + schema: + description: | + Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). + type: boolean + default: true + - name: synonym_prefix + in: query + schema: + type: boolean + description: | + Allow synonym resolution on word prefixes in the query. Default: false + - name: synonym_num_typos + in: query + schema: + type: integer + description: | + Allow synonym resolution on typo-corrected words in the query. Default: 0 + - name: pinned_hits + in: query + schema: + description: | + A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. + You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + type: string + - name: hidden_hits + in: query + schema: + description: | + A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. + You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + type: string + - name: override_tags + in: query + schema: + description: Comma separated list of tags to trigger the curations rules that match the tags. + type: string + - name: highlight_fields + in: query + schema: + description: | + A list of custom fields that must be highlighted even if you don't query for them + type: string + - name: pre_segmented_query + in: query + schema: + description: | + You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. + Set this parameter to true to do the same + type: boolean + default: false + - name: preset + in: query + schema: + description: | + Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. + type: string + - name: enable_overrides + in: query + schema: + description: | + If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false + type: boolean + default: false + - name: prioritize_exact_match + in: query + schema: + description: | + Set this parameter to true to ensure that an exact match is ranked above the others + type: boolean + default: true + - name: prioritize_token_position + in: query + schema: + description: | + Make Typesense prioritize documents where the query words appear earlier in the text. + type: boolean + default: false + - name: prioritize_num_matching_fields + in: query + schema: + description: | + Make Typesense prioritize documents where the query words appear in more number of fields. + type: boolean + default: true + - name: enable_typos_for_numerical_tokens + in: query + schema: + description: | + Make Typesense disable typos for numerical tokens. + type: boolean + default: true + - name: exhaustive_search + in: query + schema: + description: | + Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). + type: boolean + - name: search_cutoff_ms + in: query + schema: + description: | + Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. + type: integer + - name: use_cache + in: query + schema: + description: | + Enable server side caching of search query results. By default, caching is disabled. + type: boolean + - name: cache_ttl + in: query + schema: + description: | + The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. + type: integer + - name: min_len_1typo + in: query + schema: + description: | + Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + type: integer + - name: min_len_2typo + in: query + schema: + description: | + Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + type: integer + - name: vector_query + in: query + schema: + description: | + Vector query expression for fetching documents "closest" to a given query/document vector. + type: string + - name: remote_embedding_timeout_ms + in: query + schema: + description: | + Timeout (in milliseconds) for fetching remote embeddings. + type: integer + - name: remote_embedding_num_tries + in: query + schema: + description: | + Number of times to retry fetching remote embeddings. + type: integer + - name: facet_strategy + in: query + schema: + description: | + Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). + type: string + - name: stopwords + in: query + schema: + description: | + Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. + type: string + - name: facet_return_parent + in: query + schema: + description: | + Comma separated string of nested facet fields whose parent object should be returned in facet response. + type: string + - name: voice_query + in: query + schema: + description: | + The base64 encoded audio file in 16 khz 16-bit WAV format. + type: string + - name: conversation + in: query + schema: + description: | + Enable conversational search. + type: boolean + - name: conversation_model_id + in: query + schema: + description: | + The Id of Conversation Model to be used. + type: string + - name: conversation_id + in: query + schema: + description: | + The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/MultiSearchSearchesParameter' + responses: + '200': + description: Search results + content: + application/json: + schema: + $ref: '#/components/schemas/MultiSearchResult' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /analytics/events: + post: + tags: + - analytics + summary: Create an analytics event + description: Submit a single analytics event. The event must correspond to an existing analytics rule by name. + operationId: createAnalyticsEvent + requestBody: + description: The analytics event to be created + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsEvent' + required: true + responses: + '200': + description: Analytics event successfully created + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsEventCreateResponse' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + get: + tags: + - analytics + summary: Retrieve analytics events + description: Retrieve the most recent events for a user and rule. + operationId: getAnalyticsEvents + parameters: + - name: user_id + in: query + required: true + schema: + type: string + - name: name + in: query + description: Analytics rule name + required: true + schema: + type: string + - name: n + in: query + description: Number of events to return (max 1000) + required: true + schema: + type: integer + responses: + '200': + description: Events fetched + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsEventsResponse' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /analytics/flush: + post: + tags: + - analytics + summary: Flush in-memory analytics to disk + description: Triggers a flush of analytics data to persistent storage. + operationId: flushAnalytics + responses: + '200': + description: Flush triggered + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsEventCreateResponse' + /analytics/status: + get: + tags: + - analytics + summary: Get analytics subsystem status + description: Returns sizes of internal analytics buffers and queues. + operationId: getAnalyticsStatus + responses: + '200': + description: Status fetched + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsStatus' + /analytics/rules: + post: + tags: + - analytics + summary: Create analytics rule(s) + description: Create one or more analytics rules. You can send a single rule object or an array of rule objects. + operationId: createAnalyticsRule + requestBody: + description: The analytics rule(s) to be created + content: + application/json: + schema: + oneOf: + - $ref: '#/components/schemas/AnalyticsRuleCreate' + - type: array + items: + $ref: '#/components/schemas/AnalyticsRuleCreate' + required: true + responses: + '200': + description: Analytics rule(s) successfully created + content: + application/json: + schema: + oneOf: + - $ref: '#/components/schemas/AnalyticsRule' + - type: array + items: + anyOf: + - $ref: '#/components/schemas/AnalyticsRule' + - type: object + properties: + error: + type: string + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + get: + tags: + - analytics + summary: Retrieve analytics rules + description: Retrieve all analytics rules. Use the optional rule_tag filter to narrow down results. + operationId: retrieveAnalyticsRules + parameters: + - in: query + name: rule_tag + schema: + type: string + required: false + description: Filter rules by rule_tag + responses: + '200': + description: Analytics rules fetched + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/AnalyticsRule' + /analytics/rules/{ruleName}: + put: + tags: + - analytics + summary: Upserts an analytics rule + description: Upserts an analytics rule with the given name. + operationId: upsertAnalyticsRule + parameters: + - in: path + name: ruleName + description: The name of the analytics rule to upsert + schema: + type: string + required: true + requestBody: + description: The Analytics rule to be upserted + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsRuleUpdate' + required: true + responses: + '200': + description: Analytics rule successfully upserted + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsRule' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + get: + tags: + - analytics + summary: Retrieves an analytics rule + description: Retrieve the details of an analytics rule, given it's name + operationId: retrieveAnalyticsRule + parameters: + - in: path + name: ruleName + description: The name of the analytics rule to retrieve + schema: + type: string + required: true + responses: + '200': + description: Analytics rule fetched + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsRule' + '404': + description: Analytics rule not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - analytics + summary: Delete an analytics rule + description: Permanently deletes an analytics rule, given it's name + operationId: deleteAnalyticsRule + parameters: + - in: path + name: ruleName + description: The name of the analytics rule to delete + schema: + type: string + required: true + responses: + '200': + description: Analytics rule deleted + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsRule' + '404': + description: Analytics rule not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /metrics.json: + get: + tags: + - operations + summary: Get current RAM, CPU, Disk & Network usage metrics. + description: Retrieve the metrics. + operationId: retrieveMetrics + responses: + '200': + description: Metrics fetched. + content: + application/json: + schema: + type: object + /stats.json: + get: + tags: + - operations + summary: Get stats about API endpoints. + description: Retrieve the stats about API endpoints. + operationId: retrieveAPIStats + responses: + '200': + description: Stats fetched. + content: + application/json: + schema: + $ref: '#/components/schemas/APIStatsResponse' + /stopwords: + get: + tags: + - stopwords + summary: Retrieves all stopwords sets. + description: Retrieve the details of all stopwords sets + operationId: retrieveStopwordsSets + responses: + '200': + description: Stopwords sets fetched. + content: + application/json: + schema: + $ref: '#/components/schemas/StopwordsSetsRetrieveAllSchema' + /stopwords/{setId}: + put: + tags: + - stopwords + summary: Upserts a stopwords set. + description: When an analytics rule is created, we give it a name and describe the type, the source collections and the destination collection. + operationId: upsertStopwordsSet + parameters: + - in: path + name: setId + description: The ID of the stopwords set to upsert. + schema: + type: string + required: true + example: countries + requestBody: + description: The stopwords set to upsert. + content: + application/json: + schema: + $ref: '#/components/schemas/StopwordsSetUpsertSchema' + required: true + responses: + '200': + description: Stopwords set successfully upserted. + content: + application/json: + schema: + $ref: '#/components/schemas/StopwordsSetSchema' + '400': + description: Bad request, see error message for details. + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + get: + tags: + - stopwords + summary: Retrieves a stopwords set. + description: Retrieve the details of a stopwords set, given it's name. + operationId: retrieveStopwordsSet + parameters: + - in: path + name: setId + description: The ID of the stopwords set to retrieve. + schema: + type: string + required: true + example: countries + responses: + '200': + description: Stopwords set fetched. + content: + application/json: + schema: + $ref: '#/components/schemas/StopwordsSetRetrieveSchema' + '404': + description: Stopwords set not found. + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - stopwords + summary: Delete a stopwords set. + description: Permanently deletes a stopwords set, given it's name. + operationId: deleteStopwordsSet + parameters: + - in: path + name: setId + description: The ID of the stopwords set to delete. + schema: + type: string + required: true + example: countries + responses: + '200': + description: Stopwords set rule deleted. + content: + application/json: + schema: + type: object + properties: + id: + type: string + required: + - id + example: | + {"id": "countries"} + '404': + description: Stopwords set not found. + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /presets: + get: + tags: + - presets + summary: Retrieves all presets. + description: Retrieve the details of all presets + operationId: retrieveAllPresets + responses: + '200': + description: Presets fetched. + content: + application/json: + schema: + $ref: '#/components/schemas/PresetsRetrieveSchema' + /presets/{presetId}: + get: + tags: + - presets + summary: Retrieves a preset. + description: Retrieve the details of a preset, given it's name. + operationId: retrievePreset + parameters: + - in: path + name: presetId + description: The ID of the preset to retrieve. + schema: + type: string + required: true + example: listing_view + responses: + '200': + description: Preset fetched. + content: + application/json: + schema: + $ref: '#/components/schemas/PresetSchema' + '404': + description: Preset not found. + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + put: + tags: + - presets + summary: Upserts a preset. + description: Create or update an existing preset. + operationId: upsertPreset + parameters: + - in: path + name: presetId + description: The name of the preset set to upsert. + schema: + type: string + required: true + example: listing_view + requestBody: + description: The stopwords set to upsert. + content: + application/json: + schema: + $ref: '#/components/schemas/PresetUpsertSchema' + required: true + responses: + '200': + description: Preset successfully upserted. + content: + application/json: + schema: + $ref: '#/components/schemas/PresetSchema' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - presets + summary: Delete a preset. + description: Permanently deletes a preset, given it's name. + operationId: deletePreset + parameters: + - in: path + name: presetId + description: The ID of the preset to delete. + schema: + type: string + required: true + example: listing_view + responses: + '200': + description: Preset deleted. + content: + application/json: + schema: + $ref: '#/components/schemas/PresetDeleteSchema' + '404': + description: Preset not found. + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /stemming/dictionaries: + get: + tags: + - stemming + summary: List all stemming dictionaries + description: Retrieve a list of all available stemming dictionaries. + operationId: listStemmingDictionaries + responses: + '200': + description: List of all dictionaries + content: + application/json: + schema: + type: object + properties: + dictionaries: + type: array + items: + type: string + example: + - irregular-plurals + - company-terms + /stemming/dictionaries/{dictionaryId}: + get: + tags: + - stemming + summary: Retrieve a stemming dictionary + description: Fetch details of a specific stemming dictionary. + operationId: getStemmingDictionary + parameters: + - name: dictionaryId + in: path + description: The ID of the dictionary to retrieve + required: true + schema: + type: string + example: irregular-plurals + responses: + '200': + description: Stemming dictionary details + content: + application/json: + schema: + $ref: '#/components/schemas/StemmingDictionary' + '404': + description: Dictionary not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /stemming/dictionaries/import: + post: + tags: + - stemming + summary: Import a stemming dictionary + description: Upload a JSONL file containing word mappings to create or update a stemming dictionary. + operationId: importStemmingDictionary + parameters: + - name: id + in: query + description: The ID to assign to the dictionary + required: true + schema: + type: string + example: irregular-plurals + requestBody: + description: The JSONL file containing word mappings + required: true + content: + application/json: + schema: + type: string + example: | + {"word": "people", "root": "person"} + {"word": "children", "root": "child"} + responses: + '200': + description: Dictionary successfully imported + content: + application/octet-stream: + schema: + type: string + example: | + {"word": "people", "root": "person"} {"word": "children", "root": "child"} + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /nl_search_models: + get: + tags: + - nl_search_models + summary: List all NL search models + description: Retrieve all NL search models. + operationId: retrieveAllNLSearchModels + responses: + '200': + description: List of all NL search models + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/NLSearchModelSchema' + post: + tags: + - nl_search_models + summary: Create a NL search model + description: Create a new NL search model. + operationId: createNLSearchModel + requestBody: + description: The NL search model to be created + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelCreateSchema' + required: true + responses: + '201': + description: NL search model successfully created + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelSchema' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /nl_search_models/{modelId}: + get: + tags: + - nl_search_models + summary: Retrieve a NL search model + description: Retrieve a specific NL search model by its ID. + operationId: retrieveNLSearchModel + parameters: + - name: modelId + in: path + description: The ID of the NL search model to retrieve + required: true + schema: + type: string + responses: + '200': + description: NL search model fetched + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelSchema' + '404': + description: NL search model not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + put: + tags: + - nl_search_models + summary: Update a NL search model + description: Update an existing NL search model. + operationId: updateNLSearchModel + parameters: + - name: modelId + in: path + description: The ID of the NL search model to update + required: true + schema: + type: string + requestBody: + description: The NL search model fields to update + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelUpdateSchema' + required: true + responses: + '200': + description: NL search model successfully updated + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelSchema' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + '404': + description: NL search model not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - nl_search_models + summary: Delete a NL search model + description: Delete a specific NL search model by its ID. + operationId: deleteNLSearchModel + parameters: + - name: modelId + in: path + description: The ID of the NL search model to delete + required: true + schema: + type: string + responses: + '200': + description: NL search model successfully deleted + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelDeleteSchema' + '404': + description: NL search model not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' +components: + schemas: + CollectionSchema: + required: + - name + - fields + type: object + properties: + name: + type: string + description: Name of the collection + example: companies + fields: + type: array + description: A list of fields for querying, filtering and faceting + example: + - name: num_employees + type: int32 + facet: false + - name: company_name + type: string + facet: false + - name: country + type: string + facet: true + items: + $ref: '#/components/schemas/Field' + default_sorting_field: + type: string + description: The name of an int32 / float field that determines the order in which the search results are ranked when a sort_by clause is not provided during searching. This field must indicate some kind of popularity. + example: num_employees + default: '' + token_separators: + type: array + description: | + List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. + items: + type: string + minLength: 1 + maxLength: 1 + default: [] + synonym_sets: + type: array + description: List of synonym set names to associate with this collection + items: + type: string + example: synonym_set_1 + enable_nested_fields: + type: boolean + description: Enables experimental support at a collection level for nested object or object array fields. This field is only available if the Typesense server is version `0.24.0.rcn34` or later. + default: false + example: true + symbols_to_index: + type: array + description: | + List of symbols or special characters to be indexed. + items: + type: string + minLength: 1 + maxLength: 1 + default: [] + voice_query_model: + $ref: '#/components/schemas/VoiceQueryModelCollectionConfig' + metadata: + type: object + description: | + Optional details about the collection, e.g., when it was created, who created it etc. + CollectionUpdateSchema: + required: + - fields + type: object + properties: + fields: + type: array + description: A list of fields for querying, filtering and faceting + example: + - name: company_name + type: string + facet: false + - name: num_employees + type: int32 + facet: false + - name: country + type: string + facet: true + items: + $ref: '#/components/schemas/Field' + synonym_sets: + type: array + description: List of synonym set names to associate with this collection + items: + type: string + example: synonym_set_1 + metadata: + type: object + description: | + Optional details about the collection, e.g., when it was created, who created it etc. + CollectionResponse: + allOf: + - $ref: '#/components/schemas/CollectionSchema' + - type: object + required: + - num_documents + - created_at + properties: + num_documents: + type: integer + description: Number of documents in the collection + format: int64 + readOnly: true + created_at: + type: integer + description: Timestamp of when the collection was created (Unix epoch in seconds) + format: int64 + readOnly: true + Field: + required: + - name + - type + type: object + properties: + name: + type: string + example: company_name + type: + type: string + example: string + optional: + type: boolean + example: true + facet: + type: boolean + example: false + index: + type: boolean + example: true + default: true + locale: + type: string + example: el + sort: + type: boolean + example: true + infix: + type: boolean + example: true + default: false + reference: + type: string + description: | + Name of a field in another collection that should be linked to this collection so that it can be joined during query. + num_dim: + type: integer + example: 256 + drop: + type: boolean + example: true + store: + type: boolean + description: | + When set to false, the field value will not be stored on disk. Default: true. + vec_dist: + type: string + description: | + The distance metric to be used for vector search. Default: `cosine`. You can also use `ip` for inner product. + range_index: + type: boolean + description: | + Enables an index optimized for range filtering on numerical fields (e.g. rating:>3.5). Default: false. + stem: + type: boolean + description: | + Values are stemmed before indexing in-memory. Default: false. + stem_dictionary: + type: string + description: Name of the stemming dictionary to use for this field + example: irregular-plurals + token_separators: + type: array + description: | + List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. + items: + type: string + minLength: 1 + maxLength: 1 + default: [] + symbols_to_index: + type: array + description: | + List of symbols or special characters to be indexed. + items: + type: string + minLength: 1 + maxLength: 1 + default: [] + embed: + type: object + required: + - from + - model_config + properties: + from: + type: array + items: + type: string + model_config: + type: object + required: + - model_name + properties: + model_name: + type: string + api_key: + type: string + url: + type: string + access_token: + type: string + refresh_token: + type: string + client_id: + type: string + client_secret: + type: string + project_id: + type: string + indexing_prefix: + type: string + query_prefix: + type: string + VoiceQueryModelCollectionConfig: + type: object + description: | + Configuration for the voice query model + properties: + model_name: + type: string + example: ts/whisper/base.en + CollectionAliasSchema: + type: object + required: + - collection_name + properties: + collection_name: + type: string + description: Name of the collection you wish to map the alias to + CollectionAlias: + type: object + required: + - collection_name + - name + properties: + name: + type: string + readOnly: true + description: Name of the collection alias + collection_name: + type: string + description: Name of the collection the alias mapped to + CollectionAliasesResponse: + type: object + required: + - aliases + properties: + aliases: + type: array + x-go-type: '[]*CollectionAlias' + items: + $ref: '#/components/schemas/CollectionAlias' + SearchResult: + type: object + x-rust-generic-parameter: + properties: + facet_counts: + type: array + items: + $ref: '#/components/schemas/FacetCounts' + found: + type: integer + description: The number of documents found + found_docs: + type: integer + search_time_ms: + type: integer + description: The number of milliseconds the search took + out_of: + type: integer + description: The total number of documents in the collection + search_cutoff: + type: boolean + description: Whether the search was cut off + page: + type: integer + description: The search result page number + grouped_hits: + type: array + items: + $ref: '#/components/schemas/SearchGroupedHit' + hits: + type: array + description: The documents that matched the search query + items: + $ref: '#/components/schemas/SearchResultHit' + x-rust-type: Option>> + request_params: + $ref: '#/components/schemas/SearchRequestParams' + conversation: + $ref: '#/components/schemas/SearchResultConversation' + union_request_params: + type: array + description: Returned only for union query response. + items: + $ref: '#/components/schemas/SearchRequestParams' + SearchRequestParams: + type: object + required: + - collection_name + - q + - per_page + properties: + collection_name: + type: string + q: + type: string + per_page: + type: integer + voice_query: + type: object + properties: + transcribed_query: + type: string + SearchResultConversation: + type: object + required: + - answer + - conversation_history + - conversation_id + - query + properties: + answer: + type: string + conversation_history: + type: array + items: + type: object + conversation_id: + type: string + query: + type: string + SearchGroupedHit: + type: object + required: + - group_key + - hits + properties: + found: + type: integer + group_key: + type: array + items: {} + hits: + type: array + description: The documents that matched the search query + items: + $ref: '#/components/schemas/SearchResultHit' + SearchResultHit: + type: object + x-rust-generic-parameter: + properties: + highlights: + type: array + description: (Deprecated) Contains highlighted portions of the search fields + items: + $ref: '#/components/schemas/SearchHighlight' + highlight: + type: object + description: Highlighted version of the matching document + additionalProperties: true + document: + type: object + x-rust-type: Option + description: Can be any key-value pair + additionalProperties: + type: object + text_match: + type: integer + format: int64 + text_match_info: + type: object + properties: + best_field_score: + type: string + best_field_weight: + type: integer + fields_matched: + type: integer + num_tokens_dropped: + type: integer + format: int64 + x-go-type: uint64 + score: + type: string + tokens_matched: + type: integer + typo_prefix_score: + type: integer + geo_distance_meters: + type: object + description: Can be any key-value pair + additionalProperties: + type: integer + vector_distance: + type: number + format: float + description: Distance between the query vector and matching document's vector value + hybrid_search_info: + type: object + description: Information about hybrid search scoring + properties: + rank_fusion_score: + type: number + format: float + description: Combined score from rank fusion of text and vector search + search_index: + type: integer + description: Returned only for union query response. Indicates the index of the query which this document matched to. + example: + highlights: + company_name: + field: company_name + snippet: Stark Industries + document: + id: '124' + company_name: Stark Industries + num_employees: 5215 + country: USA + text_match: 1234556 + SearchHighlight: + type: object + properties: + field: + type: string + example: company_name + snippet: + type: string + description: Present only for (non-array) string fields + example: Stark Industries + snippets: + type: array + description: Present only for (array) string[] fields + example: + - Stark Industries + - Stark Corp + items: + type: string + value: + type: string + description: Full field value with highlighting, present only for (non-array) string fields + example: Stark Industries is a major supplier of space equipment. + values: + type: array + description: Full field value with highlighting, present only for (array) string[] fields + example: + - Stark Industries + - Stark Corp + items: + type: string + indices: + type: array + description: The indices property will be present only for string[] fields and will contain the corresponding indices of the snippets in the search field + example: 1 + items: + type: integer + matched_tokens: + type: array + items: + type: object + x-go-type: interface{} + SearchOverrideSchema: + type: object + required: + - rule + properties: + rule: + $ref: '#/components/schemas/SearchOverrideRule' + includes: + type: array + description: List of document `id`s that should be included in the search results with their corresponding `position`s. + items: + $ref: '#/components/schemas/SearchOverrideInclude' + excludes: + type: array + description: List of document `id`s that should be excluded from the search results. + items: + $ref: '#/components/schemas/SearchOverrideExclude' + filter_by: + type: string + description: | + A filter by clause that is applied to any search query that matches the override rule. + remove_matched_tokens: + type: boolean + description: | + Indicates whether search query tokens that exist in the override's rule should be removed from the search query. + metadata: + type: object + description: | + Return a custom JSON object in the Search API response, when this rule is triggered. This can can be used to display a pre-defined message (eg: a promotion banner) on the front-end when a particular rule is triggered. + sort_by: + type: string + description: | + A sort by clause that is applied to any search query that matches the override rule. + replace_query: + type: string + description: | + Replaces the current search query with this value, when the search query matches the override rule. + filter_curated_hits: + type: boolean + description: | + When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. + effective_from_ts: + type: integer + description: | + A Unix timestamp that indicates the date/time from which the override will be active. You can use this to create override rules that start applying from a future point in time. + effective_to_ts: + type: integer + description: | + A Unix timestamp that indicates the date/time until which the override will be active. You can use this to create override rules that stop applying after a period of time. + stop_processing: + type: boolean + description: | + When set to true, override processing will stop at the first matching rule. When set to false override processing will continue and multiple override actions will be triggered in sequence. Overrides are processed in the lexical sort order of their id field. Default: true. + SearchOverride: + allOf: + - $ref: '#/components/schemas/SearchOverrideSchema' + - type: object + required: + - id + properties: + id: + type: string + readOnly: true + SearchOverrideDeleteResponse: + type: object + required: + - id + properties: + id: + type: string + description: The id of the override that was deleted + SearchOverrideRule: + type: object + properties: + tags: + type: array + description: List of tag values to associate with this override rule. + items: + type: string + query: + type: string + description: Indicates what search queries should be overridden + match: + type: string + description: | + Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. + enum: + - exact + - contains + filter_by: + type: string + description: | + Indicates that the override should apply when the filter_by parameter in a search query exactly matches the string specified here (including backticks, spaces, brackets, etc). + SearchOverrideInclude: + type: object + required: + - id + - position + properties: + id: + type: string + description: document id that should be included + position: + type: integer + description: position number where document should be included in the search results + SearchOverrideExclude: + type: object + required: + - id + properties: + id: + type: string + description: document id that should be excluded from the search results. + SearchOverridesResponse: + type: object + required: + - overrides + properties: + overrides: + type: array + x-go-type: '[]*SearchOverride' + items: + $ref: '#/components/schemas/SearchOverride' + SearchSynonymSchema: + type: object + required: + - synonyms + properties: + root: + type: string + description: For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. + synonyms: + type: array + description: Array of words that should be considered as synonyms. + items: + type: string + locale: + type: string + description: Locale for the synonym, leave blank to use the standard tokenizer. + symbols_to_index: + type: array + description: By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is. + items: + type: string + SearchSynonym: + allOf: + - $ref: '#/components/schemas/SearchSynonymSchema' + - type: object + required: + - id + properties: + id: + type: string + readOnly: true + SearchSynonymDeleteResponse: + type: object + required: + - id + properties: + id: + type: string + description: The id of the synonym that was deleted + SearchSynonymsResponse: + type: object + required: + - synonyms + properties: + synonyms: + type: array + x-go-type: '[]*SearchSynonym' + items: + $ref: '#/components/schemas/SearchSynonym' + HealthStatus: + type: object + required: + - ok + properties: + ok: + type: boolean + SchemaChangeStatus: + type: object + properties: + collection: + type: string + description: Name of the collection being modified + validated_docs: + type: integer + description: Number of documents that have been validated + altered_docs: + type: integer + description: Number of documents that have been altered + SuccessStatus: + type: object + required: + - success + properties: + success: + type: boolean + ApiResponse: + type: object + required: + - message + properties: + message: + type: string + ApiKeySchema: + type: object + required: + - actions + - collections + - description + properties: + value: + type: string + description: + type: string + actions: + type: array + items: + type: string + collections: + type: array + items: + type: string + expires_at: + type: integer + format: int64 + ApiKey: + allOf: + - $ref: '#/components/schemas/ApiKeySchema' + - type: object + properties: + id: + type: integer + format: int64 + readOnly: true + value_prefix: + type: string + readOnly: true + ApiKeyDeleteResponse: + type: object + required: + - id + properties: + id: + type: integer + format: int64 + description: The id of the API key that was deleted + ApiKeysResponse: + type: object + required: + - keys + properties: + keys: + type: array + x-go-type: '[]*ApiKey' + items: + $ref: '#/components/schemas/ApiKey' + MultiSearchResult: + type: object + required: + - results + properties: + results: + type: array + items: + $ref: '#/components/schemas/MultiSearchResultItem' + conversation: + $ref: '#/components/schemas/SearchResultConversation' + MultiSearchResultItem: + allOf: + - $ref: '#/components/schemas/SearchResult' + - type: object + properties: + code: + type: integer + description: HTTP error code + format: int64 + error: + type: string + description: Error description + SearchParameters: + type: object + properties: + q: + description: The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. + type: string + query_by: + description: A list of `string` fields that should be queried against. Multiple fields are separated with a comma. + type: string + nl_query: + description: Whether to use natural language processing to parse the query. + type: boolean + nl_model_id: + description: The ID of the natural language model to use. + type: string + query_by_weights: + description: The relative weight to give each `query_by` field when ranking results. This can be used to boost fields in priority, when looking for matches. Multiple fields are separated with a comma. + type: string + text_match_type: + description: In a multi-field matching context, this parameter determines how the representative text match score of a record is calculated. Possible values are max_score (default) or max_weight. + type: string + prefix: + description: Boolean field to indicate that the last word in the query should be treated as a prefix, and not as a whole word. This is used for building autocomplete and instant search interfaces. Defaults to true. + type: string + infix: + description: If infix index is enabled for this field, infix searching can be done on a per-field basis by sending a comma separated string parameter called infix to the search query. This parameter can have 3 values; `off` infix search is disabled, which is default `always` infix search is performed along with regular search `fallback` infix search is performed if regular search does not produce results + type: string + max_extra_prefix: + description: There are also 2 parameters that allow you to control the extent of infix searching max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before or after the query that can be present in the token. For example query "K2100" has 2 extra symbols in "6PK2100". By default, any number of prefixes/suffixes can be present for a match. + type: integer + max_extra_suffix: + description: There are also 2 parameters that allow you to control the extent of infix searching max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before or after the query that can be present in the token. For example query "K2100" has 2 extra symbols in "6PK2100". By default, any number of prefixes/suffixes can be present for a match. + type: integer + filter_by: + description: Filter conditions for refining your open api validator search results. Separate multiple conditions with &&. + type: string + example: 'num_employees:>100 && country: [USA, UK]' + max_filter_by_candidates: + description: Controls the number of similar words that Typesense considers during fuzzy search on filter_by values. Useful for controlling prefix matches like company_name:Acm*. + type: integer + sort_by: + description: A list of numerical fields and their corresponding sort orders that will be used for ordering your results. Up to 3 sort fields can be specified. The text similarity score is exposed as a special `_text_match` field that you can use in the list of sorting fields. If no `sort_by` parameter is specified, results are sorted by `_text_match:desc,default_sorting_field:desc` + type: string + example: num_employees:desc + facet_by: + description: A list of fields that will be used for faceting your results on. Separate multiple fields with a comma. + type: string + max_facet_values: + description: Maximum number of facet values to be returned. + type: integer + facet_query: + description: Facet values that are returned can now be filtered via this parameter. The matching facet text is also highlighted. For example, when faceting by `category`, you can set `facet_query=category:shoe` to return only facet values that contain the prefix "shoe". + type: string + num_typos: + description: | + The number of typographical errors (1 or 2) that would be tolerated. Default: 2 + type: string + page: + description: Results from this specific page number would be fetched. + type: integer + per_page: + description: 'Number of results to fetch per page. Default: 10' + type: integer + limit: + description: | + Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. + type: integer + offset: + description: Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. + type: integer + group_by: + description: You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. + type: string + group_limit: + description: | + Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 + type: integer + group_missing_values: + description: | + Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true + type: boolean + include_fields: + description: List of fields from the document to include in the search result + type: string + exclude_fields: + description: List of fields from the document to exclude in the search result + type: string + highlight_full_fields: + description: List of fields which should be highlighted fully without snippeting + type: string + highlight_affix_num_tokens: + description: | + The number of tokens that should surround the highlighted text on each side. Default: 4 + type: integer + highlight_start_tag: + description: | + The start tag used for the highlighted snippets. Default: `` + type: string + highlight_end_tag: + description: | + The end tag used for the highlighted snippets. Default: `` + type: string + enable_highlight_v1: + description: | + Flag for enabling/disabling the deprecated, old highlight structure in the response. Default: true + type: boolean + default: true + enable_analytics: + description: | + Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). + type: boolean + default: true + snippet_threshold: + description: | + Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 + type: integer + synonym_sets: + type: string + description: List of synonym set names to associate with this search query + example: synonym_set_1,synonym_set_2 + drop_tokens_threshold: + description: | + If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 + type: integer + drop_tokens_mode: + $ref: '#/components/schemas/DropTokensMode' + typo_tokens_threshold: + description: | + If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 + type: integer + enable_typos_for_alpha_numerical_tokens: + type: boolean + description: | + Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + filter_curated_hits: + type: boolean + description: | + Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + enable_synonyms: + type: boolean + description: | + If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + synonym_prefix: + type: boolean + description: | + Allow synonym resolution on word prefixes in the query. Default: false + synonym_num_typos: + type: integer + description: | + Allow synonym resolution on typo-corrected words in the query. Default: 0 + pinned_hits: + description: | + A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. + You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + type: string + hidden_hits: + description: | + A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. + You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + type: string + override_tags: + description: Comma separated list of tags to trigger the curations rules that match the tags. + type: string + highlight_fields: + description: | + A list of custom fields that must be highlighted even if you don't query for them + type: string + split_join_tokens: + description: | + Treat space as typo: search for q=basket ball if q=basketball is not found or vice-versa. Splitting/joining of tokens will only be attempted if the original query produces no results. To always trigger this behavior, set value to `always``. To disable, set value to `off`. Default is `fallback`. + type: string + pre_segmented_query: + description: | + You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. + Set this parameter to true to do the same + type: boolean + preset: + description: | + Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. + type: string + enable_overrides: + description: | + If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false + type: boolean + default: false + prioritize_exact_match: + description: | + Set this parameter to true to ensure that an exact match is ranked above the others + type: boolean + default: true + max_candidates: + description: | + Control the number of words that Typesense considers for typo and prefix searching. + type: integer + prioritize_token_position: + description: | + Make Typesense prioritize documents where the query words appear earlier in the text. + type: boolean + default: false + prioritize_num_matching_fields: + description: | + Make Typesense prioritize documents where the query words appear in more number of fields. + type: boolean + default: true + enable_typos_for_numerical_tokens: + description: | + Make Typesense disable typos for numerical tokens. + type: boolean + default: true + exhaustive_search: + description: | + Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). + type: boolean + search_cutoff_ms: + description: | + Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. + type: integer + use_cache: + description: | + Enable server side caching of search query results. By default, caching is disabled. + type: boolean + cache_ttl: + description: | + The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. + type: integer + min_len_1typo: + description: | + Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + type: integer + min_len_2typo: + description: | + Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + type: integer + vector_query: + description: | + Vector query expression for fetching documents "closest" to a given query/document vector. + type: string + remote_embedding_timeout_ms: + description: | + Timeout (in milliseconds) for fetching remote embeddings. + type: integer + remote_embedding_num_tries: + description: | + Number of times to retry fetching remote embeddings. + type: integer + facet_strategy: + description: | + Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). + type: string + stopwords: + description: | + Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. + type: string + facet_return_parent: + description: | + Comma separated string of nested facet fields whose parent object should be returned in facet response. + type: string + voice_query: + description: | + The base64 encoded audio file in 16 khz 16-bit WAV format. + type: string + conversation: + description: | + Enable conversational search. + type: boolean + conversation_model_id: + description: | + The Id of Conversation Model to be used. + type: string + conversation_id: + description: | + The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + type: string + MultiSearchParameters: + description: | + Parameters for the multi search API. + type: object + properties: + q: + description: The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. + type: string + query_by: + description: A list of `string` fields that should be queried against. Multiple fields are separated with a comma. + type: string + query_by_weights: + description: The relative weight to give each `query_by` field when ranking results. This can be used to boost fields in priority, when looking for matches. Multiple fields are separated with a comma. + type: string + text_match_type: + description: In a multi-field matching context, this parameter determines how the representative text match score of a record is calculated. Possible values are max_score (default) or max_weight. + type: string + prefix: + description: Boolean field to indicate that the last word in the query should be treated as a prefix, and not as a whole word. This is used for building autocomplete and instant search interfaces. Defaults to true. + type: string + infix: + description: If infix index is enabled for this field, infix searching can be done on a per-field basis by sending a comma separated string parameter called infix to the search query. This parameter can have 3 values; `off` infix search is disabled, which is default `always` infix search is performed along with regular search `fallback` infix search is performed if regular search does not produce results + type: string + max_extra_prefix: + description: There are also 2 parameters that allow you to control the extent of infix searching max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before or after the query that can be present in the token. For example query "K2100" has 2 extra symbols in "6PK2100". By default, any number of prefixes/suffixes can be present for a match. + type: integer + max_extra_suffix: + description: There are also 2 parameters that allow you to control the extent of infix searching max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before or after the query that can be present in the token. For example query "K2100" has 2 extra symbols in "6PK2100". By default, any number of prefixes/suffixes can be present for a match. + type: integer + filter_by: + description: Filter conditions for refining youropen api validator search results. Separate multiple conditions with &&. + type: string + example: 'num_employees:>100 && country: [USA, UK]' + sort_by: + description: A list of numerical fields and their corresponding sort orders that will be used for ordering your results. Up to 3 sort fields can be specified. The text similarity score is exposed as a special `_text_match` field that you can use in the list of sorting fields. If no `sort_by` parameter is specified, results are sorted by `_text_match:desc,default_sorting_field:desc` + type: string + facet_by: + description: A list of fields that will be used for faceting your results on. Separate multiple fields with a comma. + type: string + max_facet_values: + description: Maximum number of facet values to be returned. + type: integer + facet_query: + description: Facet values that are returned can now be filtered via this parameter. The matching facet text is also highlighted. For example, when faceting by `category`, you can set `facet_query=category:shoe` to return only facet values that contain the prefix "shoe". + type: string + num_typos: + description: | + The number of typographical errors (1 or 2) that would be tolerated. Default: 2 + type: string + page: + description: Results from this specific page number would be fetched. + type: integer + per_page: + description: 'Number of results to fetch per page. Default: 10' + type: integer + limit: + description: | + Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. + type: integer + offset: + description: Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. + type: integer + group_by: + description: You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. + type: string + group_limit: + description: | + Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 + type: integer + group_missing_values: + description: | + Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true + type: boolean + include_fields: + description: List of fields from the document to include in the search result + type: string + exclude_fields: + description: List of fields from the document to exclude in the search result + type: string + highlight_full_fields: + description: List of fields which should be highlighted fully without snippeting + type: string + highlight_affix_num_tokens: + description: | + The number of tokens that should surround the highlighted text on each side. Default: 4 + type: integer + highlight_start_tag: + description: | + The start tag used for the highlighted snippets. Default: `` + type: string + highlight_end_tag: + description: | + The end tag used for the highlighted snippets. Default: `` + type: string + snippet_threshold: + description: | + Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 + type: integer + drop_tokens_threshold: + description: | + If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 + type: integer + drop_tokens_mode: + $ref: '#/components/schemas/DropTokensMode' + typo_tokens_threshold: + description: | + If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 + type: integer + enable_typos_for_alpha_numerical_tokens: + type: boolean + description: | + Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + filter_curated_hits: + type: boolean + description: | + Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + enable_synonyms: + type: boolean + description: | + If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + enable_analytics: + description: | + Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). + type: boolean + default: true + synonym_prefix: + type: boolean + description: | + Allow synonym resolution on word prefixes in the query. Default: false + synonym_num_typos: + type: integer + description: | + Allow synonym resolution on typo-corrected words in the query. Default: 0 + pinned_hits: + description: | + A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. + You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + type: string + hidden_hits: + description: | + A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. + You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + type: string + override_tags: + description: Comma separated list of tags to trigger the curations rules that match the tags. + type: string + highlight_fields: + description: | + A list of custom fields that must be highlighted even if you don't query for them + type: string + pre_segmented_query: + description: | + You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. + Set this parameter to true to do the same + type: boolean + default: false + preset: + description: | + Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. + type: string + enable_overrides: + description: | + If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false + type: boolean + default: false + prioritize_exact_match: + description: | + Set this parameter to true to ensure that an exact match is ranked above the others + type: boolean + default: true + prioritize_token_position: + description: | + Make Typesense prioritize documents where the query words appear earlier in the text. + type: boolean + default: false + prioritize_num_matching_fields: + description: | + Make Typesense prioritize documents where the query words appear in more number of fields. + type: boolean + default: true + enable_typos_for_numerical_tokens: + description: | + Make Typesense disable typos for numerical tokens. + type: boolean + default: true + exhaustive_search: + description: | + Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). + type: boolean + search_cutoff_ms: + description: | + Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. + type: integer + use_cache: + description: | + Enable server side caching of search query results. By default, caching is disabled. + type: boolean + cache_ttl: + description: | + The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. + type: integer + min_len_1typo: + description: | + Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + type: integer + min_len_2typo: + description: | + Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + type: integer + vector_query: + description: | + Vector query expression for fetching documents "closest" to a given query/document vector. + type: string + remote_embedding_timeout_ms: + description: | + Timeout (in milliseconds) for fetching remote embeddings. + type: integer + remote_embedding_num_tries: + description: | + Number of times to retry fetching remote embeddings. + type: integer + facet_strategy: + description: | + Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). + type: string + stopwords: + description: | + Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. + type: string + facet_return_parent: + description: | + Comma separated string of nested facet fields whose parent object should be returned in facet response. + type: string + voice_query: + description: | + The base64 encoded audio file in 16 khz 16-bit WAV format. + type: string + conversation: + description: | + Enable conversational search. + type: boolean + conversation_model_id: + description: | + The Id of Conversation Model to be used. + type: string + conversation_id: + description: | + The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + type: string + MultiSearchSearchesParameter: + type: object + required: + - searches + properties: + union: + type: boolean + default: false + description: When true, merges the search results from each search query into a single ordered set of hits. + searches: + type: array + items: + $ref: '#/components/schemas/MultiSearchCollectionParameters' + MultiSearchCollectionParameters: + allOf: + - $ref: '#/components/schemas/MultiSearchParameters' + - type: object + properties: + collection: + type: string + description: | + The collection to search in. + x-typesense-api-key: + type: string + description: A separate search API key for each search within a multi_search request + rerank_hybrid_matches: + type: boolean + description: | + When true, computes both text match and vector distance scores for all matches in hybrid search. Documents found only through keyword search will get a vector distance score, and documents found only through vector search will get a text match score. + default: false + FacetCounts: + type: object + properties: + counts: + type: array + items: + type: object + properties: + count: + type: integer + highlighted: + type: string + value: + type: string + parent: + type: object + field_name: + type: string + stats: + type: object + properties: + max: + type: number + format: double + min: + type: number + format: double + sum: + type: number + format: double + total_values: + type: integer + avg: + type: number + format: double + AnalyticsEventCreateResponse: + type: object + required: + - ok + properties: + ok: + type: boolean + AnalyticsEvent: + type: object + required: + - name + - event_type + - data + properties: + name: + type: string + description: Name of the analytics rule this event corresponds to + event_type: + type: string + description: Type of event (e.g., click, conversion, query, visit) + data: + type: object + description: Event payload + properties: + user_id: + type: string + doc_id: + type: string + doc_ids: + type: array + items: + type: string + q: + type: string + analytics_tag: + type: string + AnalyticsEventsResponse: + type: object + required: + - events + properties: + events: + type: array + items: + type: object + properties: + name: + type: string + event_type: + type: string + collection: + type: string + timestamp: + type: integer + format: int64 + user_id: + type: string + doc_id: + type: string + doc_ids: + type: array + items: + type: string + query: + type: string + AnalyticsRuleCreate: + type: object + required: + - name + - type + - collection + - event_type + properties: + name: + type: string + type: + type: string + enum: + - popular_queries + - nohits_queries + - counter + - log + collection: + type: string + event_type: + type: string + rule_tag: + type: string + params: + type: object + properties: + destination_collection: + type: string + limit: + type: integer + capture_search_requests: + type: boolean + meta_fields: + type: array + items: + type: string + expand_query: + type: boolean + counter_field: + type: string + weight: + type: integer + AnalyticsRuleUpdate: + type: object + description: Fields allowed to update on an analytics rule + properties: + name: + type: string + rule_tag: + type: string + params: + type: object + properties: + destination_collection: + type: string + limit: + type: integer + capture_search_requests: + type: boolean + meta_fields: + type: array + items: + type: string + expand_query: + type: boolean + counter_field: + type: string + weight: + type: integer + AnalyticsRule: + allOf: + - $ref: '#/components/schemas/AnalyticsRuleCreate' + - type: object + AnalyticsStatus: + type: object + properties: + popular_prefix_queries: + type: integer + nohits_prefix_queries: + type: integer + log_prefix_queries: + type: integer + query_log_events: + type: integer + query_counter_events: + type: integer + doc_log_events: + type: integer + doc_counter_events: + type: integer + APIStatsResponse: + type: object + properties: + delete_latency_ms: + type: number + format: double + delete_requests_per_second: + type: number + format: double + import_latency_ms: + type: number + format: double + import_requests_per_second: + type: number + format: double + latency_ms: + type: object + x-go-type: map[string]float64 + overloaded_requests_per_second: + type: number + format: double + pending_write_batches: + type: number + format: double + requests_per_second: + type: object + x-go-type: map[string]float64 + search_latency_ms: + type: number + format: double + search_requests_per_second: + type: number + format: double + total_requests_per_second: + type: number + format: double + write_latency_ms: + type: number + format: double + write_requests_per_second: + type: number + format: double + StopwordsSetUpsertSchema: + type: object + properties: + stopwords: + type: array + items: + type: string + locale: + type: string + required: + - stopwords + example: | + {"stopwords": ["Germany", "France", "Italy"], "locale": "en"} + StopwordsSetSchema: + type: object + properties: + id: + type: string + stopwords: + type: array + items: + type: string + locale: + type: string + required: + - id + - stopwords + example: | + {"id": "countries", "stopwords": ["Germany", "France", "Italy"], "locale": "en"} + StopwordsSetRetrieveSchema: + type: object + properties: + stopwords: + $ref: '#/components/schemas/StopwordsSetSchema' + required: + - stopwords + example: | + {"stopwords": {"id": "countries", "stopwords": ["Germany", "France", "Italy"], "locale": "en"}} + StopwordsSetsRetrieveAllSchema: + type: object + properties: + stopwords: + type: array + items: + $ref: '#/components/schemas/StopwordsSetSchema' + required: + - stopwords + example: | + {"stopwords": [{"id": "countries", "stopwords": ["Germany", "France", "Italy"], "locale": "en"}]} + PresetUpsertSchema: + properties: + value: + oneOf: + - $ref: '#/components/schemas/SearchParameters' + - $ref: '#/components/schemas/MultiSearchSearchesParameter' + required: + - value + PresetSchema: + allOf: + - $ref: '#/components/schemas/PresetUpsertSchema' + - type: object + required: + - name + properties: + name: + type: string + PresetsRetrieveSchema: + type: object + required: + - presets + properties: + presets: + type: array + items: + $ref: '#/components/schemas/PresetSchema' + x-go-type: '[]*PresetSchema' + PresetDeleteSchema: + type: object + required: + - name + properties: + name: + type: string + DirtyValues: + type: string + enum: + - coerce_or_reject + - coerce_or_drop + - drop + - reject + IndexAction: + type: string + enum: + - create + - update + - upsert + - emplace + DropTokensMode: + type: string + enum: + - right_to_left + - left_to_right + - both_sides:3 + description: | + Dictates the direction in which the words in the query must be dropped when the original words in the query do not appear in any document. Values: right_to_left (default), left_to_right, both_sides:3 A note on both_sides:3 - for queries up to 3 tokens (words) in length, this mode will drop tokens from both sides and exhaustively rank all matching results. If query length is greater than 3 words, Typesense will just fallback to default behavior of right_to_left + ConversationModelCreateSchema: + required: + - model_name + - max_bytes + allOf: + - $ref: '#/components/schemas/ConversationModelUpdateSchema' + - type: object + required: + - model_name + - max_bytes + - history_collection + properties: + model_name: + description: Name of the LLM model offered by OpenAI, Cloudflare or vLLM + type: string + max_bytes: + description: | + The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. + type: integer + history_collection: + type: string + description: Typesense collection that stores the historical conversations + ConversationModelUpdateSchema: + type: object + properties: + id: + type: string + description: An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. + model_name: + description: Name of the LLM model offered by OpenAI, Cloudflare or vLLM + type: string + api_key: + description: The LLM service's API Key + type: string + history_collection: + type: string + description: Typesense collection that stores the historical conversations + account_id: + description: LLM service's account ID (only applicable for Cloudflare) + type: string + system_prompt: + description: The system prompt that contains special instructions to the LLM + type: string + ttl: + type: integer + description: | + Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) + max_bytes: + description: | + The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. + type: integer + vllm_url: + description: URL of vLLM service + type: string + ConversationModelSchema: + allOf: + - $ref: '#/components/schemas/ConversationModelCreateSchema' + - type: object + required: + - id + properties: + id: + type: string + description: An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. + StemmingDictionary: + type: object + required: + - id + - words + properties: + id: + type: string + description: Unique identifier for the dictionary + example: irregular-plurals + words: + type: array + description: List of word mappings in the dictionary + items: + type: object + required: + - word + - root + properties: + word: + type: string + description: The word form to be stemmed + example: people + root: + type: string + description: The root form of the word + example: person + NLSearchModelBase: + type: object + properties: + model_name: + type: string + description: Name of the NL model to use + api_key: + type: string + description: API key for the NL model service + api_url: + type: string + description: Custom API URL for the NL model service + max_bytes: + type: integer + description: Maximum number of bytes to process + temperature: + type: number + description: Temperature parameter for the NL model + system_prompt: + type: string + description: System prompt for the NL model + top_p: + type: number + description: Top-p parameter for the NL model (Google-specific) + top_k: + type: integer + description: Top-k parameter for the NL model (Google-specific) + stop_sequences: + type: array + items: + type: string + description: Stop sequences for the NL model (Google-specific) + api_version: + type: string + description: API version for the NL model service + project_id: + type: string + description: Project ID for GCP Vertex AI + access_token: + type: string + description: Access token for GCP Vertex AI + refresh_token: + type: string + description: Refresh token for GCP Vertex AI + client_id: + type: string + description: Client ID for GCP Vertex AI + client_secret: + type: string + description: Client secret for GCP Vertex AI + region: + type: string + description: Region for GCP Vertex AI + max_output_tokens: + type: integer + description: Maximum output tokens for GCP Vertex AI + account_id: + type: string + description: Account ID for Cloudflare-specific models + NLSearchModelCreateSchema: + allOf: + - $ref: '#/components/schemas/NLSearchModelBase' + - type: object + properties: + id: + type: string + description: Optional ID for the NL search model + NLSearchModelSchema: + allOf: + - $ref: '#/components/schemas/NLSearchModelCreateSchema' + - type: object + required: + - id + properties: + id: + type: string + description: ID of the NL search model + NLSearchModelUpdateSchema: + $ref: '#/components/schemas/NLSearchModelCreateSchema' + NLSearchModelDeleteSchema: + type: object + required: + - id + properties: + id: + type: string + description: ID of the deleted NL search model + SynonymItemSchema: + type: object + required: + - id + - synonyms + properties: + id: + type: string + description: Unique identifier for the synonym item + synonyms: + type: array + description: Array of words that should be considered as synonyms + items: + type: string + root: + type: string + description: For 1-way synonyms, indicates the root word that words in the synonyms parameter map to + locale: + type: string + description: Locale for the synonym, leave blank to use the standard tokenizer + symbols_to_index: + type: array + description: By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is + items: + type: string + SynonymSetCreateSchema: + type: object + required: + - items + properties: + items: + type: array + description: Array of synonym items + items: + $ref: '#/components/schemas/SynonymItemSchema' + SynonymSetSchema: + allOf: + - $ref: '#/components/schemas/SynonymSetCreateSchema' + - type: object + required: + - name + properties: + name: + type: string + description: Name of the synonym set + SynonymSetsRetrieveSchema: + type: object + required: + - synonym_sets + properties: + synonym_sets: + type: array + description: Array of synonym sets + items: + $ref: '#/components/schemas/SynonymSetSchema' + SynonymSetRetrieveSchema: + $ref: '#/components/schemas/SynonymSetCreateSchema' + SynonymSetDeleteSchema: + type: object + required: + - name + properties: + name: + type: string + description: Name of the deleted synonym set + ImportDocumentsParameters: + type: object + properties: + batch_size: + type: integer + return_id: + type: boolean + description: Returning the id of the imported documents. If you want the import response to return the ingested document's id in the response, you can use the return_id parameter. + remote_embedding_batch_size: + type: integer + return_doc: + type: boolean + action: + $ref: '#/components/schemas/IndexAction' + dirty_values: + $ref: '#/components/schemas/DirtyValues' + ExportDocumentsParameters: + type: object + properties: + filter_by: + description: Filter conditions for refining your search results. Separate multiple conditions with &&. + type: string + include_fields: + description: List of fields from the document to include in the search result + type: string + exclude_fields: + description: List of fields from the document to exclude in the search result + type: string + UpdateDocumentsParameters: + type: object + properties: + filter_by: + type: string + example: 'num_employees:>100 && country: [USA, UK]' + DeleteDocumentsParameters: + type: object + required: + - filter_by + properties: + filter_by: + type: string + example: 'num_employees:>100 && country: [USA, UK]' + batch_size: + description: Batch size parameter controls the number of documents that should be deleted at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. + type: integer + ignore_not_found: + type: boolean + truncate: + description: When true, removes all documents from the collection while preserving the collection and its schema. + type: boolean + GetCollectionsParameters: + type: object + properties: + exclude_fields: + description: Comma-separated list of fields from the collection to exclude from the response + type: string + limit: + description: | + Number of collections to fetch. Default: returns all collections. + type: integer + offset: + description: Identifies the starting point to return collections when paginating. + type: integer + securitySchemes: + api_key_header: + type: apiKey + name: X-TYPESENSE-API-KEY + in: header diff --git a/typesense/Cargo.toml b/typesense/Cargo.toml index f1a0491..479f3a1 100644 --- a/typesense/Cargo.toml +++ b/typesense/Cargo.toml @@ -26,18 +26,37 @@ serde_json = "1.0" sha2 = "0.10" typesense_derive = { workspace = true, optional = true } typesense_codegen = { workspace = true } +thiserror = "1.0" +bon = "3.7.0" +reqwest-retry = "0.7.0" +web-time = "=1.1.0" # required for wasm32 target + +# native-only dependencies +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +reqwest = { version = "0.12", features = ["json"] } +reqwest-middleware = { version = "0.4.2"} + +# wasm deps +[target.'cfg(target_arch = "wasm32")'.dependencies] +# IMPORTANT: disable default features to avoid hyper/tokio/mio +reqwest = { version = "0.12", default-features = false, features = ["json"] } [dev-dependencies] dotenvy = "0.15" trybuild = "1.0.42" +nanoid = "0.4" +# native-only dev deps [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] tokio = { version = "1.5", features = ["macros", "rt", "rt-multi-thread"] } +wiremock = "0.5" +# wasm test deps [target.'cfg(target_arch = "wasm32")'.dev-dependencies] console_error_panic_hook = "0.1.6" wasm-bindgen = "0.2" wasm-bindgen-test = "0.3.23" +wasm-bindgen-futures = "0.4.50" [[test]] name = "derive_tests" diff --git a/typesense/src/builders/mod.rs b/typesense/src/builders/mod.rs new file mode 100644 index 0000000..662b21e --- /dev/null +++ b/typesense/src/builders/mod.rs @@ -0,0 +1,13 @@ +//! Contain convenient builders for Typesense schemas. + +mod multi_search_collection_parameters; +mod multi_search_parameters; +mod multi_search_searches_parameters; + +pub use multi_search_collection_parameters::{ + MultiSearchCollectionParametersBuilder, new_multi_search_collection_parameters, +}; +pub use multi_search_parameters::{MultiSearchParametersBuilder, new_multi_search_parameters}; +pub use multi_search_searches_parameters::{ + MultiSearchSearchesParameterBuilder, new_multi_search_searches_parameter, +}; diff --git a/typesense/src/builders/multi_search_collection_parameters.rs b/typesense/src/builders/multi_search_collection_parameters.rs new file mode 100644 index 0000000..5cad599 --- /dev/null +++ b/typesense/src/builders/multi_search_collection_parameters.rs @@ -0,0 +1,265 @@ +//! Module for the `MultiSearchCollectionParameters` builder. + +use crate::models::{DropTokensMode, MultiSearchCollectionParameters}; +use bon::builder; + +/// Creates a new [`MultiSearchCollectionParameters`] builder. +/// +/// This builder helps construct an individual search query for a multi-search request. +/// All parameters are optional. +#[builder( + // expose a public builder type and a public finish_fn + builder_type(name = MultiSearchCollectionParametersBuilder, vis = "pub"), + finish_fn(name = build, vis = "pub"), + // allow passing &str into String params + on(String, into) +)] +pub fn new_multi_search_collection_parameters( + /// The collection to search in. + collection: Option, + /// The query text to search for in the collection. + q: Option, + /// A list of `string` fields that should be queried against. + query_by: Option, + /// The relative weight to give each `query_by` field when ranking results. + query_by_weights: Option, + /// How the representative text match score is calculated. + text_match_type: Option, + /// Indicates if the last word in the query should be treated as a prefix. + prefix: Option, + /// Infix search configuration. Can be `off`, `always`, or `fallback`. + infix: Option, + /// Maximum number of extra symbols before a query token for infix searching. + max_extra_prefix: Option, + /// Maximum number of extra symbols after a query token for infix searching. + max_extra_suffix: Option, + /// Filter conditions for refining search results. + filter_by: Option, + /// A list of fields and their sort orders. + sort_by: Option, + /// A list of fields to facet by. + facet_by: Option, + /// Maximum number of facet values to be returned. + max_facet_values: Option, + /// A query to filter facet values. + facet_query: Option, + /// The number of typographical errors (1 or 2) that would be tolerated. + num_typos: Option, + /// The page number to fetch. + page: Option, + /// Number of results to fetch per page. + per_page: Option, + /// Number of hits to fetch. + limit: Option, + /// The starting point of the result set. + offset: Option, + /// Fields to group results by. + group_by: Option, + /// Maximum number of hits to return for every group. + group_limit: Option, + /// Whether to group documents with null values in the `group_by` field. + group_missing_values: Option, + /// List of fields to include in the search result. + include_fields: Option, + /// List of fields to exclude from the search result. + exclude_fields: Option, + /// List of fields which should be highlighted fully. + highlight_full_fields: Option, + /// The number of tokens surrounding the highlighted text. + highlight_affix_num_tokens: Option, + /// The start tag for highlighted snippets. + highlight_start_tag: Option, + /// The end tag for highlighted snippets. + highlight_end_tag: Option, + /// Field values under this length will be fully highlighted. + snippet_threshold: Option, + /// Threshold for dropping query tokens to find more results. + drop_tokens_threshold: Option, + drop_tokens_mode: Option, + /// Threshold for trying more typos to find more results. + typo_tokens_threshold: Option, + /// Whether to enable typos on alphanumerical tokens. + enable_typos_for_alpha_numerical_tokens: Option, + /// Whether the `filter_by` condition applies to curated results. + filter_curated_hits: Option, + /// Whether to enable synonyms for the query. + enable_synonyms: Option, + /// Allow synonym resolution on word prefixes. + synonym_prefix: Option, + /// Number of typos allowed for synonym resolution. + synonym_num_typos: Option, + /// A list of records to unconditionally include at specific positions. + pinned_hits: Option, + /// A list of records to unconditionally hide from search results. + hidden_hits: Option, + /// Comma-separated list of tags to trigger curation rules. + override_tags: Option, + /// A list of custom fields that must be highlighted. + highlight_fields: Option, + /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same + pre_segmented_query: Option, + /// Search using a preset of search parameters. + preset: Option, + /// Whether to enable overrides for the query. + enable_overrides: Option, + /// Whether to prioritize an exact match. + prioritize_exact_match: Option, + /// Prioritize documents where query words appear earlier in the text. + prioritize_token_position: Option, + /// Prioritize documents where query words appear in more fields. + prioritize_num_matching_fields: Option, + /// Disable typos for numerical tokens. + enable_typos_for_numerical_tokens: Option, + /// Whether to perform an exhaustive search. + exhaustive_search: Option, + /// Search cutoff time in milliseconds. + search_cutoff_ms: Option, + /// Enable server-side caching of search results. + use_cache: Option, + /// The TTL for the search query cache. + cache_ttl: Option, + /// Minimum word length for 1-typo correction. + min_len_1typo: Option, + /// Minimum word length for 2-typo correction. + min_len_2typo: Option, + /// Vector query expression. + vector_query: Option, + /// Timeout for fetching remote embeddings. + remote_embedding_timeout_ms: Option, + /// Number of retries for fetching remote embeddings. + remote_embedding_num_tries: Option, + /// The underlying faceting strategy to use. + facet_strategy: Option, + /// Name of the stopwords set to apply for this search. + stopwords: Option, + /// Nested facet fields whose parent object should be returned. + facet_return_parent: Option, + /// The base64 encoded audio file. + voice_query: Option, + /// Enable conversational search. + conversation: Option, + /// The ID of the Conversation Model to use. + conversation_model_id: Option, + /// The ID of a previous conversation to continue. + conversation_id: Option, + /// A separate search API key for this specific search. + x_typesense_api_key: Option, + /// When true, computes both text match and vector distance scores for all matches in hybrid search. + rerank_hybrid_matches: Option, +) -> MultiSearchCollectionParameters { + MultiSearchCollectionParameters { + collection, + q, + query_by, + query_by_weights, + text_match_type, + prefix, + infix, + max_extra_prefix, + max_extra_suffix, + filter_by, + sort_by, + facet_by, + max_facet_values, + facet_query, + num_typos, + page, + per_page, + limit, + offset, + group_by, + group_limit, + group_missing_values, + include_fields, + exclude_fields, + highlight_full_fields, + highlight_affix_num_tokens, + highlight_start_tag, + highlight_end_tag, + snippet_threshold, + drop_tokens_threshold, + drop_tokens_mode, + typo_tokens_threshold, + enable_typos_for_alpha_numerical_tokens, + filter_curated_hits, + enable_synonyms, + synonym_prefix, + synonym_num_typos, + pinned_hits, + hidden_hits, + override_tags, + highlight_fields, + pre_segmented_query, + preset, + enable_overrides, + prioritize_exact_match, + prioritize_token_position, + prioritize_num_matching_fields, + enable_typos_for_numerical_tokens, + exhaustive_search, + search_cutoff_ms, + use_cache, + cache_ttl, + min_len_1typo, + min_len_2typo, + vector_query, + remote_embedding_timeout_ms, + remote_embedding_num_tries, + facet_strategy, + stopwords, + facet_return_parent, + voice_query, + conversation, + conversation_model_id, + conversation_id, + x_typesense_api_key, + rerank_hybrid_matches, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::models::MultiSearchCollectionParameters; + + #[test] + fn test_multi_search_collection_parameters_builder_basic() { + let built = new_multi_search_collection_parameters() + .collection("products") + .q("phone") + .limit(10) + .build(); + + let expected = MultiSearchCollectionParameters { + collection: Some("products".to_string()), + q: Some("phone".to_string()), + limit: Some(10), + ..Default::default() + }; + + assert_eq!(built, expected); + } + + #[test] + fn test_multi_search_collection_parameters_builder_api_key() { + let built = new_multi_search_collection_parameters() + .collection("private_docs") + .x_typesense_api_key("specific_key_for_this_search") + .build(); + + let expected = MultiSearchCollectionParameters { + collection: Some("private_docs".to_string()), + x_typesense_api_key: Some("specific_key_for_this_search".to_string()), + ..Default::default() + }; + + assert_eq!(built, expected); + } + + #[test] + fn test_multi_search_collection_parameters_builder_defaults() { + let built = new_multi_search_collection_parameters().build(); + let expected = MultiSearchCollectionParameters::default(); + assert_eq!(built, expected); + } +} diff --git a/typesense/src/builders/multi_search_parameters.rs b/typesense/src/builders/multi_search_parameters.rs new file mode 100644 index 0000000..9375697 --- /dev/null +++ b/typesense/src/builders/multi_search_parameters.rs @@ -0,0 +1,260 @@ +//! Module for the `MultiSearchParameters` builder. + +use crate::models::{DropTokensMode, MultiSearchParameters}; +use bon::builder; + +/// Creates a new [`MultiSearchParameters`] builder. +/// +/// This builder helps construct a set of common search parameters that can be applied +/// to all search queries within a multi-search request. +#[builder( + // expose a public builder type and a public finish_fn + builder_type(name = MultiSearchParametersBuilder, vis = "pub"), + finish_fn(name = build, vis = "pub"), + // allow passing &str into String params + on(String, into) +)] +pub fn new_multi_search_parameters( + /// The query text to search for in the collection. + q: Option, + /// A list of `string` fields that should be queried against. + query_by: Option, + /// The relative weight to give each `query_by` field when ranking results. + query_by_weights: Option, + /// How the representative text match score is calculated. + text_match_type: Option, + /// Indicates if the last word in the query should be treated as a prefix. + prefix: Option, + /// Infix search configuration. Can be `off`, `always`, or `fallback`. + infix: Option, + /// Maximum number of extra symbols before a query token for infix searching. + max_extra_prefix: Option, + /// Maximum number of extra symbols after a query token for infix searching. + max_extra_suffix: Option, + /// Filter conditions for refining search results. + filter_by: Option, + /// A list of fields and their sort orders. + sort_by: Option, + /// A list of fields to facet by. + facet_by: Option, + /// Maximum number of facet values to be returned. + max_facet_values: Option, + /// A query to filter facet values. + facet_query: Option, + /// The number of typographical errors (1 or 2) that would be tolerated. + num_typos: Option, + /// The page number to fetch. + page: Option, + /// Number of results to fetch per page. + per_page: Option, + /// Number of hits to fetch. + limit: Option, + /// The starting point of the result set. + offset: Option, + /// Fields to group results by. + group_by: Option, + /// Maximum number of hits to return for every group. + group_limit: Option, + /// Whether to group documents with null values in the `group_by` field. + group_missing_values: Option, + /// List of fields to include in the search result. + include_fields: Option, + /// List of fields to exclude from the search result. + exclude_fields: Option, + /// List of fields which should be highlighted fully. + highlight_full_fields: Option, + /// The number of tokens surrounding the highlighted text. + highlight_affix_num_tokens: Option, + /// The start tag for highlighted snippets. + highlight_start_tag: Option, + /// The end tag for highlighted snippets. + highlight_end_tag: Option, + /// Field values under this length will be fully highlighted. + snippet_threshold: Option, + /// Threshold for dropping query tokens to find more results. + drop_tokens_threshold: Option, + drop_tokens_mode: Option, + /// Threshold for trying more typos to find more results. + typo_tokens_threshold: Option, + /// Whether to enable typos on alphanumerical tokens. + enable_typos_for_alpha_numerical_tokens: Option, + /// Whether the `filter_by` condition applies to curated results. + filter_curated_hits: Option, + /// Whether to enable synonyms for the query. + enable_synonyms: Option, + /// Allow synonym resolution on word prefixes. + synonym_prefix: Option, + /// Number of typos allowed for synonym resolution. + synonym_num_typos: Option, + /// A list of records to unconditionally include at specific positions. + pinned_hits: Option, + /// A list of records to unconditionally hide from search results. + hidden_hits: Option, + /// Comma-separated list of tags to trigger curation rules. + override_tags: Option, + /// A list of custom fields that must be highlighted. + highlight_fields: Option, + /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same + pre_segmented_query: Option, + /// Search using a preset of search parameters. + preset: Option, + /// Whether to enable overrides for the query. + enable_overrides: Option, + /// Whether to prioritize an exact match. + prioritize_exact_match: Option, + /// Prioritize documents where query words appear earlier in the text. + prioritize_token_position: Option, + /// Prioritize documents where query words appear in more fields. + prioritize_num_matching_fields: Option, + /// Disable typos for numerical tokens. + enable_typos_for_numerical_tokens: Option, + /// Whether to perform an exhaustive search. + exhaustive_search: Option, + /// Search cutoff time in milliseconds. + search_cutoff_ms: Option, + /// Enable server-side caching of search results. + use_cache: Option, + /// The TTL for the search query cache. + cache_ttl: Option, + /// Minimum word length for 1-typo correction. + min_len_1typo: Option, + /// Minimum word length for 2-typo correction. + min_len_2typo: Option, + /// Vector query expression. + vector_query: Option, + /// Timeout for fetching remote embeddings. + remote_embedding_timeout_ms: Option, + /// Number of retries for fetching remote embeddings. + remote_embedding_num_tries: Option, + /// The underlying faceting strategy to use. + facet_strategy: Option, + /// Name of the stopwords set to apply for this search. + stopwords: Option, + /// Nested facet fields whose parent object should be returned. + facet_return_parent: Option, + /// The base64 encoded audio file. + voice_query: Option, + /// Enable conversational search. + conversation: Option, + /// The ID of the Conversation Model to use. + conversation_model_id: Option, + /// The ID of a previous conversation to continue. + conversation_id: Option, +) -> MultiSearchParameters { + MultiSearchParameters { + q, + query_by, + query_by_weights, + text_match_type, + prefix, + infix, + max_extra_prefix, + max_extra_suffix, + filter_by, + sort_by, + facet_by, + max_facet_values, + facet_query, + num_typos, + page, + per_page, + limit, + offset, + group_by, + group_limit, + group_missing_values, + include_fields, + exclude_fields, + highlight_full_fields, + highlight_affix_num_tokens, + highlight_start_tag, + highlight_end_tag, + snippet_threshold, + drop_tokens_threshold, + drop_tokens_mode, + typo_tokens_threshold, + enable_typos_for_alpha_numerical_tokens, + filter_curated_hits, + enable_synonyms, + synonym_prefix, + synonym_num_typos, + pinned_hits, + hidden_hits, + override_tags, + highlight_fields, + pre_segmented_query, + preset, + enable_overrides, + prioritize_exact_match, + prioritize_token_position, + prioritize_num_matching_fields, + enable_typos_for_numerical_tokens, + exhaustive_search, + search_cutoff_ms, + use_cache, + cache_ttl, + min_len_1typo, + min_len_2typo, + vector_query, + remote_embedding_timeout_ms, + remote_embedding_num_tries, + facet_strategy, + stopwords, + facet_return_parent, + voice_query, + conversation, + conversation_model_id, + conversation_id, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::models::{DropTokensMode, MultiSearchParameters}; + + #[test] + fn test_multi_search_parameters_builder_basic() { + let built = new_multi_search_parameters() + .query_by("title") + .per_page(5) + .build(); + + let expected = MultiSearchParameters { + query_by: Some("title".to_string()), + per_page: Some(5), + ..Default::default() + }; + + assert_eq!(built, expected); + } + + #[test] + fn test_multi_search_parameters_builder_full() { + let built = new_multi_search_parameters() + .q("*") + .filter_by("category:shoes") + .use_cache(true) + .drop_tokens_mode(DropTokensMode::LeftToRight) + .search_cutoff_ms(100) + .build(); + + let expected = MultiSearchParameters { + q: Some("*".to_string()), + filter_by: Some("category:shoes".to_string()), + use_cache: Some(true), + drop_tokens_mode: Some(DropTokensMode::LeftToRight), + search_cutoff_ms: Some(100), + ..Default::default() + }; + + assert_eq!(built, expected); + } + + #[test] + fn test_multi_search_parameters_builder_defaults() { + let built = new_multi_search_parameters().build(); + let expected = MultiSearchParameters::default(); + assert_eq!(built, expected); + } +} diff --git a/typesense/src/builders/multi_search_searches_parameters.rs b/typesense/src/builders/multi_search_searches_parameters.rs new file mode 100644 index 0000000..60a3490 --- /dev/null +++ b/typesense/src/builders/multi_search_searches_parameters.rs @@ -0,0 +1,127 @@ +//! Module for the `MultiSearchSearchesParameter` builder. + +use crate::models::{MultiSearchCollectionParameters, MultiSearchSearchesParameter}; + +/// A builder for creating a `MultiSearchSearchesParameter` object. +/// +/// This builder is used to construct the body of a multi-search request by +/// adding individual search queries one by one. +#[derive(Debug, Default)] +pub struct MultiSearchSearchesParameterBuilder { + searches: Vec, +} + +impl MultiSearchSearchesParameterBuilder { + /// Creates a new, empty builder. + pub fn new() -> Self { + Self::default() + } + + /// Adds a single search query to the multi-search request. + /// + /// # Arguments + /// + /// * `search` - A `MultiSearchCollectionParameters` object representing an + /// individual search query. + pub fn add_search(mut self, search: MultiSearchCollectionParameters) -> Self { + self.searches.push(search); + self + } + + /// Adds multiple search queries to the multi-search request from an iterator. + /// + /// # Arguments + /// + /// * `searches` - An iterator that yields `MultiSearchCollectionParameters` objects. + pub fn add_searches( + mut self, + searches: impl IntoIterator, + ) -> Self { + self.searches.extend(searches); + self + } + + /// Consumes the builder and returns a `MultiSearchSearchesParameter` object. + pub fn build(self) -> MultiSearchSearchesParameter { + MultiSearchSearchesParameter { + searches: self.searches, + } + } +} + +/// Creates a new [`MultiSearchSearchesParameterBuilder`]. +/// +/// This is the entry point for building a multi-search request body. +pub fn new_multi_search_searches_parameter() -> MultiSearchSearchesParameterBuilder { + MultiSearchSearchesParameterBuilder::new() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::builders::new_multi_search_collection_parameters; + + #[test] + fn test_multi_search_builder_new_is_empty() { + let multi_search_request = new_multi_search_searches_parameter().build(); + assert!(multi_search_request.searches.is_empty()); + } + + #[test] + fn test_multi_search_builder_add_one_search() { + let search1 = new_multi_search_collection_parameters() + .collection("products") + .q("shoe") + .build(); + + let multi_search_request = new_multi_search_searches_parameter() + .add_search(search1.clone()) + .build(); + + assert_eq!(multi_search_request.searches.len(), 1); + assert_eq!(multi_search_request.searches[0], search1); + } + + #[test] + fn test_multi_search_builder_add_multiple_searches_chained() { + let search1 = new_multi_search_collection_parameters() + .collection("products") + .q("shoe") + .build(); + let search2 = new_multi_search_collection_parameters() + .collection("brands") + .q("Nike") + .build(); + + let multi_search_request = new_multi_search_searches_parameter() + .add_search(search1.clone()) + .add_search(search2.clone()) + .build(); + + assert_eq!(multi_search_request.searches.len(), 2); + assert_eq!(multi_search_request.searches[0], search1); + assert_eq!(multi_search_request.searches[1], search2); + } + + #[test] + fn test_multi_search_builder_add_searches_from_iterator() { + let searches_vec = vec![ + new_multi_search_collection_parameters() + .collection("c1") + .build(), + new_multi_search_collection_parameters() + .collection("c2") + .build(), + new_multi_search_collection_parameters() + .collection("c3") + .build(), + ]; + + let multi_search_request = new_multi_search_searches_parameter() + .add_searches(searches_vec.clone()) + .build(); + + assert_eq!(multi_search_request.searches.len(), 3); + assert_eq!(multi_search_request.searches, searches_vec); + } +} diff --git a/typesense/src/client/collection/document.rs b/typesense/src/client/collection/document.rs new file mode 100644 index 0000000..a8a1e55 --- /dev/null +++ b/typesense/src/client/collection/document.rs @@ -0,0 +1,154 @@ +//! Provides access to API endpoints for a single document within a Typesense collection. +//! +//! An instance of `Document` is scoped to a specific document and is created +//! via a parent `Collection` struct, for example: +//! `client.collection::("books").document("123")` + +use crate::{Client, Error}; +use serde::{Serialize, de::DeserializeOwned}; +use typesense_codegen::{ + apis::{configuration, documents_api}, + models, +}; + +/// Provides methods for interacting with a single document within a specific Typesense collection. +/// +/// This struct is created by calling a method like `client.collection::("collection_name").document("document_id")`. +/// The generic `T` represents the shape of the document and must implement `Serialize` and `DeserializeOwned`. +/// If `T` is not specified, it defaults to `serde_json::Value` for schemaless interactions. +pub struct Document<'a, T = serde_json::Value> +where + T: DeserializeOwned + Serialize + Send + Sync, +{ + pub(super) client: &'a Client, + pub(super) collection_name: &'a str, + pub(super) document_id: &'a str, + pub(super) _phantom: std::marker::PhantomData, +} + +impl<'a, T> Document<'a, T> +where + T: DeserializeOwned + Serialize + Send + Sync, +{ + /// Creates a new `Document` instance for a specific document ID. + /// This is intended for internal use by the parent `Collection` struct. + pub(super) fn new(client: &'a Client, collection_name: &'a str, document_id: &'a str) -> Self { + Self { + client, + collection_name, + document_id, + _phantom: std::marker::PhantomData, + } + } + + /// Fetches this individual document from the collection and deserializes it into `T`. + /// + /// # Returns + /// A `Result` containing the strongly-typed document `T` if successful. + pub async fn retrieve(&self) -> Result> { + let params = documents_api::GetDocumentParams { + collection_name: self.collection_name.to_string(), + document_id: self.document_id.to_string(), + }; + + let result_value = self + .client + .execute(|config: configuration::Configuration| { + let params_for_move = params.clone(); + async move { documents_api::get_document(&config, params_for_move).await } + }) + .await?; + + // Deserialize the raw JSON value into the user's type T. + serde_json::from_value(result_value).map_err(Error::from) + } + + /// Updates this individual document. The update can be partial. + /// The updated full document is returned. + /// + /// # Arguments + /// * `partial_document` - A serializable struct or a `serde_json::Value` containing the fields to update. For example: `serde_json::json!({ "in_stock": false })`. + /// * `params` - An optional `DocumentIndexParameters` struct to specify additional parameters, such as `dirty_values` which determines what Typesense should do when the type of a particular field being indexed does not match the previously inferred type for that field, or the one defined in the collection's schema. + /// + /// # Returns + /// A `Result` containing the full, updated document deserialized into `T`. + /// + /// # Example + /// ```no_run + /// # use serde::{Serialize, Deserialize}; + /// # use typesense::{Client, models}; + /// # use reqwest::Url; + /// # #[derive(Serialize, Deserialize)] + /// # struct Book { id: String, title: String, pages: i32 } + /// # + /// # async fn run() -> Result<(), Box> { + /// # let client = Client::builder() + /// # .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) + /// # .api_key("xyz") + /// # .build() + /// # .unwrap(); + /// let book_update = serde_json::json!({ "pages": 654 }); + /// + /// // Simple update + /// let updated_book = client.collection_of::("books").document("123") + /// .update(&book_update, None) + /// .await?; + /// + /// // Update with additional parameters + /// let params = models::DocumentIndexParameters { + /// dirty_values: Some(models::DirtyValues::CoerceOrReject), + /// }; + /// let updated_book_with_params = client.collection_of::("books").document("124") + /// .update(&book_update, Some(params)) + /// .await?; + /// # + /// # Ok(()) + /// # } + /// ``` + pub async fn update( + &self, + partial_document: &U, + params: Option, + ) -> Result> { + let params = documents_api::UpdateDocumentParams { + collection_name: self.collection_name.to_string(), + document_id: self.document_id.to_string(), + body: serde_json::to_value(partial_document)?, + dirty_values: params.unwrap_or_default().dirty_values, + }; + + let result_value = self + .client + .execute(|config: configuration::Configuration| { + let params_for_move = params.clone(); + async move { documents_api::update_document(&config, params_for_move).await } + }) + .await?; + + // Deserialize the raw JSON value of the updated document into T. + serde_json::from_value(result_value).map_err(Error::from) + } + + /// Deletes this individual document from the collection. + /// The deleted document is returned. + /// + /// # Returns + /// A `Result` containing the deleted document deserialized into `T`. + pub async fn delete(&self) -> Result> { + let params = documents_api::DeleteDocumentParams { + collection_name: self.collection_name.to_string(), + document_id: self.document_id.to_string(), + }; + + let result_value = self + .client + .execute(|config: configuration::Configuration| { + let params_for_move = params.clone(); + async move { documents_api::delete_document(&config, params_for_move).await } + }) + .await?; + + // Deserialize the raw JSON value of the deleted document into T. + serde_json::from_value(result_value).map_err(Error::from) + } +} diff --git a/typesense/src/client/collection/documents.rs b/typesense/src/client/collection/documents.rs new file mode 100644 index 0000000..41c8cfd --- /dev/null +++ b/typesense/src/client/collection/documents.rs @@ -0,0 +1,305 @@ +//! Provides access to the document, search, and override-related API endpoints. +//! +//! An instance of `Documents` is scoped to a specific collection and is created +//! via the main `client.collection("collection_name").documents()` method or +//! `client.collection_of::("...").documents()`. + +use crate::models::DocumentIndexParameters; +use crate::models::SearchResult; +use crate::{Client, Error}; +use serde::{Serialize, de::DeserializeOwned}; +use typesense_codegen::{ + apis::{configuration, documents_api}, + models::{ + self as raw_models, DeleteDocumentsParameters, ExportDocumentsParameters, + ImportDocumentsParameters, UpdateDocumentsParameters, + }, +}; +/// Provides methods for interacting with documents within a specific Typesense collection. +/// +/// This struct is generic over the document type `T`. If created via `client.collection(...)`, +/// `T` defaults to `serde_json::Value`. If created via `client.collection_of::(...)`, +/// `T` will be `MyType`. +pub struct Documents<'a, T = serde_json::Value> +where + T: DeserializeOwned + Serialize + Send + Sync, +{ + pub(super) client: &'a Client, + pub(super) collection_name: &'a str, + pub(super) _phantom: std::marker::PhantomData, +} + +impl<'a, T> Documents<'a, T> +where + T: DeserializeOwned + Serialize + Send + Sync, +{ + /// Creates a new `Documents` instance. + /// + /// This is typically called by `Client::documents()`. + pub(super) fn new(client: &'a Client, collection_name: &'a str) -> Self { + Self { + client, + collection_name, + _phantom: std::marker::PhantomData, + } + } + + /// Indexes a document in the collection. + /// # Arguments + /// * `document` - A `serde_json::Value` representing the document. + /// * `action` - The indexing action to perform (e.g., "create", "upsert"). + async fn index( + &self, + document: serde_json::Value, + action: &str, + params: Option, + ) -> Result> { + let params = documents_api::IndexDocumentParams { + collection_name: self.collection_name.to_string(), + body: document, + action: Some(action.to_string()), + dirty_values: params.unwrap_or_default().dirty_values, // Or expose this as an argument if needed + }; + self.client + .execute(|config: configuration::Configuration| { + let params_for_move = params.clone(); + async move { documents_api::index_document(&config, params_for_move).await } + }) + .await + } + + /// Creates a new document in the collection. + /// + /// Fails if a document with the same ID already exists. If the document has an `id` field + /// of type `string`, it will be used as the document's ID. Otherwise, Typesense will + /// auto-generate an ID. The newly indexed document is returned. + /// + /// # Arguments + /// * `document` - A reference to the document to create. + /// * `params` - Optional parameters like `dirty_values`. + pub async fn create( + &self, + document: &T, + params: Option, + ) -> Result> { + let doc_value = serde_json::to_value(document)?; + let result_value = self.index(doc_value, "create", params).await?; + serde_json::from_value(result_value).map_err(Error::from) + } + + /// Creates a new document or updates an existing one if an ID match is found. + /// + /// This method requires the full document to be sent. For partial updates, use + /// `collection.document("...").update()`. The indexed document is returned. + /// + /// # Arguments + /// * `document` - A reference to the document to upsert. + /// * `params` - Optional parameters like `dirty_values`. + pub async fn upsert( + &self, + document: &T, + params: Option, + ) -> Result> { + let doc_value = serde_json::to_value(document)?; + let result_value = self.index(doc_value, "upsert", params).await?; + serde_json::from_value(result_value).map_err(Error::from) + } + + // --- Bulk Operation Methods --- + + /// Imports a batch of documents in JSONL format. + /// + /// The documents to be imported must be formatted as a newline-delimited JSON string. + /// + /// # Arguments + /// * `documents_jsonl` - A string containing the documents in JSONL format. + /// * `params` - An `ImportDocumentsParameters` struct containing options like `action` and `batch_size`. + pub async fn import( + &self, + documents_jsonl: String, + params: ImportDocumentsParameters, + ) -> Result> { + let params = documents_api::ImportDocumentsParams { + body: documents_jsonl, + collection_name: self.collection_name.to_string(), + + action: params.action, + batch_size: params.batch_size, + dirty_values: params.dirty_values, + remote_embedding_batch_size: params.remote_embedding_batch_size, + return_doc: params.return_doc, + return_id: params.return_id, + }; + + self.client + .execute(|config: configuration::Configuration| async move { + documents_api::import_documents(&config, params.clone()).await + }) + .await + } + + /// Exports all documents in a collection in JSONL format. + /// + /// # Arguments + /// * `params` - An `ExportDocumentsParameters` struct containing options like `filter_by` and `include_fields`. + pub async fn export( + &self, + params: ExportDocumentsParameters, + ) -> Result> { + let params = documents_api::ExportDocumentsParams { + collection_name: self.collection_name.to_string(), + exclude_fields: params.exclude_fields, + filter_by: params.filter_by, + include_fields: params.include_fields, + }; + + self.client + .execute(|config: configuration::Configuration| async move { + documents_api::export_documents(&config, params.clone()).await + }) + .await + } + + /// Deletes a batch of documents matching a specific filter condition. + /// + /// # Arguments + /// * `params` - A `DeleteDocumentsParameters` describing the conditions for deleting documents. + pub async fn delete( + &self, + params: DeleteDocumentsParameters, + ) -> Result> + { + let params = documents_api::DeleteDocumentsParams { + collection_name: self.collection_name.to_string(), + filter_by: Some(params.filter_by), + batch_size: params.batch_size, + ignore_not_found: params.ignore_not_found, + truncate: params.truncate, + }; + self.client + .execute(|config: configuration::Configuration| async move { + documents_api::delete_documents(&config, params.clone()).await + }) + .await + } + + /// Updates a batch of documents matching a specific filter condition. + /// + /// # Arguments + /// * `document` - A `serde_json::Value` containing the fields to update. + /// * `params` - A `UpdateDocumentsParameters` describing the conditions for updating documents. + pub async fn update( + &self, + document: serde_json::Value, + params: UpdateDocumentsParameters, + ) -> Result> + { + let params = documents_api::UpdateDocumentsParams { + collection_name: self.collection_name.to_string(), + filter_by: params.filter_by, + body: document, + }; + self.client + .execute(|config: configuration::Configuration| async move { + documents_api::update_documents(&config, params.clone()).await + }) + .await + } + + /// Searches for documents in the collection that match the given criteria. + /// The search results will have their `document` field deserialized into type `T`. + /// + /// # Arguments + /// * `params` - A `SearchParameters` struct containing all search parameters. + pub async fn search( + &self, + params: raw_models::SearchParameters, + ) -> Result, Error> { + let search_params = documents_api::SearchCollectionParams { + collection_name: self.collection_name.to_string(), + + // Map all corresponding fields directly. + cache_ttl: params.cache_ttl, + conversation: params.conversation, + conversation_id: params.conversation_id, + conversation_model_id: params.conversation_model_id, + drop_tokens_mode: params.drop_tokens_mode, + drop_tokens_threshold: params.drop_tokens_threshold, + enable_highlight_v1: params.enable_highlight_v1, + enable_overrides: params.enable_overrides, + enable_synonyms: params.enable_synonyms, + enable_typos_for_alpha_numerical_tokens: params.enable_typos_for_alpha_numerical_tokens, + enable_typos_for_numerical_tokens: params.enable_typos_for_numerical_tokens, + exclude_fields: params.exclude_fields, + exhaustive_search: params.exhaustive_search, + facet_by: params.facet_by, + facet_query: params.facet_query, + facet_return_parent: params.facet_return_parent, + facet_strategy: params.facet_strategy, + filter_by: params.filter_by, + filter_curated_hits: params.filter_curated_hits, + group_by: params.group_by, + group_limit: params.group_limit, + group_missing_values: params.group_missing_values, + hidden_hits: params.hidden_hits, + highlight_affix_num_tokens: params.highlight_affix_num_tokens, + highlight_end_tag: params.highlight_end_tag, + highlight_fields: params.highlight_fields, + highlight_full_fields: params.highlight_full_fields, + highlight_start_tag: params.highlight_start_tag, + include_fields: params.include_fields, + infix: params.infix, + limit: params.limit, + max_candidates: params.max_candidates, + max_extra_prefix: params.max_extra_prefix, + max_extra_suffix: params.max_extra_suffix, + max_facet_values: params.max_facet_values, + max_filter_by_candidates: params.max_filter_by_candidates, + min_len_1typo: params.min_len_1typo, + min_len_2typo: params.min_len_2typo, + num_typos: params.num_typos, + offset: params.offset, + override_tags: params.override_tags, + page: params.page, + per_page: params.per_page, + pinned_hits: params.pinned_hits, + pre_segmented_query: params.pre_segmented_query, + prefix: params.prefix, + preset: params.preset, + prioritize_exact_match: params.prioritize_exact_match, + prioritize_num_matching_fields: params.prioritize_num_matching_fields, + prioritize_token_position: params.prioritize_token_position, + q: params.q, + query_by: params.query_by, + query_by_weights: params.query_by_weights, + remote_embedding_num_tries: params.remote_embedding_num_tries, + remote_embedding_timeout_ms: params.remote_embedding_timeout_ms, + search_cutoff_ms: params.search_cutoff_ms, + snippet_threshold: params.snippet_threshold, + sort_by: params.sort_by, + split_join_tokens: params.split_join_tokens, + stopwords: params.stopwords, + synonym_num_typos: params.synonym_num_typos, + synonym_prefix: params.synonym_prefix, + text_match_type: params.text_match_type, + typo_tokens_threshold: params.typo_tokens_threshold, + use_cache: params.use_cache, + vector_query: params.vector_query, + voice_query: params.voice_query, + nl_model_id: params.nl_model_id, + nl_query: params.nl_query, + enable_analytics: params.enable_analytics, + synonym_sets: params.synonym_sets, + }; + + let raw_result = self + .client + .execute(|config: configuration::Configuration| async move { + documents_api::search_collection(&config, params.clone()).await + }) + .await?; + + // Transform the raw API result into our generic, typed SearchResult. + SearchResult::from_raw(raw_result).map_err(Error::from) + } +} diff --git a/typesense/src/client/collection/mod.rs b/typesense/src/client/collection/mod.rs new file mode 100644 index 0000000..0edae44 --- /dev/null +++ b/typesense/src/client/collection/mod.rs @@ -0,0 +1,103 @@ +//! Provides access to the collection and alias-related API endpoints. +//! +//! A `Collections` instance is created via the main `Client::collections()` method. + +mod document; +mod documents; +use crate::{Client, Error}; + +use serde::{Serialize, de::DeserializeOwned}; +use typesense_codegen::{ + apis::{collections_api, configuration}, + models, +}; + +/// Provides methods for interacting with a Typesense collection. +/// +/// This struct is created by calling `client.collection("collection_name")`. +pub struct Collection<'a, T = serde_json::Value> +where + T: DeserializeOwned + Serialize + Send + Sync, +{ + pub(super) client: &'a Client, + pub(super) collection_name: &'a str, + pub(super) _phantom: std::marker::PhantomData, +} + +impl<'a, T> Collection<'a, T> +where + T: DeserializeOwned + Serialize + Send + Sync, +{ + /// Creates a new `Collection` instance. + pub(super) fn new(client: &'a Client, collection_name: &'a str) -> Self { + Self { + client, + collection_name, + _phantom: std::marker::PhantomData, + } + } + + /// Provides access to the document-related API endpoints for a specific collection. + pub fn documents(&'a self) -> documents::Documents<'a, T> { + documents::Documents::new(self.client, self.collection_name) + } + + /// Provides access to the API endpoints for a single document within a Typesense collection. + pub fn document(&'a self, document_id: &'a str) -> document::Document<'a, T> { + document::Document::new(self.client, self.collection_name, document_id) + } + + /// Retrieves the details of a collection, given its name. + pub async fn retrieve( + &self, + ) -> Result> { + let params = collections_api::GetCollectionParams { + collection_name: self.collection_name.to_string(), + }; + + self.client + .execute(|config: configuration::Configuration| { + let params_for_move = params.clone(); + async move { collections_api::get_collection(&config, params_for_move).await } + }) + .await + } + + /// Permanently drops a collection. + /// + /// This action cannot be undone. For large collections, this might have an + /// impact on read latencies during the delete operation. + pub async fn delete( + &self, + ) -> Result> { + let params = collections_api::DeleteCollectionParams { + collection_name: self.collection_name.to_string(), + }; + self.client + .execute(|config: configuration::Configuration| { + let params_for_move = params.clone(); + async move { collections_api::delete_collection(&config, params_for_move).await } + }) + .await + } + + /// Updates a collection's schema to modify the fields and their types. + /// + /// # Arguments + /// * `update_schema` - A `CollectionUpdateSchema` object describing the fields to update. + pub async fn update( + &self, + update_schema: models::CollectionUpdateSchema, + ) -> Result> { + let params = collections_api::UpdateCollectionParams { + collection_name: self.collection_name.to_string(), + collection_update_schema: update_schema, + }; + self.client + .execute(|config: configuration::Configuration| { + let params_for_move = params.clone(); + async move { collections_api::update_collection(&config, params_for_move).await } + }) + .await + } +} diff --git a/typesense/src/client/collections.rs b/typesense/src/client/collections.rs new file mode 100644 index 0000000..3087107 --- /dev/null +++ b/typesense/src/client/collections.rs @@ -0,0 +1,60 @@ +//! Provides access to the collection and alias-related API endpoints. +//! +//! A `Collections` instance is created via the main `client.collections()` method. + +use crate::{Client, Error}; +use typesense_codegen::{ + apis::{collections_api, configuration}, + models::{self, GetCollectionsParameters}, +}; + +/// Provides methods for interacting with Typesense collections and aliases. +/// +/// This struct is created by calling `client.collections()`. +pub struct Collections<'a> { + pub(super) client: &'a Client, +} + +impl<'a> Collections<'a> { + /// Creates a new `Collection` instance + pub(super) fn new(client: &'a Client) -> Self { + Self { client } + } + + /// Creates a new collection with the given schema. + /// + /// When a collection is created, you give it a name and describe the fields + /// that will be indexed from the documents added to the collection. + /// + /// # Arguments + /// * `schema` - A `CollectionSchema` object describing the collection to be created. + pub async fn create( + &self, + schema: models::CollectionSchema, + ) -> Result> { + let params = collections_api::CreateCollectionParams { + collection_schema: schema, + }; + + self.client + .execute(|config: configuration::Configuration| async move { + collections_api::create_collection(&config, params.clone()).await + }) + .await + } + + /// Returns a summary of all collections in the Typesense cluster. + /// + /// The collections are returned sorted by creation date, with the most + /// recent collections appearing first. + pub async fn retrieve( + &self, + params: &GetCollectionsParameters, + ) -> Result, Error> { + self.client + .execute(|config: configuration::Configuration| async move { + collections_api::get_collections(&config, params.clone()).await + }) + .await + } +} diff --git a/typesense/src/client/key.rs b/typesense/src/client/key.rs new file mode 100644 index 0000000..fb2701d --- /dev/null +++ b/typesense/src/client/key.rs @@ -0,0 +1,55 @@ +//! Provides access to the API endpoints for managing a single API key. +//! +//! A `Key` instance is created via the `Client::key(key_id)` method. + +use crate::{Client, Error}; +use typesense_codegen::{ + apis::{configuration, keys_api}, + models, +}; + +/// Provides methods for managing a specific Typesense API key. +/// +/// This struct is created by calling `client.key(key_id)`. +pub struct Key<'a> { + pub(super) client: &'a Client, + pub(super) key_id: i64, +} + +impl<'a> Key<'a> { + /// Creates a new `Key` instance for a specific key ID. + pub(super) fn new(client: &'a Client, key_id: i64) -> Self { + Self { client, key_id } + } + + /// Retrieves metadata about this specific API key. + /// + /// For security reasons, this endpoint only returns the key prefix and metadata, + /// not the full key value. + pub async fn retrieve(&self) -> Result> { + let params = keys_api::GetKeyParams { + key_id: self.key_id, + }; + self.client + .execute(|config: configuration::Configuration| { + let params_for_move = params.clone(); + async move { keys_api::get_key(&config, params_for_move).await } + }) + .await + } + + /// Deletes this specific API key. + pub async fn delete( + &self, + ) -> Result> { + let params = keys_api::DeleteKeyParams { + key_id: self.key_id, + }; + self.client + .execute(|config: configuration::Configuration| { + let params_for_move = params.clone(); + async move { keys_api::delete_key(&config, params_for_move).await } + }) + .await + } +} diff --git a/typesense/src/client/keys.rs b/typesense/src/client/keys.rs new file mode 100644 index 0000000..12b791c --- /dev/null +++ b/typesense/src/client/keys.rs @@ -0,0 +1,78 @@ +//! Provides access to the API endpoints for managing the collection of API keys. +//! +//! An `Keys` instance is created via the `Client::keys()` method. + +use crate::{ + Client, Error, + models::{self, ScopedKeyParameters}, +}; +use base64::{Engine, engine::general_purpose::STANDARD as Base64Engine}; +use hmac::{Hmac, Mac}; +use sha2::Sha256; +use typesense_codegen::apis::{configuration, keys_api}; + +/// Provides methods for managing a collection of Typesense API keys. +/// +/// This struct is created by calling `client.keys()`. +pub struct Keys<'a> { + pub(super) client: &'a Client, +} + +impl<'a> Keys<'a> { + /// Creates a new `Keys` instance. + pub(super) fn new(client: &'a Client) -> Self { + Self { client } + } + + /// Creates a new API key with fine-grained access control. + /// + /// You can restrict access on a per-collection and per-action level. + /// The full, unhashed key is only returned on creation. + /// + /// # Arguments + /// * `schema` - An `ApiKeySchema` object describing the key's permissions. + pub async fn create( + &self, + schema: models::ApiKeySchema, + ) -> Result> { + let params = keys_api::CreateKeyParams { + api_key_schema: Some(schema), + }; + self.client + .execute(|config: configuration::Configuration| { + let params_for_move = params.clone(); + async move { keys_api::create_key(&config, params_for_move).await } + }) + .await + } + + /// Lists all API keys and their metadata. + pub async fn retrieve(&self) -> Result> { + self.client + .execute(|config: configuration::Configuration| async move { + keys_api::get_keys(&config).await + }) + .await + } + + /// Generate a scoped search API key that can have embedded search parameters in them. + /// + /// More info [here](https://typesense.org/docs/latest/api/api-keys.html#generate-scoped-search-key). + pub fn generate_scoped_search_key( + &self, + key: impl AsRef, + params: &ScopedKeyParameters, + ) -> anyhow::Result { + let params = serde_json::to_string(params)?; + + let mut mac = Hmac::::new_from_slice(key.as_ref().as_bytes())?; + mac.update(params.as_bytes()); + let result = mac.finalize(); + let digest = Base64Engine.encode(result.into_bytes()); + + let key_prefix = &key.as_ref()[0..4]; + let raw_scoped_key = format!("{}{}{}", digest, key_prefix, params); + + Ok(Base64Engine.encode(raw_scoped_key.as_bytes())) + } +} diff --git a/typesense/src/client/mod.rs b/typesense/src/client/mod.rs new file mode 100644 index 0000000..96f78ea --- /dev/null +++ b/typesense/src/client/mod.rs @@ -0,0 +1,542 @@ +//! # A batteries-included, multi-node-aware client for the Typesense API. +//! +//! This module provides the main `Client` for interacting with a Typesense cluster. +//! It is designed for resilience and ease of use, incorporating features like +//! automatic failover, health checks, and a structured, ergonomic API. +//! +//! ## Key Features: +//! - **Multi-Node Configuration**: Automatically manages connections to multiple Typesense nodes. +//! - **Health Checks & Failover**: Monitors node health and seamlessly fails over to healthy nodes upon encountering server or network errors. +//! - **Nearest Node Priority**: Can be configured to always prioritize a specific nearest node to reduce latency. +//! - **Built-in Retries**: Handles transient network errors with an exponential backoff policy for each node. +//! +//! ## Example Usage +//! +//! The following example demonstrates how to use the client in a standard +//! server-side **Tokio** environment. +//! +//! ```no_run +//! #[cfg(not(target_family = "wasm"))] +//! { +//! use typesense::{Client, models}; +//! use reqwest::Url; +//! use reqwest_retry::policies::ExponentialBackoff; +//! use std::time::Duration; +//! +//! #[tokio::main] +//! async fn main() -> Result<(), Box> { +//! let client = Client::builder() +//! .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) +//! .api_key("xyz") +//! .healthcheck_interval(Duration::from_secs(60)) +//! .retry_policy(ExponentialBackoff::builder().build_with_max_retries(3)) +//! .connection_timeout(Duration::from_secs(5)) +//! .build() +//! .unwrap(); +//! +//! // Retrieve details for a collection +//! let collection = client.collection("products").retrieve().await?; +//! println!("Collection Name: {}", collection.name); +//! +//! // Search for a document +//! let search_params = models::SearchParameters { +//! q: Some("phone".to_string()), +//! query_by: Some("name".to_string()), +//! ..Default::default() +//! }; +//! +//! let search_results = client +//! .collection("products") +//! .documents() +//! .search(search_params) +//! .await?; +//! +//! println!("Found {} hits.", search_results.found.unwrap_or(0)); +//! Ok(()) +//! } +//! } +//! ``` +//! --- +//! +//! ### WebAssembly (Wasm) Usage +//! +//! When compiling for a WebAssembly target (`wasm32-unknown-unknown`), the +//! client's underlying HTTP transport and runtime are different. +//! +//! - `reqwest` internally uses the browser's **fetch API**. +//! - Tokio-based features such as middleware, retries, and connection +//! timeouts are **not available**. +//! +//! Example: +//! +//! ```no_run +//! #[cfg(target_family = "wasm")] +//! { +//! use typesense::{Client, models}; +//! use reqwest::Url; +//! use std::time::Duration; +//! use wasm_bindgen_futures::spawn_local; +//! +//! fn main() { +//! spawn_local(async { +//! let client = Client::builder() +//! .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) +//! .api_key("xyz") +//! .healthcheck_interval(Duration::from_secs(60)) +//! // .retry_policy(...) <-- not supported in Wasm +//! // .connection_timeout(...) <-- not supported in Wasm +//! .build() +//! .unwrap(); +//! +//! // Retrieve details for a collection +//! match client.collection("products").retrieve().await { +//! Ok(collection) => println!("Collection Name: {}", collection.name), +//! Err(e) => eprintln!("Error retrieving collection: {}", e), +//! } +//! +//! // Search for a document +//! let search_params = models::SearchParameters { +//! q: Some("phone".to_string()), +//! query_by: Some("name".to_string()), +//! ..Default::default() +//! }; +//! +//! match client.collection("products").documents().search(search_params).await { +//! Ok(search_results) => { +//! println!("Found {} hits.", search_results.found.unwrap_or(0)); +//! } +//! Err(e) => eprintln!("Error searching documents: {}", e), +//! } +//! }); +//! } +//! } +//! ``` +mod collection; +mod collections; +mod key; +mod keys; + +use collection::Collection; +use collections::Collections; +use key::Key; +use keys::Keys; + +use serde::Serialize; +use serde::de::DeserializeOwned; + +use crate::Error; +use reqwest::Url; +#[cfg(not(target_arch = "wasm32"))] +use reqwest_middleware::ClientBuilder as ReqwestMiddlewareClientBuilder; +#[cfg(not(target_arch = "wasm32"))] +use reqwest_retry::RetryTransientMiddleware; +use reqwest_retry::policies::ExponentialBackoff; + +use std::future::Future; +use std::sync::{ + Arc, Mutex, + atomic::{AtomicUsize, Ordering}, +}; +use typesense_codegen::apis::{self, configuration}; +use web_time::{Duration, Instant}; + +// This is an internal detail to track the state of each node. +#[derive(Debug)] +struct Node { + url: Url, + is_healthy: bool, + last_access_timestamp: Instant, +} +/// The main entry point for all interactions with the Typesense API. +/// +/// The client manages connections to multiple nodes and provides access to different +/// API resource groups (namespaces) like `collections`, `documents`, and `operations`. +#[derive(Debug)] +pub struct Client { + // The Client now holds the stateful Node list. + nodes: Vec>>, + nearest_node: Option>>, + api_key: String, + healthcheck_interval: Duration, + current_node_index: AtomicUsize, + + #[cfg(not(target_arch = "wasm32"))] + retry_policy: ExponentialBackoff, + #[cfg(not(target_arch = "wasm32"))] + connection_timeout: Duration, +} + +#[bon::bon] +impl Client { + /// Creates a new `Client` with the given configuration. + /// + /// Returns an error if the configuration contains no nodes. Default values: + /// - **nearest_node**: None. + /// - **healthcheck_interval**: 60 seconds. + /// - **retry_policy**: Exponential backoff with a maximum of 3 retries. (disabled on WASM) + /// - **connection_timeout**: 5 seconds. (disabled on WASM) + #[builder] + pub fn new( + /// The Typesense API key used for authentication. + api_key: impl Into, + /// A list of all nodes in the Typesense cluster. + nodes: Vec, + /// An optional, preferred node to try first for every request. Ideal for reducing latency. + #[builder(into)] + nearest_node: Option, + #[builder(default = Duration::from_secs(60))] + /// The duration after which an unhealthy node will be retried for requests. + healthcheck_interval: Duration, + #[builder(default = ExponentialBackoff::builder().build_with_max_retries(3))] + /// The retry policy for transient network errors on a *single* node. + retry_policy: ExponentialBackoff, + #[builder(default = Duration::from_secs(5))] + /// The timeout for each individual network request. + connection_timeout: Duration, + ) -> Result { + if nodes.is_empty() && nearest_node.is_none() { + return Err("Configuration must include at least one node or a nearest_node."); + } + + let node_list = nodes + .into_iter() + .map(|url| { + Arc::new(Mutex::new(Node { + url, + is_healthy: true, + last_access_timestamp: Instant::now(), + })) + }) + .collect(); + + let nearest_node_arc = nearest_node.map(|url| { + Arc::new(Mutex::new(Node { + url, + is_healthy: true, + last_access_timestamp: Instant::now(), + })) + }); + + Ok(Self { + nodes: node_list, + nearest_node: nearest_node_arc, + api_key: api_key.into(), + healthcheck_interval, + current_node_index: AtomicUsize::new(0), + + #[cfg(not(target_arch = "wasm32"))] + retry_policy, + #[cfg(not(target_arch = "wasm32"))] + connection_timeout, + }) + } + + /// Selects the next node to use for a request based on health and priority. + fn get_next_node(&self) -> Arc> { + // 1. Always try the nearest_node first if it exists. + if let Some(nearest_node_arc) = &self.nearest_node { + let node = nearest_node_arc.lock().unwrap(); + let is_due_for_check = Instant::now().duration_since(node.last_access_timestamp) + >= self.healthcheck_interval; + + if node.is_healthy || is_due_for_check { + return Arc::clone(nearest_node_arc); + } + } + + // 2. Fallback to the main list of nodes if no healthy nearest_node is available. + if self.nodes.is_empty() { + // This can only happen if ONLY a nearest_node was provided and it's unhealthy. + // We must return it to give it a chance to recover. + return Arc::clone(self.nearest_node.as_ref().unwrap()); + } + + // 3. Loop through all nodes once to find a healthy one. + for _ in 0..self.nodes.len() { + let index = self.current_node_index.fetch_add(1, Ordering::Relaxed) % self.nodes.len(); + let node_arc = &self.nodes[index]; + let node = node_arc.lock().unwrap(); + let is_due_for_check = Instant::now().duration_since(node.last_access_timestamp) + >= self.healthcheck_interval; + + if node.is_healthy || is_due_for_check { + return Arc::clone(node_arc); + } + } + + // 4. If all nodes are unhealthy and not due for a check, just pick the next one in the round-robin. + // This gives it a chance to prove it has recovered. + let index = self.current_node_index.load(Ordering::Relaxed) % self.nodes.len(); + Arc::clone(&self.nodes[index]) + } + + /// Sets the health status of a given node after a request attempt. + fn set_node_health(&self, node_arc: &Arc>, is_healthy: bool) { + let mut node = node_arc.lock().unwrap(); + node.is_healthy = is_healthy; + node.last_access_timestamp = Instant::now(); + } + + /// The core execution method that handles multi-node failover and retries. + /// This internal method is called by all public API methods. + pub(super) async fn execute<'a, F, Fut, T, E>(&'a self, api_call: F) -> Result> + where + F: Fn(configuration::Configuration) -> Fut, + Fut: Future>>, + E: std::fmt::Debug + 'static, + apis::Error: std::error::Error + 'static, + { + let mut last_api_error: Option> = None; + let num_nodes_to_try = self.nodes.len() + self.nearest_node.is_some() as usize; + + // Loop up to the total number of available nodes. + for _ in 0..num_nodes_to_try { + let node_arc = self.get_next_node(); + let node_url = { + // Lock is held for a very short duration. + let node = node_arc.lock().unwrap(); + node.url.clone() + }; + + #[cfg(target_arch = "wasm32")] + let http_client = reqwest::Client::builder() + .build() + .expect("Failed to build reqwest client"); + + #[cfg(not(target_arch = "wasm32"))] + let http_client = ReqwestMiddlewareClientBuilder::new( + reqwest::Client::builder() + .timeout(self.connection_timeout) + .build() + .expect("Failed to build reqwest client"), + ) + .with(RetryTransientMiddleware::new_with_policy(self.retry_policy)) + .build(); + + // Create the temporary config on the stack for this attempt. + let gen_config = configuration::Configuration { + base_path: node_url + .to_string() + .strip_suffix('/') + .unwrap_or(node_url.as_str()) + .to_string(), + api_key: Some(configuration::ApiKey { + prefix: None, + key: self.api_key.clone(), + }), + client: http_client, + ..Default::default() + }; + + match api_call(gen_config).await { + Ok(response) => { + self.set_node_health(&node_arc, true); + return Ok(response); + } + Err(e) => { + if is_retriable(&e) { + self.set_node_health(&node_arc, false); + last_api_error = Some(e); + } else { + return Err(e.into()); + } + } + } + } + + Err(crate::Error::AllNodesFailed { + source: last_api_error + .expect("No nodes were available to try, or all errors were non-retriable."), + }) + } + + /// Provides access to API endpoints for managing collections like `create()` and `retrieve()`. + /// # Example + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { + /// # use typesense::Client; + /// # use reqwest::Url; + /// # + /// # #[tokio::main] + /// # async fn main() -> Result<(), Box> { + /// # let client = Client::builder() + /// # .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) + /// # .api_key("xyz") + /// # .build() + /// # .unwrap(); + /// let all_collections = client.collections().retrieve().await.unwrap(); + /// # Ok(()) + /// # } + /// # } + /// ``` + pub fn collections(&self) -> Collections<'_> { + Collections::new(self) + } + + /// Provides access to API endpoints for a specific collection. + /// + /// This method returns a `Collection` handle, which is generic over the type of document + /// stored in that collection. + /// + /// # Type Parameters + /// * `T` - The type of the documents in the collection. It must be serializable and deserializable. + /// **This defaults to `serde_json::Value`**, allowing you to perform collection-level + /// operations (like delete, update, retrieve schema) without specifying a type, + /// or to work with schemaless documents. + /// + /// # Arguments + /// * `collection_name` - The name of the collection to interact with. + /// + /// # Example: Working with a strongly-typed collection + /// + /// When you want to retrieve or search for documents and have them automatically + /// deserialized into your own structs. + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { + /// # use typesense::Client; + /// # use serde::{Serialize, Deserialize}; + /// # use reqwest::Url; + /// # + /// # #[derive(Serialize, Deserialize, Debug)] + /// # struct Book { id: String, title: String } + /// # async fn run() -> Result<(), Box> { + /// # let client = Client::builder() + /// # .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) + /// # .api_key("xyz") + /// # .build() + /// # .unwrap(); + /// // Get a typed handle to the "books" collection + /// let books_collection = client.collection_of::("books"); + /// + /// // Retrieve a single book, it returns `Result` + /// let book = books_collection.document("123").retrieve().await?; + /// println!("Retrieved book: {:?}", book); + /// # + /// # Ok(()) + /// # } + /// # } + /// ``` + pub fn collection_of<'a, T>(&'a self, collection_name: &'a str) -> Collection<'a, T> + where + T: DeserializeOwned + Serialize + Send + Sync, + { + Collection::new(self, collection_name) + } + + /// Provides access to API endpoints for a specific collection using schemaless `serde_json::Value` documents. + /// + /// This is the simplest way to interact with a collection when you do not need strong typing. + /// It is a convenient shorthand for `client.collection_of::("...")`. + /// + /// The returned handle can be used for both document operations (which will return `serde_json::Value`) + /// and collection-level operations (like `.delete()` or `.retrieve()`). + /// + /// # Arguments + /// * `collection_name` - The name of the collection to interact with. + /// + /// # Example + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { + /// # use typesense::Client; + /// # use reqwest::Url; + /// # async fn run() -> Result<(), Box> { + /// # let client = Client::builder() + /// # .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) + /// # .api_key("xyz") + /// # .build() + /// # .unwrap(); + /// let products_collection = client.collection("products"); + /// # + /// # Ok(()) + /// # } + /// # } + /// ``` + pub fn collection<'a>(&'a self, collection_name: &'a str) -> Collection<'a, serde_json::Value> { + Collection::new(self, collection_name) + } + + /// Provides access to endpoints for managing the collection of API keys. + /// + /// # Example + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { + /// # use typesense::{Client, models}; + /// # use reqwest::Url; + /// # + /// # #[tokio::main] + /// # async fn main() -> Result<(), Box> { + /// # let client = Client::builder() + /// # .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) + /// # .api_key("xyz") + /// # .build() + /// # .unwrap(); + /// # let schema = models::ApiKeySchema { + /// # description: "Search-only key.".to_string(), + /// # actions: vec!["documents:search".to_string()], + /// # collections: vec!["*".to_string()], + /// # ..Default::default() + /// # }; + /// let new_key = client.keys().create(schema).await.unwrap(); + /// # Ok(()) + /// # } + /// # } + /// ``` + pub fn keys(&self) -> Keys<'_> { + Keys::new(self) + } + + /// Provides access to endpoints for managing a single API key. + /// + /// # Arguments + /// * `key_id` - The ID of the key to manage. + /// + /// # Example + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { + /// # use typesense::Client; + /// # use reqwest::Url; + /// # + /// # #[tokio::main] + /// # async fn main() -> Result<(), Box> { + /// # let client = Client::builder() + /// # .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) + /// # .api_key("xyz") + /// # .build() + /// # .unwrap(); + /// let deleted_key = client.key(123).delete().await.unwrap(); + /// # Ok(()) + /// # } + /// # } + /// ``` + pub fn key(&self, key_id: i64) -> Key<'_> { + Key::new(self, key_id) + } +} + +/// A helper function to determine if an error is worth retrying on another node. +fn is_retriable(error: &apis::Error) -> bool +where + E: std::fmt::Debug + 'static, + apis::Error: std::error::Error + 'static, +{ + match error { + // Server-side errors (5xx) indicate a problem with the node, so we should try another. + apis::Error::ResponseError(content) => content.status.is_server_error(), + + // Underlying reqwest errors (e.g., connection refused) are retriable on both native and wasm. + apis::Error::Reqwest(_) => true, + + // Network-level errors from middleware are always retriable. + // This match arm is ONLY included when compiling for non-wasm targets. + #[cfg(not(target_arch = "wasm32"))] + apis::Error::ReqwestMiddleware(_) => true, + + // Client-side (4xx) or parsing errors are not retriable as the request is likely invalid. + _ => false, + } +} diff --git a/typesense/src/collection_schema.rs b/typesense/src/collection_schema.rs index c28207a..0951e76 100644 --- a/typesense/src/collection_schema.rs +++ b/typesense/src/collection_schema.rs @@ -82,6 +82,7 @@ impl CollectionSchemaBuilder { token_separators: self.token_separators, enable_nested_fields: self.enable_nested_fields, symbols_to_index: self.symbols_to_index, + ..Default::default() } } } diff --git a/typesense/src/error.rs b/typesense/src/error.rs new file mode 100644 index 0000000..68e9d4f --- /dev/null +++ b/typesense/src/error.rs @@ -0,0 +1,109 @@ +//! Contains the error types for the Typesense client + +use thiserror::Error; +pub use typesense_codegen::apis::Error as ApiError; + +/// The primary error type for the Typesense client. +/// +/// This enum encapsulates all possible failures, from network issues to API errors +/// returned by the Typesense server, to client-side data handling problems. +/// +/// The generic parameter `E` represents the specific error type associated with a +/// particular API operation (e.g., `SearchCollectionError`, `GetDocumentError`). +#[derive(Debug, Error)] +pub enum Error +where + E: std::fmt::Debug + 'static, + ApiError: std::error::Error + 'static, +{ + /// Occurs when an operation fails against all configured Typesense nodes. + /// + /// This error is only returned when using a client configured with multiple nodes. + /// It signifies that the client attempted the operation against each node in turn, + /// and every attempt failed. The user should check the health and connectivity + /// of all their Typesense nodes. + /// + /// The `source` field contains the error from the *last* node that was attempted. + #[error("All configured Typesense nodes failed to respond. Last error: {source}")] + AllNodesFailed { + /// The underlying API or network error from the last node attempt. + #[source] + source: ApiError, + }, + + /// Wraps an error returned by the Typesense API or the underlying network stack. + /// + /// This can be due to: + /// - A server-side issue (e.g., HTTP 5xx errors). + /// - A client-side mistake (e.g., HTTP 4xx errors like `404 Not Found` or `401 Unauthorized`). + /// - A network connectivity problem (e.g., connection refused, timeout, DNS failure). + /// + /// You should inspect the wrapped error to get specific details about the HTTP status code and response body. + #[error("An API or network error occurred: {0}")] + Api(#[from] ApiError), + + /// Occurs when the JSON response from Typesense cannot be deserialized into the target Rust struct. + /// + /// This typically signifies a mismatch between the data in your Typesense collection + /// and the fields or data types defined in your Rust struct (`T`). + /// + /// **To debug this, check for:** + /// - A field that exists in Typesense but not in your struct (unless your struct ignores unknown fields). + /// - A field in your struct that doesn't exist in the Typesense document and is not wrapped in an `Option`. + /// - A type mismatch (e.g., a Typesense `string` field that you are trying to deserialize into a `u64`). + #[error("Failed to deserialize the API response into the target struct: {0}")] + Deserialization(#[from] serde_json::Error), +} + +/// Represents the possible errors that can occur when parsing a `multi_search` response. +/// +/// This error enum is returned by the `MultiSearchResultExt::parse_at` method when it +/// fails to convert a raw search result into a strongly-typed `SearchResult`. +#[derive(Debug, Error)] +pub enum MultiSearchParseError { + /// Indicates that the requested index was outside the bounds of the results vector. + /// + /// For a `multi_search` request with `n` search queries, the valid indices for the + /// results are `0` through `n-1`. This error occurs if the provided index is `n` or greater. + /// + /// # Fields + /// * `0` - The invalid index that was requested. + #[error("Search result index {0} is out of bounds.")] + IndexOutOfBounds(usize), + + /// Indicates that the Typesense server returned an error for the specific search query at this index. + /// + // It's possible for a `multi_search` request to succeed overall, but for one or more + // individual searches within it to fail (e.g., due to a typo in a collection name). + /// + /// # Fields + /// * `index` - The index of the search query that failed. + /// * `message` - The error message returned by the Typesense API for this specific search. + #[error("The search at index {index} failed with an API error: {message}")] + ApiError { + /// The index of the search query that failed. + index: usize, + /// The error message returned by the Typesense API for this specific search. + message: String, + }, + + /// Indicates a failure to deserialize a document's JSON into the target struct `T`. + /// + /// This typically happens when the fields in the document stored in Typesense do not + /// match the fields defined in the target Rust struct `T`. Check for mismatches in + /// field names or data types. + /// + /// # Fields + /// * `index` - The index of the search query where the deserialization error occurred. + /// * `source` - The underlying `serde_json::Error` that provides detailed information + /// about the deserialization failure. + #[error("Failed to deserialize a document at index {index}: {source}")] + Deserialization { + /// The index of the search query where the deserialization error occurred. + index: usize, + /// The underlying `serde_json::Error` that provides detailed information + /// about the deserialization failure. + #[source] + source: serde_json::Error, + }, +} diff --git a/typesense/src/field/mod.rs b/typesense/src/field/mod.rs deleted file mode 100644 index 934abed..0000000 --- a/typesense/src/field/mod.rs +++ /dev/null @@ -1,110 +0,0 @@ -//! Module with the common definitions for the -//! [fields](https://github.com/typesense/typesense/blob/v0.19.0/include/field.) -//! available in Typesense. - -mod field_type; -pub use field_type::*; -pub use typesense_codegen::models::{Field, FieldEmbed}; - -/// Builder for the `Field` struct. -#[derive(Debug, Default)] -pub struct FieldBuilder { - name: String, - typesense_type: FieldType, - optional: Option, - facet: Option, - index: Option, - locale: Option, - sort: Option, - infix: Option, - num_dim: Option, - drop: Option, - embed: Option>, -} - -impl FieldBuilder { - /// Create a Builder - #[inline] - pub fn new(name: impl Into, typesense_type: FieldType) -> Self { - Self { - name: name.into(), - typesense_type, - ..Default::default() - } - } - - /// Set if field is optional. - #[inline] - pub fn optional(mut self, optional: Option) -> Self { - self.optional = optional; - self - } - - /// Set if field is facet. - #[inline] - pub fn facet(mut self, facet: Option) -> Self { - self.facet = facet; - self - } - - /// Set if field is index. - #[inline] - pub fn index(mut self, index: Option) -> Self { - self.index = index; - self - } - - /// Set field locale. - #[inline] - pub fn locale(mut self, locale: Option) -> Self { - self.locale = locale; - self - } - - /// Set sort attribute for field - #[inline] - pub fn sort(mut self, sort: Option) -> Self { - self.sort = sort; - self - } - - /// Set infix attribute for field - #[inline] - pub fn infix(mut self, infix: Option) -> Self { - self.infix = infix; - self - } - - /// Set num_dim attribute for field - #[inline] - pub fn num_dim(mut self, num_dim: Option) -> Self { - self.num_dim = num_dim; - self - } - - /// Set drop attribute for field - #[inline] - pub fn drop(mut self, drop: Option) -> Self { - self.drop = drop; - self - } - - /// Create a `Field` with the current values of the builder, - /// It can fail if the name or the typesense_type are not defined. - #[inline] - pub fn build(self) -> Field { - Field { - name: self.name, - r#type: self.typesense_type, - optional: self.optional, - facet: self.facet, - index: self.index, - locale: self.locale, - sort: self.sort, - infix: self.infix, - num_dim: self.num_dim, - drop: self.drop, - embed: self.embed, - } - } -} diff --git a/typesense/src/keys.rs b/typesense/src/keys.rs deleted file mode 100644 index 0f01e55..0000000 --- a/typesense/src/keys.rs +++ /dev/null @@ -1,83 +0,0 @@ -//! Module containing everything related to Keys API. -//! -//! More info [here](https://typesense.org/docs/0.20.0/api/api-keys.html). - -use base64::{Engine, engine::general_purpose::STANDARD as Base64Engine}; -use core::fmt; -use hmac::{Hmac, Mac}; -use serde::{Deserialize, Serialize}; -use sha2::Sha256; -use typesense_codegen::models::ScopedKeyParameters; - -/// Generate a scoped search API key that can have embedded search parameters in them. -/// -/// More info [here](https://typesense.org/docs/0.20.0/api/api-keys.html#generate-scoped-search-key). -pub async fn generate_scoped_search_key( - key: impl AsRef, - filter_by: impl Into, - expires_at: i64, -) -> anyhow::Result { - let generate_scoped_search_key = ScopedKeyParameters { - filter_by: Some(filter_by.into()), - expires_at: Some(expires_at), - }; - let params = serde_json::to_string(&generate_scoped_search_key)?; - - let mut mac = Hmac::::new_from_slice(key.as_ref().as_bytes())?; - mac.update(params.as_bytes()); - let result = mac.finalize(); - let digest = Base64Engine.encode(result.into_bytes()); - - let key_prefix = &key.as_ref()[0..4]; - let raw_scoped_key = format!("{digest}{key_prefix}{params}"); - - Ok(Base64Engine.encode(raw_scoped_key.as_bytes())) -} - -/// Enum over the possible list of Actions. -/// -/// More info [here](https://typesense.org/docs/0.25.2/api/api-keys.html#sample-actions). -#[derive(Serialize, Deserialize)] -pub enum Actions { - /// Allows only search requests. - #[serde(rename = "documents:search")] - DocumentsSearch, - - /// Allows fetching a single document. - #[serde(rename = "documents:get")] - DocumentsGet, - - /// Allow all kinds of collection related operations. - #[serde(rename = "documents:*")] - DocumentsAll, - - /// Allows a collection to be deleted. - #[serde(rename = "collections:delete")] - CollectionsDelete, - - /// Allows a collection to be created. - #[serde(rename = "collections:create")] - CollectionsCreate, - - /// Allow all kinds of collection related operations. - #[serde(rename = "collections:*")] - CollectionsAll, - - /// Allows all operations. - #[serde(rename = "*")] - All, -} - -impl fmt::Display for Actions { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::DocumentsAll => write!(f, "documents:*"), - Self::DocumentsSearch => write!(f, "documents:search"), - Self::DocumentsGet => write!(f, "documents:get"), - Self::CollectionsAll => write!(f, "collections:*"), - Self::CollectionsDelete => write!(f, "collections:delete"), - Self::CollectionsCreate => write!(f, "collections:create"), - Self::All => write!(f, "*"), - } - } -} diff --git a/typesense/src/lib.rs b/typesense/src/lib.rs index 0e6c763..722f658 100644 --- a/typesense/src/lib.rs +++ b/typesense/src/lib.rs @@ -42,13 +42,18 @@ //! } //! } //! ``` +mod client; +mod traits; -pub mod collection_schema; -pub mod document; -pub mod field; -pub mod keys; +pub mod builders; +pub mod error; +pub mod models; +pub mod prelude; -pub use typesense_codegen::*; +pub use builders::*; +pub use client::Client; +pub use error::*; +pub use models::*; #[cfg(feature = "typesense_derive")] #[doc(hidden)] diff --git a/typesense/src/models/document_index_parameters.rs b/typesense/src/models/document_index_parameters.rs new file mode 100644 index 0000000..09fb7fe --- /dev/null +++ b/typesense/src/models/document_index_parameters.rs @@ -0,0 +1,13 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct DocumentIndexParameters { + #[serde(rename = "dirty_values", skip_serializing_if = "Option::is_none")] + pub dirty_values: Option, +} + +impl DocumentIndexParameters { + pub fn new() -> DocumentIndexParameters { + DocumentIndexParameters { dirty_values: None } + } +} diff --git a/typesense/src/models/mod.rs b/typesense/src/models/mod.rs new file mode 100644 index 0000000..d0fd696 --- /dev/null +++ b/typesense/src/models/mod.rs @@ -0,0 +1,10 @@ +//! # Typesense generic models +mod document_index_parameters; +mod multi_search; +mod scoped_key_parameters; + +pub use document_index_parameters::*; + +pub use scoped_key_parameters::*; + +pub use typesense_codegen::models::*; diff --git a/typesense/src/models/multi_search.rs b/typesense/src/models/multi_search.rs new file mode 100644 index 0000000..3e67ccd --- /dev/null +++ b/typesense/src/models/multi_search.rs @@ -0,0 +1,23 @@ +use crate::models; +use serde::{Deserialize, Serialize}; + +/// Represents the body of a multi-search request. +/// +/// This struct acts as a container for a list of individual search queries that will be +/// sent to the Typesense multi-search endpoint. Each search query is defined in a +/// `MultiSearchCollectionParameters` struct within the `searches` vector. +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct MultiSearchSearchesParameter { + /// A vector of individual search queries to be executed. The order of the search results returned by Typesense will match the order of these queries. + #[serde(rename = "searches")] + pub searches: Vec, +} + +impl MultiSearchSearchesParameter { + /// Creates a new `MultiSearchSearchesParameter` instance. + pub fn new( + searches: Vec, + ) -> MultiSearchSearchesParameter { + MultiSearchSearchesParameter { searches } + } +} diff --git a/typesense/src/models/scoped_key_parameters.rs b/typesense/src/models/scoped_key_parameters.rs new file mode 100644 index 0000000..b423b96 --- /dev/null +++ b/typesense/src/models/scoped_key_parameters.rs @@ -0,0 +1,25 @@ +use crate::models::SearchParameters; +use serde::Serialize; + +/// Defines the parameters for generating a scoped API key. +/// +/// A scoped key is a temporary, client-side key that has a specific set of +/// search restrictions and an optional expiration time embedded within it. It allows +/// you to delegate search permissions securely without exposing your main API key. +#[derive(Debug, Clone, Default, Serialize)] +pub struct ScopedKeyParameters { + /// The search parameters to embed in the key. These parameters will be + /// enforced for all searches made with the generated key. + /// For example, you can use `filter_by` to restrict searches to a subset of documents. + #[serde(flatten, skip_serializing_if = "Option::is_none")] + pub search_params: Option, + + /// The number of `multi_search` requests that can be performed using this key. + /// This is an optional parameter to further restrict the key's capabilities. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit_multi_searches: Option, + + /// The Unix timestamp (in seconds) after which the generated key will expire. + #[serde(skip_serializing_if = "Option::is_none")] + pub expires_at: Option, +} diff --git a/typesense/src/prelude.rs b/typesense/src/prelude.rs new file mode 100644 index 0000000..1aeb654 --- /dev/null +++ b/typesense/src/prelude.rs @@ -0,0 +1,9 @@ +//! The Typesense prelude. +//! +//! This module re-exports the most commonly used traits and types from the library, +//! making them easy to import with a single `use` statement. + +pub use crate::traits::{Document, FieldType, MultiSearchResultExt, ToTypesenseField}; + +// pub use crate::error::Error as TypesenseError; +// pub use crate::error::MultiSearchParseError; diff --git a/typesense/src/traits/document.rs b/typesense/src/traits/document.rs new file mode 100644 index 0000000..e26a53a --- /dev/null +++ b/typesense/src/traits/document.rs @@ -0,0 +1,14 @@ +//! # Document +//! +//! In Typesense, documents are each one of the JSON elements that are stored in the collections. +//! A document to be indexed in a given collection must conform to the schema of the collection. +//! +use crate::collection_schema::CollectionSchema; +use serde::{Serialize, de::DeserializeOwned}; + +/// Trait that should implement every struct that wants to be represented as a Typesense +/// Document +pub trait Document: DeserializeOwned + Serialize { + /// Collection schema associated with the document. + fn collection_schema() -> CollectionSchema; +} diff --git a/typesense/src/field/field_type.rs b/typesense/src/traits/field_type.rs similarity index 82% rename from typesense/src/field/field_type.rs rename to typesense/src/traits/field_type.rs index 3150ad9..fd4dee2 100644 --- a/typesense/src/field/field_type.rs +++ b/typesense/src/traits/field_type.rs @@ -1,5 +1,5 @@ +use crate::traits::Document; use std::collections::{BTreeMap, HashMap}; - /// Type for a field. Currently it is a wrapping to a `String` but it could be extended to a enum pub type FieldType = String; @@ -10,11 +10,24 @@ pub trait ToTypesenseField { fn to_typesense_type() -> &'static str; } +/// Generic implementation for any type that is also a Typesense document. +impl ToTypesenseField for T { + fn to_typesense_type() -> &'static str { + "object" + } +} + +/// Generic implementation for a Vec of any type that is also a Typesense document. +impl ToTypesenseField for Vec { + fn to_typesense_type() -> &'static str { + "object[]" + } +} /// macro used internally to add implementations of ToTypesenseField for several rust types. #[macro_export] macro_rules! impl_to_typesense_field ( ($for:ty, $typesense_variant:expr) => { - impl $crate::field::ToTypesenseField for $for { + impl $crate::prelude::ToTypesenseField for $for { #[inline(always)] fn to_typesense_type() -> &'static str { $typesense_variant @@ -22,7 +35,7 @@ macro_rules! impl_to_typesense_field ( } }; ($for:ty, $typesense_variant:expr, $any:ident) => { - impl<$any> $crate::field::ToTypesenseField for $for { + impl<$any> $crate::prelude::ToTypesenseField for $for { #[inline(always)] fn to_typesense_type() -> &'static str { $typesense_variant diff --git a/typesense/src/traits/mod.rs b/typesense/src/traits/mod.rs new file mode 100644 index 0000000..667128e --- /dev/null +++ b/typesense/src/traits/mod.rs @@ -0,0 +1,9 @@ +//! Contains the core traits and extensions for Typesense client operations + +mod document; +mod field_type; +mod multi_search_ext; + +pub use document::Document; +pub use field_type::*; +pub use multi_search_ext::MultiSearchResultExt; diff --git a/typesense/src/traits/multi_search_ext.rs b/typesense/src/traits/multi_search_ext.rs new file mode 100644 index 0000000..dff04f2 --- /dev/null +++ b/typesense/src/traits/multi_search_ext.rs @@ -0,0 +1,18 @@ +use serde::de::DeserializeOwned; + +use crate::{MultiSearchParseError, SearchResult}; + +/// An extension trait for `typesense_codegen::models::MultiSearchResult` to provide typed parsing. +pub trait MultiSearchResultExt { + /// Parses the result at a specific index from a multi-search response into a strongly-typed `SearchResult`. + /// + /// # Arguments + /// * `index` - The zero-based index of the search result to parse. + /// + /// # Type Parameters + /// * `T` - The concrete document type to deserialize the hits into. + fn parse_at( + &self, + index: usize, + ) -> Result, MultiSearchParseError>; +} diff --git a/typesense/tests/api/collection.rs b/typesense/tests/api/collection.rs deleted file mode 100644 index 23016fd..0000000 --- a/typesense/tests/api/collection.rs +++ /dev/null @@ -1,136 +0,0 @@ -#![allow(dead_code)] - -use super::Config; -use serde::{Deserialize, Serialize}; -use typesense::Typesense; -use typesense::document::Document; -use typesense_codegen::apis::collections_api; -use typesense_codegen::models::{CollectionResponse, CollectionSchema}; - -#[derive(Typesense, Serialize, Deserialize)] -#[typesense(collection_name = "companies", default_sorting_field = "num_employees")] -struct Company { - company_name: String, - num_employees: i32, - #[typesense(facet)] - country: String, -} - -fn schema_to_resp(schema: CollectionSchema, resp: &CollectionResponse) -> CollectionResponse { - CollectionResponse { - name: schema.name, - fields: schema.fields, - default_sorting_field: schema.default_sorting_field, - token_separators: schema.token_separators, - enable_nested_fields: schema.enable_nested_fields, - symbols_to_index: schema.symbols_to_index, - num_documents: resp.num_documents, - created_at: resp.created_at, - } -} - -async fn create_collection() { - let collection_schema_response = - collections_api::create_collection(Config::get(), Company::collection_schema()) - .await - .unwrap(); - - assert_eq!(collection_schema_response.num_documents, 0); - assert_eq!( - schema_to_resp(Company::collection_schema(), &collection_schema_response), - collection_schema_response - ); -} - -async fn get_collection() { - let collection_schema_response = collections_api::get_collection(Config::get(), "companies") - .await - .unwrap(); - - assert_eq!(collection_schema_response.num_documents, 1250); - assert_eq!( - schema_to_resp(Company::collection_schema(), &collection_schema_response), - collection_schema_response - ); -} - -async fn delete_collection() { - let collection_schema_response = collections_api::delete_collection(Config::get(), "companies") - .await - .unwrap(); - - assert_eq!(collection_schema_response.num_documents, 1200); - assert_eq!( - schema_to_resp(Company::collection_schema(), &collection_schema_response), - collection_schema_response - ); -} - -async fn get_collections() { - let collection_schema_response = collections_api::get_collections(Config::get()) - .await - .unwrap(); - - assert_eq!(collection_schema_response.len(), 2); -} - -#[cfg(all(feature = "tokio_test", not(target_arch = "wasm32")))] -mod tokio_test { - use super::*; - - #[tokio::test] - async fn create_collection_tokio() { - create_collection().await - } - - #[tokio::test] - async fn get_collection_tokio() { - get_collection().await - } - - #[tokio::test] - async fn delete_collection_tokio() { - delete_collection().await - } - - #[tokio::test] - async fn get_collections_tokio() { - get_collections().await - } -} - -#[cfg(target_arch = "wasm32")] -mod wasm_test { - use super::*; - use wasm_bindgen_test::wasm_bindgen_test; - - wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser); - - #[wasm_bindgen_test] - async fn create_collection_wasm() { - console_error_panic_hook::set_once(); - - create_collection().await - } - - #[wasm_bindgen_test] - async fn get_collection_wasm() { - console_error_panic_hook::set_once(); - - get_collection().await - } - - #[wasm_bindgen_test] - async fn delete_collection_wasm() { - console_error_panic_hook::set_once(); - - delete_collection().await - } - - #[wasm_bindgen_test] - async fn get_collections_wasm() { - console_error_panic_hook::set_once(); - - get_collections().await - } -} diff --git a/typesense/tests/api/documents.rs b/typesense/tests/api/documents.rs deleted file mode 100644 index 8e3b01a..0000000 --- a/typesense/tests/api/documents.rs +++ /dev/null @@ -1,111 +0,0 @@ -#![allow(dead_code)] - -use super::Config; -use serde::{Deserialize, Serialize}; -use typesense::Typesense; -use typesense::document::Document; -use typesense::models::SearchParameters; -use typesense_codegen::apis::documents_api; - -#[derive(Typesense, Serialize, Deserialize)] -#[typesense(collection_name = "companies", default_sorting_field = "num_employees")] -struct Company { - company_name: String, - num_employees: i32, - #[typesense(facet)] - country: String, -} - -async fn import_documents() { - let documents = [ - Company { - company_name: "test".to_owned(), - num_employees: 1, - country: "c1".to_owned(), - }, - Company { - company_name: "test2".to_owned(), - num_employees: 2, - country: "c2".to_owned(), - }, - ] - .map(|c| serde_json::to_string(&c).unwrap()) - .join("\n"); - - let resp = documents_api::import_documents( - Config::get(), - &Company::collection_schema().name, - documents, - None, - ) - .await - .unwrap(); - - assert_eq!(&resp, "{\"success\":true}\n{\"success\":true}"); -} - -async fn search_collection() { - let search = SearchParameters { - q: "test".to_owned(), - query_by: "company_name".to_owned(), - ..Default::default() - }; - - let resp = documents_api::search_collection::( - Config::get(), - &Company::collection_schema().name, - search, - ) - .await - .unwrap(); - - assert_eq!(resp.found, Some(2)); - assert_eq!( - resp.hits - .unwrap() - .first() - .unwrap() - .document - .as_ref() - .unwrap() - .company_name, - "test".to_owned() - ); -} - -#[cfg(all(feature = "tokio_test", not(target_arch = "wasm32")))] -mod tokio_test { - use super::*; - - #[tokio::test] - async fn import_documents_tokio() { - import_documents().await - } - - #[tokio::test] - async fn search_collection_tokio() { - search_collection().await - } -} - -#[cfg(target_arch = "wasm32")] -mod wasm_test { - use super::*; - use wasm_bindgen_test::wasm_bindgen_test; - - wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser); - - #[wasm_bindgen_test] - async fn import_documents_wasm() { - console_error_panic_hook::set_once(); - - import_documents().await - } - - #[wasm_bindgen_test] - async fn search_collection_wasm() { - console_error_panic_hook::set_once(); - - search_collection().await - } -} diff --git a/typesense/tests/api/lib.rs b/typesense/tests/api/lib.rs deleted file mode 100644 index 94a3985..0000000 --- a/typesense/tests/api/lib.rs +++ /dev/null @@ -1,41 +0,0 @@ -use std::sync::OnceLock; -use typesense_codegen::apis::configuration::{ApiKey, Configuration}; - -mod collection; -mod documents; - -static CONFIG: OnceLock = OnceLock::new(); - -#[cfg(not(target_arch = "wasm32"))] -fn init() -> Configuration { - let _ = dotenvy::dotenv(); - - let base_path = std::env::var("URL").expect("URL must be present in .env"); - let key = std::env::var("API_KEY").expect("API_KEY must be present in .env"); - - Configuration { - base_path, - api_key: Some(ApiKey { prefix: None, key }), - ..Default::default() - } -} - -#[cfg(target_arch = "wasm32")] -fn init() -> Configuration { - let base_path = "http://localhost:5000".to_owned(); - let key = "VerySecretKey".to_owned(); - - Configuration { - base_path, - api_key: Some(ApiKey { prefix: None, key }), - ..Default::default() - } -} - -pub struct Config; - -impl Config { - pub fn get() -> &'static Configuration { - CONFIG.get_or_init(init) - } -} diff --git a/typesense_codegen/.openapi-generator-ignore b/typesense_codegen/.openapi-generator-ignore index 7484ee5..b2708db 100644 --- a/typesense_codegen/.openapi-generator-ignore +++ b/typesense_codegen/.openapi-generator-ignore @@ -21,3 +21,8 @@ #docs/*.md # Then explicitly reverse the ignore rule for a single file: #!docs/README.md + +Cargo.toml +src/apis/configuration.rs +src/apis/mod.rs +src/lib.rs \ No newline at end of file diff --git a/typesense_codegen/.openapi-generator/FILES b/typesense_codegen/.openapi-generator/FILES index 2e9cc88..79da908 100644 --- a/typesense_codegen/.openapi-generator/FILES +++ b/typesense_codegen/.openapi-generator/FILES @@ -1,18 +1,23 @@ .gitignore -.openapi-generator-ignore .travis.yml -Cargo.toml README.md docs/AnalyticsApi.md -docs/AnalyticsRuleParameters.md -docs/AnalyticsRuleParametersDestination.md -docs/AnalyticsRuleParametersSource.md -docs/AnalyticsRuleSchema.md -docs/AnalyticsRulesRetrieveSchema.md +docs/AnalyticsEvent.md +docs/AnalyticsEventCreateResponse.md +docs/AnalyticsEventData.md +docs/AnalyticsEventsResponse.md +docs/AnalyticsEventsResponseEventsInner.md +docs/AnalyticsRule.md +docs/AnalyticsRuleCreate.md +docs/AnalyticsRuleCreateParams.md +docs/AnalyticsRuleUpdate.md +docs/AnalyticsStatus.md docs/ApiKey.md +docs/ApiKeyDeleteResponse.md docs/ApiKeySchema.md docs/ApiKeysResponse.md docs/ApiResponse.md +docs/ApiStatsResponse.md docs/CollectionAlias.md docs/CollectionAliasSchema.md docs/CollectionAliasesResponse.md @@ -20,113 +25,209 @@ docs/CollectionResponse.md docs/CollectionSchema.md docs/CollectionUpdateSchema.md docs/CollectionsApi.md +docs/ConversationModelCreateSchema.md +docs/ConversationModelSchema.md +docs/ConversationModelUpdateSchema.md +docs/ConversationsApi.md +docs/CreateAnalyticsRule200Response.md +docs/CreateAnalyticsRule200ResponseOneOfInner.md +docs/CreateAnalyticsRule200ResponseOneOfInnerAnyOf.md +docs/CreateAnalyticsRuleRequest.md +docs/CurationApi.md docs/Debug200Response.md docs/DebugApi.md docs/DeleteDocuments200Response.md -docs/DeleteDocumentsDeleteDocumentsParametersParameter.md +docs/DeleteDocumentsParameters.md +docs/DeleteStopwordsSet200Response.md +docs/DirtyValues.md docs/DocumentsApi.md -docs/ErrorResponse.md -docs/ExportDocumentsExportDocumentsParametersParameter.md +docs/DropTokensMode.md +docs/ExportDocumentsParameters.md docs/FacetCounts.md docs/FacetCountsCountsInner.md docs/FacetCountsStats.md docs/Field.md docs/FieldEmbed.md docs/FieldEmbedModelConfig.md +docs/GetCollectionsParameters.md docs/HealthApi.md docs/HealthStatus.md -docs/ImportDocumentsImportDocumentsParametersParameter.md +docs/ImportDocumentsParameters.md +docs/IndexAction.md docs/KeysApi.md +docs/ListStemmingDictionaries200Response.md docs/MultiSearchCollectionParameters.md docs/MultiSearchParameters.md docs/MultiSearchResult.md +docs/MultiSearchResultItem.md docs/MultiSearchSearchesParameter.md +docs/NlSearchModelBase.md +docs/NlSearchModelCreateSchema.md +docs/NlSearchModelDeleteSchema.md +docs/NlSearchModelSchema.md +docs/NlSearchModelsApi.md docs/OperationsApi.md docs/OverrideApi.md -docs/PromoteApi.md -docs/ScopedKeyParameters.md +docs/PresetDeleteSchema.md +docs/PresetSchema.md +docs/PresetUpsertSchema.md +docs/PresetUpsertSchemaValue.md +docs/PresetsApi.md +docs/PresetsRetrieveSchema.md +docs/SchemaChangeStatus.md docs/SearchGroupedHit.md docs/SearchHighlight.md docs/SearchOverride.md +docs/SearchOverrideDeleteResponse.md docs/SearchOverrideExclude.md docs/SearchOverrideInclude.md docs/SearchOverrideRule.md docs/SearchOverrideSchema.md docs/SearchOverridesResponse.md docs/SearchParameters.md +docs/SearchRequestParams.md +docs/SearchRequestParamsVoiceQuery.md docs/SearchResult.md +docs/SearchResultConversation.md docs/SearchResultHit.md -docs/SearchResultRequestParams.md +docs/SearchResultHitHybridSearchInfo.md +docs/SearchResultHitTextMatchInfo.md docs/SearchSynonym.md +docs/SearchSynonymDeleteResponse.md docs/SearchSynonymSchema.md docs/SearchSynonymsResponse.md -docs/SnapshotParameters.md +docs/StemmingApi.md +docs/StemmingDictionary.md +docs/StemmingDictionaryWordsInner.md +docs/StopwordsApi.md +docs/StopwordsSetRetrieveSchema.md +docs/StopwordsSetSchema.md +docs/StopwordsSetUpsertSchema.md +docs/StopwordsSetsRetrieveAllSchema.md docs/SuccessStatus.md +docs/SynonymItemSchema.md +docs/SynonymSetCreateSchema.md +docs/SynonymSetDeleteSchema.md +docs/SynonymSetSchema.md +docs/SynonymSetsRetrieveSchema.md +docs/SynonymsApi.md +docs/ToggleSlowRequestLogRequest.md docs/UpdateDocuments200Response.md -docs/UpdateDocumentsUpdateDocumentsParametersParameter.md +docs/UpdateDocumentsParameters.md +docs/VoiceQueryModelCollectionConfig.md git_push.sh src/apis/analytics_api.rs src/apis/collections_api.rs -src/apis/configuration.rs +src/apis/conversations_api.rs +src/apis/curation_api.rs src/apis/debug_api.rs src/apis/documents_api.rs src/apis/health_api.rs src/apis/keys_api.rs -src/apis/mod.rs +src/apis/nl_search_models_api.rs src/apis/operations_api.rs src/apis/override_api.rs -src/apis/promote_api.rs -src/lib.rs -src/models/analytics_rule_parameters.rs -src/models/analytics_rule_parameters_destination.rs -src/models/analytics_rule_parameters_source.rs -src/models/analytics_rule_schema.rs -src/models/analytics_rules_retrieve_schema.rs +src/apis/presets_api.rs +src/apis/stemming_api.rs +src/apis/stopwords_api.rs +src/apis/synonyms_api.rs +src/models/analytics_event.rs +src/models/analytics_event_create_response.rs +src/models/analytics_event_data.rs +src/models/analytics_events_response.rs +src/models/analytics_events_response_events_inner.rs +src/models/analytics_rule.rs +src/models/analytics_rule_create.rs +src/models/analytics_rule_create_params.rs +src/models/analytics_rule_update.rs +src/models/analytics_status.rs src/models/api_key.rs +src/models/api_key_delete_response.rs src/models/api_key_schema.rs src/models/api_keys_response.rs src/models/api_response.rs +src/models/api_stats_response.rs src/models/collection_alias.rs src/models/collection_alias_schema.rs src/models/collection_aliases_response.rs src/models/collection_response.rs src/models/collection_schema.rs src/models/collection_update_schema.rs +src/models/conversation_model_create_schema.rs +src/models/conversation_model_schema.rs +src/models/conversation_model_update_schema.rs +src/models/create_analytics_rule_200_response.rs +src/models/create_analytics_rule_200_response_one_of_inner.rs +src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs +src/models/create_analytics_rule_request.rs src/models/debug_200_response.rs src/models/delete_documents_200_response.rs -src/models/delete_documents_delete_documents_parameters_parameter.rs -src/models/error_response.rs -src/models/export_documents_export_documents_parameters_parameter.rs +src/models/delete_documents_parameters.rs +src/models/delete_stopwords_set_200_response.rs +src/models/dirty_values.rs +src/models/drop_tokens_mode.rs +src/models/export_documents_parameters.rs src/models/facet_counts.rs src/models/facet_counts_counts_inner.rs src/models/facet_counts_stats.rs src/models/field.rs src/models/field_embed.rs src/models/field_embed_model_config.rs +src/models/get_collections_parameters.rs src/models/health_status.rs -src/models/import_documents_import_documents_parameters_parameter.rs +src/models/import_documents_parameters.rs +src/models/index_action.rs +src/models/list_stemming_dictionaries_200_response.rs src/models/mod.rs src/models/multi_search_collection_parameters.rs src/models/multi_search_parameters.rs src/models/multi_search_result.rs +src/models/multi_search_result_item.rs src/models/multi_search_searches_parameter.rs -src/models/scoped_key_parameters.rs +src/models/nl_search_model_base.rs +src/models/nl_search_model_create_schema.rs +src/models/nl_search_model_delete_schema.rs +src/models/nl_search_model_schema.rs +src/models/preset_delete_schema.rs +src/models/preset_schema.rs +src/models/preset_upsert_schema.rs +src/models/preset_upsert_schema_value.rs +src/models/presets_retrieve_schema.rs +src/models/schema_change_status.rs src/models/search_grouped_hit.rs src/models/search_highlight.rs src/models/search_override.rs +src/models/search_override_delete_response.rs src/models/search_override_exclude.rs src/models/search_override_include.rs src/models/search_override_rule.rs src/models/search_override_schema.rs src/models/search_overrides_response.rs src/models/search_parameters.rs +src/models/search_request_params.rs +src/models/search_request_params_voice_query.rs src/models/search_result.rs +src/models/search_result_conversation.rs src/models/search_result_hit.rs -src/models/search_result_request_params.rs +src/models/search_result_hit_hybrid_search_info.rs +src/models/search_result_hit_text_match_info.rs src/models/search_synonym.rs +src/models/search_synonym_delete_response.rs src/models/search_synonym_schema.rs src/models/search_synonyms_response.rs -src/models/snapshot_parameters.rs +src/models/stemming_dictionary.rs +src/models/stemming_dictionary_words_inner.rs +src/models/stopwords_set_retrieve_schema.rs +src/models/stopwords_set_schema.rs +src/models/stopwords_set_upsert_schema.rs +src/models/stopwords_sets_retrieve_all_schema.rs src/models/success_status.rs +src/models/synonym_item_schema.rs +src/models/synonym_set_create_schema.rs +src/models/synonym_set_delete_schema.rs +src/models/synonym_set_schema.rs +src/models/synonym_sets_retrieve_schema.rs +src/models/toggle_slow_request_log_request.rs src/models/update_documents_200_response.rs -src/models/update_documents_update_documents_parameters_parameter.rs +src/models/update_documents_parameters.rs +src/models/voice_query_model_collection_config.rs diff --git a/typesense_codegen/.openapi-generator/VERSION b/typesense_codegen/.openapi-generator/VERSION index c9e125b..e465da4 100644 --- a/typesense_codegen/.openapi-generator/VERSION +++ b/typesense_codegen/.openapi-generator/VERSION @@ -1 +1 @@ -7.4.0-SNAPSHOT +7.14.0 diff --git a/typesense_codegen/Cargo.toml b/typesense_codegen/Cargo.toml index 8b1aefb..51d07b6 100644 --- a/typesense_codegen/Cargo.toml +++ b/typesense_codegen/Cargo.toml @@ -8,12 +8,16 @@ edition.workspace = true license.workspace = true [dependencies] -serde = "^1.0" -serde_derive = "^1.0" +serde = { version = "^1.0", features = ["derive"] } serde_json = "^1.0" -url = "^2.2" -uuid = { version = "^1.0", features = ["serde", "v4", "js"] } +serde_repr = "^0.1" +url = "^2.5" +bon = "3.7.0" +reqwest = { version = "0.12", default-features = false, features = ["json"] } +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +reqwest-middleware = { version = "0.4", features = ["json"] } -[dependencies.reqwest] -version = "^0.12" -features = ["json", "multipart"] +[features] +default = ["native-tls"] +native-tls = ["reqwest/native-tls"] +rustls = ["reqwest/rustls-tls"] diff --git a/typesense_codegen/README.md b/typesense_codegen/README.md index c634c1d..f16906b 100644 --- a/typesense_codegen/README.md +++ b/typesense_codegen/README.md @@ -7,8 +7,9 @@ An open source search engine for building delightful search experiences. This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://openapis.org) from a remote server, you can easily generate an API client. -- API version: 0.25.0 -- Package version: 0.25.0 +- API version: 30.0 +- Package version: 30.0 +- Generator version: 7.14.0 - Build package: `org.openapitools.codegen.languages.RustClientCodegen` ## Installation @@ -21,14 +22,19 @@ openapi = { path = "./openapi" } ## Documentation for API Endpoints -All URIs are relative to *http://localhost* +All URIs are relative to *http://localhost:8108* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*AnalyticsApi* | [**create_analytics_rule**](docs/AnalyticsApi.md#create_analytics_rule) | **POST** /analytics/rules | Creates an analytics rule +*AnalyticsApi* | [**create_analytics_event**](docs/AnalyticsApi.md#create_analytics_event) | **POST** /analytics/events | Create an analytics event +*AnalyticsApi* | [**create_analytics_rule**](docs/AnalyticsApi.md#create_analytics_rule) | **POST** /analytics/rules | Create analytics rule(s) *AnalyticsApi* | [**delete_analytics_rule**](docs/AnalyticsApi.md#delete_analytics_rule) | **DELETE** /analytics/rules/{ruleName} | Delete an analytics rule +*AnalyticsApi* | [**flush_analytics**](docs/AnalyticsApi.md#flush_analytics) | **POST** /analytics/flush | Flush in-memory analytics to disk +*AnalyticsApi* | [**get_analytics_events**](docs/AnalyticsApi.md#get_analytics_events) | **GET** /analytics/events | Retrieve analytics events +*AnalyticsApi* | [**get_analytics_status**](docs/AnalyticsApi.md#get_analytics_status) | **GET** /analytics/status | Get analytics subsystem status *AnalyticsApi* | [**retrieve_analytics_rule**](docs/AnalyticsApi.md#retrieve_analytics_rule) | **GET** /analytics/rules/{ruleName} | Retrieves an analytics rule -*AnalyticsApi* | [**retrieve_analytics_rules**](docs/AnalyticsApi.md#retrieve_analytics_rules) | **GET** /analytics/rules | Retrieves all analytics rules +*AnalyticsApi* | [**retrieve_analytics_rules**](docs/AnalyticsApi.md#retrieve_analytics_rules) | **GET** /analytics/rules | Retrieve analytics rules +*AnalyticsApi* | [**upsert_analytics_rule**](docs/AnalyticsApi.md#upsert_analytics_rule) | **PUT** /analytics/rules/{ruleName} | Upserts an analytics rule *CollectionsApi* | [**create_collection**](docs/CollectionsApi.md#create_collection) | **POST** /collections | Create a new collection *CollectionsApi* | [**delete_alias**](docs/CollectionsApi.md#delete_alias) | **DELETE** /aliases/{aliasName} | Delete an alias *CollectionsApi* | [**delete_collection**](docs/CollectionsApi.md#delete_collection) | **DELETE** /collections/{collectionName} | Delete a collection @@ -38,17 +44,22 @@ Class | Method | HTTP request | Description *CollectionsApi* | [**get_collections**](docs/CollectionsApi.md#get_collections) | **GET** /collections | List all collections *CollectionsApi* | [**update_collection**](docs/CollectionsApi.md#update_collection) | **PATCH** /collections/{collectionName} | Update a collection *CollectionsApi* | [**upsert_alias**](docs/CollectionsApi.md#upsert_alias) | **PUT** /aliases/{aliasName} | Create or update a collection alias +*ConversationsApi* | [**create_conversation_model**](docs/ConversationsApi.md#create_conversation_model) | **POST** /conversations/models | Create a conversation model +*ConversationsApi* | [**delete_conversation_model**](docs/ConversationsApi.md#delete_conversation_model) | **DELETE** /conversations/models/{modelId} | Delete a conversation model +*ConversationsApi* | [**retrieve_all_conversation_models**](docs/ConversationsApi.md#retrieve_all_conversation_models) | **GET** /conversations/models | List all conversation models +*ConversationsApi* | [**retrieve_conversation_model**](docs/ConversationsApi.md#retrieve_conversation_model) | **GET** /conversations/models/{modelId} | Retrieve a conversation model +*ConversationsApi* | [**update_conversation_model**](docs/ConversationsApi.md#update_conversation_model) | **PUT** /conversations/models/{modelId} | Update a conversation model +*CurationApi* | [**delete_search_override**](docs/CurationApi.md#delete_search_override) | **DELETE** /collections/{collectionName}/overrides/{overrideId} | Delete an override associated with a collection +*CurationApi* | [**get_search_overrides**](docs/CurationApi.md#get_search_overrides) | **GET** /collections/{collectionName}/overrides | List all collection overrides +*CurationApi* | [**upsert_search_override**](docs/CurationApi.md#upsert_search_override) | **PUT** /collections/{collectionName}/overrides/{overrideId} | Create or update an override to promote certain documents over others *DebugApi* | [**debug**](docs/DebugApi.md#debug) | **GET** /debug | Print debugging information *DocumentsApi* | [**delete_document**](docs/DocumentsApi.md#delete_document) | **DELETE** /collections/{collectionName}/documents/{documentId} | Delete a document *DocumentsApi* | [**delete_documents**](docs/DocumentsApi.md#delete_documents) | **DELETE** /collections/{collectionName}/documents | Delete a bunch of documents *DocumentsApi* | [**delete_search_override**](docs/DocumentsApi.md#delete_search_override) | **DELETE** /collections/{collectionName}/overrides/{overrideId} | Delete an override associated with a collection -*DocumentsApi* | [**delete_search_synonym**](docs/DocumentsApi.md#delete_search_synonym) | **DELETE** /collections/{collectionName}/synonyms/{synonymId} | Delete a synonym associated with a collection *DocumentsApi* | [**export_documents**](docs/DocumentsApi.md#export_documents) | **GET** /collections/{collectionName}/documents/export | Export all documents in a collection -*DocumentsApi* | [**get_document**](docs/DocumentsApi.md#get_document) | **GET** /collections/{collectionName}/documents/{documentId} | Retreive a document +*DocumentsApi* | [**get_document**](docs/DocumentsApi.md#get_document) | **GET** /collections/{collectionName}/documents/{documentId} | Retrieve a document *DocumentsApi* | [**get_search_override**](docs/DocumentsApi.md#get_search_override) | **GET** /collections/{collectionName}/overrides/{overrideId} | Retrieve a single search override *DocumentsApi* | [**get_search_overrides**](docs/DocumentsApi.md#get_search_overrides) | **GET** /collections/{collectionName}/overrides | List all collection overrides -*DocumentsApi* | [**get_search_synonym**](docs/DocumentsApi.md#get_search_synonym) | **GET** /collections/{collectionName}/synonyms/{synonymId} | Retrieve a single search synonym -*DocumentsApi* | [**get_search_synonyms**](docs/DocumentsApi.md#get_search_synonyms) | **GET** /collections/{collectionName}/synonyms | List all collection synonyms *DocumentsApi* | [**import_documents**](docs/DocumentsApi.md#import_documents) | **POST** /collections/{collectionName}/documents/import | Import documents into a collection *DocumentsApi* | [**index_document**](docs/DocumentsApi.md#index_document) | **POST** /collections/{collectionName}/documents | Index a document *DocumentsApi* | [**multi_search**](docs/DocumentsApi.md#multi_search) | **POST** /multi_search | send multiple search requests in a single HTTP request @@ -56,74 +67,143 @@ Class | Method | HTTP request | Description *DocumentsApi* | [**update_document**](docs/DocumentsApi.md#update_document) | **PATCH** /collections/{collectionName}/documents/{documentId} | Update a document *DocumentsApi* | [**update_documents**](docs/DocumentsApi.md#update_documents) | **PATCH** /collections/{collectionName}/documents | Update documents with conditional query *DocumentsApi* | [**upsert_search_override**](docs/DocumentsApi.md#upsert_search_override) | **PUT** /collections/{collectionName}/overrides/{overrideId} | Create or update an override to promote certain documents over others -*DocumentsApi* | [**upsert_search_synonym**](docs/DocumentsApi.md#upsert_search_synonym) | **PUT** /collections/{collectionName}/synonyms/{synonymId} | Create or update a synonym *HealthApi* | [**health**](docs/HealthApi.md#health) | **GET** /health | Checks if Typesense server is ready to accept requests. *KeysApi* | [**create_key**](docs/KeysApi.md#create_key) | **POST** /keys | Create an API Key *KeysApi* | [**delete_key**](docs/KeysApi.md#delete_key) | **DELETE** /keys/{keyId} | Delete an API key given its ID. *KeysApi* | [**get_key**](docs/KeysApi.md#get_key) | **GET** /keys/{keyId} | Retrieve (metadata about) a key *KeysApi* | [**get_keys**](docs/KeysApi.md#get_keys) | **GET** /keys | Retrieve (metadata about) all keys. +*NlSearchModelsApi* | [**create_nl_search_model**](docs/NlSearchModelsApi.md#create_nl_search_model) | **POST** /nl_search_models | Create a NL search model +*NlSearchModelsApi* | [**delete_nl_search_model**](docs/NlSearchModelsApi.md#delete_nl_search_model) | **DELETE** /nl_search_models/{modelId} | Delete a NL search model +*NlSearchModelsApi* | [**retrieve_all_nl_search_models**](docs/NlSearchModelsApi.md#retrieve_all_nl_search_models) | **GET** /nl_search_models | List all NL search models +*NlSearchModelsApi* | [**retrieve_nl_search_model**](docs/NlSearchModelsApi.md#retrieve_nl_search_model) | **GET** /nl_search_models/{modelId} | Retrieve a NL search model +*NlSearchModelsApi* | [**update_nl_search_model**](docs/NlSearchModelsApi.md#update_nl_search_model) | **PUT** /nl_search_models/{modelId} | Update a NL search model +*OperationsApi* | [**clear_cache**](docs/OperationsApi.md#clear_cache) | **POST** /operations/cache/clear | Clear the cached responses of search requests in the LRU cache. +*OperationsApi* | [**compact_db**](docs/OperationsApi.md#compact_db) | **POST** /operations/db/compact | Compacting the on-disk database +*OperationsApi* | [**get_schema_changes**](docs/OperationsApi.md#get_schema_changes) | **GET** /operations/schema_changes | Get the status of in-progress schema change operations +*OperationsApi* | [**retrieve_api_stats**](docs/OperationsApi.md#retrieve_api_stats) | **GET** /stats.json | Get stats about API endpoints. +*OperationsApi* | [**retrieve_metrics**](docs/OperationsApi.md#retrieve_metrics) | **GET** /metrics.json | Get current RAM, CPU, Disk & Network usage metrics. *OperationsApi* | [**take_snapshot**](docs/OperationsApi.md#take_snapshot) | **POST** /operations/snapshot | Creates a point-in-time snapshot of a Typesense node's state and data in the specified directory. +*OperationsApi* | [**toggle_slow_request_log**](docs/OperationsApi.md#toggle_slow_request_log) | **POST** /config | Toggle Slow Request Log *OperationsApi* | [**vote**](docs/OperationsApi.md#vote) | **POST** /operations/vote | Triggers a follower node to initiate the raft voting process, which triggers leader re-election. *OverrideApi* | [**get_search_override**](docs/OverrideApi.md#get_search_override) | **GET** /collections/{collectionName}/overrides/{overrideId} | Retrieve a single search override -*PromoteApi* | [**delete_search_override**](docs/PromoteApi.md#delete_search_override) | **DELETE** /collections/{collectionName}/overrides/{overrideId} | Delete an override associated with a collection -*PromoteApi* | [**get_search_overrides**](docs/PromoteApi.md#get_search_overrides) | **GET** /collections/{collectionName}/overrides | List all collection overrides -*PromoteApi* | [**upsert_search_override**](docs/PromoteApi.md#upsert_search_override) | **PUT** /collections/{collectionName}/overrides/{overrideId} | Create or update an override to promote certain documents over others +*PresetsApi* | [**delete_preset**](docs/PresetsApi.md#delete_preset) | **DELETE** /presets/{presetId} | Delete a preset. +*PresetsApi* | [**retrieve_all_presets**](docs/PresetsApi.md#retrieve_all_presets) | **GET** /presets | Retrieves all presets. +*PresetsApi* | [**retrieve_preset**](docs/PresetsApi.md#retrieve_preset) | **GET** /presets/{presetId} | Retrieves a preset. +*PresetsApi* | [**upsert_preset**](docs/PresetsApi.md#upsert_preset) | **PUT** /presets/{presetId} | Upserts a preset. +*StemmingApi* | [**get_stemming_dictionary**](docs/StemmingApi.md#get_stemming_dictionary) | **GET** /stemming/dictionaries/{dictionaryId} | Retrieve a stemming dictionary +*StemmingApi* | [**import_stemming_dictionary**](docs/StemmingApi.md#import_stemming_dictionary) | **POST** /stemming/dictionaries/import | Import a stemming dictionary +*StemmingApi* | [**list_stemming_dictionaries**](docs/StemmingApi.md#list_stemming_dictionaries) | **GET** /stemming/dictionaries | List all stemming dictionaries +*StopwordsApi* | [**delete_stopwords_set**](docs/StopwordsApi.md#delete_stopwords_set) | **DELETE** /stopwords/{setId} | Delete a stopwords set. +*StopwordsApi* | [**retrieve_stopwords_set**](docs/StopwordsApi.md#retrieve_stopwords_set) | **GET** /stopwords/{setId} | Retrieves a stopwords set. +*StopwordsApi* | [**retrieve_stopwords_sets**](docs/StopwordsApi.md#retrieve_stopwords_sets) | **GET** /stopwords | Retrieves all stopwords sets. +*StopwordsApi* | [**upsert_stopwords_set**](docs/StopwordsApi.md#upsert_stopwords_set) | **PUT** /stopwords/{setId} | Upserts a stopwords set. +*SynonymsApi* | [**delete_synonym_set**](docs/SynonymsApi.md#delete_synonym_set) | **DELETE** /synonym_sets/{synonymSetName} | Delete a synonym set +*SynonymsApi* | [**retrieve_synonym_set**](docs/SynonymsApi.md#retrieve_synonym_set) | **GET** /synonym_sets/{synonymSetName} | Retrieve a synonym set +*SynonymsApi* | [**retrieve_synonym_sets**](docs/SynonymsApi.md#retrieve_synonym_sets) | **GET** /synonym_sets | List all synonym sets +*SynonymsApi* | [**upsert_synonym_set**](docs/SynonymsApi.md#upsert_synonym_set) | **PUT** /synonym_sets/{synonymSetName} | Create or update a synonym set ## Documentation For Models - - [AnalyticsRuleParameters](docs/AnalyticsRuleParameters.md) - - [AnalyticsRuleParametersDestination](docs/AnalyticsRuleParametersDestination.md) - - [AnalyticsRuleParametersSource](docs/AnalyticsRuleParametersSource.md) - - [AnalyticsRuleSchema](docs/AnalyticsRuleSchema.md) - - [AnalyticsRulesRetrieveSchema](docs/AnalyticsRulesRetrieveSchema.md) + - [AnalyticsEvent](docs/AnalyticsEvent.md) + - [AnalyticsEventCreateResponse](docs/AnalyticsEventCreateResponse.md) + - [AnalyticsEventData](docs/AnalyticsEventData.md) + - [AnalyticsEventsResponse](docs/AnalyticsEventsResponse.md) + - [AnalyticsEventsResponseEventsInner](docs/AnalyticsEventsResponseEventsInner.md) + - [AnalyticsRule](docs/AnalyticsRule.md) + - [AnalyticsRuleCreate](docs/AnalyticsRuleCreate.md) + - [AnalyticsRuleCreateParams](docs/AnalyticsRuleCreateParams.md) + - [AnalyticsRuleUpdate](docs/AnalyticsRuleUpdate.md) + - [AnalyticsStatus](docs/AnalyticsStatus.md) - [ApiKey](docs/ApiKey.md) + - [ApiKeyDeleteResponse](docs/ApiKeyDeleteResponse.md) - [ApiKeySchema](docs/ApiKeySchema.md) - [ApiKeysResponse](docs/ApiKeysResponse.md) - [ApiResponse](docs/ApiResponse.md) + - [ApiStatsResponse](docs/ApiStatsResponse.md) - [CollectionAlias](docs/CollectionAlias.md) - [CollectionAliasSchema](docs/CollectionAliasSchema.md) - [CollectionAliasesResponse](docs/CollectionAliasesResponse.md) - [CollectionResponse](docs/CollectionResponse.md) - [CollectionSchema](docs/CollectionSchema.md) - [CollectionUpdateSchema](docs/CollectionUpdateSchema.md) + - [ConversationModelCreateSchema](docs/ConversationModelCreateSchema.md) + - [ConversationModelSchema](docs/ConversationModelSchema.md) + - [ConversationModelUpdateSchema](docs/ConversationModelUpdateSchema.md) + - [CreateAnalyticsRule200Response](docs/CreateAnalyticsRule200Response.md) + - [CreateAnalyticsRule200ResponseOneOfInner](docs/CreateAnalyticsRule200ResponseOneOfInner.md) + - [CreateAnalyticsRule200ResponseOneOfInnerAnyOf](docs/CreateAnalyticsRule200ResponseOneOfInnerAnyOf.md) + - [CreateAnalyticsRuleRequest](docs/CreateAnalyticsRuleRequest.md) - [Debug200Response](docs/Debug200Response.md) - [DeleteDocuments200Response](docs/DeleteDocuments200Response.md) - - [DeleteDocumentsDeleteDocumentsParametersParameter](docs/DeleteDocumentsDeleteDocumentsParametersParameter.md) - - [ErrorResponse](docs/ErrorResponse.md) - - [ExportDocumentsExportDocumentsParametersParameter](docs/ExportDocumentsExportDocumentsParametersParameter.md) + - [DeleteDocumentsParameters](docs/DeleteDocumentsParameters.md) + - [DeleteStopwordsSet200Response](docs/DeleteStopwordsSet200Response.md) + - [DirtyValues](docs/DirtyValues.md) + - [DropTokensMode](docs/DropTokensMode.md) + - [ExportDocumentsParameters](docs/ExportDocumentsParameters.md) - [FacetCounts](docs/FacetCounts.md) - [FacetCountsCountsInner](docs/FacetCountsCountsInner.md) - [FacetCountsStats](docs/FacetCountsStats.md) - [Field](docs/Field.md) - [FieldEmbed](docs/FieldEmbed.md) - [FieldEmbedModelConfig](docs/FieldEmbedModelConfig.md) + - [GetCollectionsParameters](docs/GetCollectionsParameters.md) - [HealthStatus](docs/HealthStatus.md) - - [ImportDocumentsImportDocumentsParametersParameter](docs/ImportDocumentsImportDocumentsParametersParameter.md) + - [ImportDocumentsParameters](docs/ImportDocumentsParameters.md) + - [IndexAction](docs/IndexAction.md) + - [ListStemmingDictionaries200Response](docs/ListStemmingDictionaries200Response.md) - [MultiSearchCollectionParameters](docs/MultiSearchCollectionParameters.md) - [MultiSearchParameters](docs/MultiSearchParameters.md) - [MultiSearchResult](docs/MultiSearchResult.md) + - [MultiSearchResultItem](docs/MultiSearchResultItem.md) - [MultiSearchSearchesParameter](docs/MultiSearchSearchesParameter.md) - - [ScopedKeyParameters](docs/ScopedKeyParameters.md) + - [NlSearchModelBase](docs/NlSearchModelBase.md) + - [NlSearchModelCreateSchema](docs/NlSearchModelCreateSchema.md) + - [NlSearchModelDeleteSchema](docs/NlSearchModelDeleteSchema.md) + - [NlSearchModelSchema](docs/NlSearchModelSchema.md) + - [PresetDeleteSchema](docs/PresetDeleteSchema.md) + - [PresetSchema](docs/PresetSchema.md) + - [PresetUpsertSchema](docs/PresetUpsertSchema.md) + - [PresetUpsertSchemaValue](docs/PresetUpsertSchemaValue.md) + - [PresetsRetrieveSchema](docs/PresetsRetrieveSchema.md) + - [SchemaChangeStatus](docs/SchemaChangeStatus.md) - [SearchGroupedHit](docs/SearchGroupedHit.md) - [SearchHighlight](docs/SearchHighlight.md) - [SearchOverride](docs/SearchOverride.md) + - [SearchOverrideDeleteResponse](docs/SearchOverrideDeleteResponse.md) - [SearchOverrideExclude](docs/SearchOverrideExclude.md) - [SearchOverrideInclude](docs/SearchOverrideInclude.md) - [SearchOverrideRule](docs/SearchOverrideRule.md) - [SearchOverrideSchema](docs/SearchOverrideSchema.md) - [SearchOverridesResponse](docs/SearchOverridesResponse.md) - [SearchParameters](docs/SearchParameters.md) + - [SearchRequestParams](docs/SearchRequestParams.md) + - [SearchRequestParamsVoiceQuery](docs/SearchRequestParamsVoiceQuery.md) - [SearchResult](docs/SearchResult.md) + - [SearchResultConversation](docs/SearchResultConversation.md) - [SearchResultHit](docs/SearchResultHit.md) - - [SearchResultRequestParams](docs/SearchResultRequestParams.md) + - [SearchResultHitHybridSearchInfo](docs/SearchResultHitHybridSearchInfo.md) + - [SearchResultHitTextMatchInfo](docs/SearchResultHitTextMatchInfo.md) - [SearchSynonym](docs/SearchSynonym.md) + - [SearchSynonymDeleteResponse](docs/SearchSynonymDeleteResponse.md) - [SearchSynonymSchema](docs/SearchSynonymSchema.md) - [SearchSynonymsResponse](docs/SearchSynonymsResponse.md) - - [SnapshotParameters](docs/SnapshotParameters.md) + - [StemmingDictionary](docs/StemmingDictionary.md) + - [StemmingDictionaryWordsInner](docs/StemmingDictionaryWordsInner.md) + - [StopwordsSetRetrieveSchema](docs/StopwordsSetRetrieveSchema.md) + - [StopwordsSetSchema](docs/StopwordsSetSchema.md) + - [StopwordsSetUpsertSchema](docs/StopwordsSetUpsertSchema.md) + - [StopwordsSetsRetrieveAllSchema](docs/StopwordsSetsRetrieveAllSchema.md) - [SuccessStatus](docs/SuccessStatus.md) + - [SynonymItemSchema](docs/SynonymItemSchema.md) + - [SynonymSetCreateSchema](docs/SynonymSetCreateSchema.md) + - [SynonymSetDeleteSchema](docs/SynonymSetDeleteSchema.md) + - [SynonymSetSchema](docs/SynonymSetSchema.md) + - [SynonymSetsRetrieveSchema](docs/SynonymSetsRetrieveSchema.md) + - [ToggleSlowRequestLogRequest](docs/ToggleSlowRequestLogRequest.md) - [UpdateDocuments200Response](docs/UpdateDocuments200Response.md) - - [UpdateDocumentsUpdateDocumentsParametersParameter](docs/UpdateDocumentsUpdateDocumentsParametersParameter.md) + - [UpdateDocumentsParameters](docs/UpdateDocumentsParameters.md) + - [VoiceQueryModelCollectionConfig](docs/VoiceQueryModelCollectionConfig.md) To get access to the crate's generated documentation, use: diff --git a/typesense_codegen/docs/AnalyticsApi.md b/typesense_codegen/docs/AnalyticsApi.md index 7b6b7d0..b69fc6e 100644 --- a/typesense_codegen/docs/AnalyticsApi.md +++ b/typesense_codegen/docs/AnalyticsApi.md @@ -1,33 +1,68 @@ # \AnalyticsApi -All URIs are relative to *http://localhost* +All URIs are relative to *http://localhost:8108* Method | HTTP request | Description ------------- | ------------- | ------------- -[**create_analytics_rule**](AnalyticsApi.md#create_analytics_rule) | **POST** /analytics/rules | Creates an analytics rule +[**create_analytics_event**](AnalyticsApi.md#create_analytics_event) | **POST** /analytics/events | Create an analytics event +[**create_analytics_rule**](AnalyticsApi.md#create_analytics_rule) | **POST** /analytics/rules | Create analytics rule(s) [**delete_analytics_rule**](AnalyticsApi.md#delete_analytics_rule) | **DELETE** /analytics/rules/{ruleName} | Delete an analytics rule +[**flush_analytics**](AnalyticsApi.md#flush_analytics) | **POST** /analytics/flush | Flush in-memory analytics to disk +[**get_analytics_events**](AnalyticsApi.md#get_analytics_events) | **GET** /analytics/events | Retrieve analytics events +[**get_analytics_status**](AnalyticsApi.md#get_analytics_status) | **GET** /analytics/status | Get analytics subsystem status [**retrieve_analytics_rule**](AnalyticsApi.md#retrieve_analytics_rule) | **GET** /analytics/rules/{ruleName} | Retrieves an analytics rule -[**retrieve_analytics_rules**](AnalyticsApi.md#retrieve_analytics_rules) | **GET** /analytics/rules | Retrieves all analytics rules +[**retrieve_analytics_rules**](AnalyticsApi.md#retrieve_analytics_rules) | **GET** /analytics/rules | Retrieve analytics rules +[**upsert_analytics_rule**](AnalyticsApi.md#upsert_analytics_rule) | **PUT** /analytics/rules/{ruleName} | Upserts an analytics rule +## create_analytics_event + +> models::AnalyticsEventCreateResponse create_analytics_event(analytics_event) +Create an analytics event + +Submit a single analytics event. The event must correspond to an existing analytics rule by name. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**analytics_event** | [**AnalyticsEvent**](AnalyticsEvent.md) | The analytics event to be created | [required] | + +### Return type + +[**models::AnalyticsEventCreateResponse**](AnalyticsEventCreateResponse.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + ## create_analytics_rule -> crate::models::AnalyticsRuleSchema create_analytics_rule(analytics_rule_schema) -Creates an analytics rule +> models::CreateAnalyticsRule200Response create_analytics_rule(create_analytics_rule_request) +Create analytics rule(s) -When an analytics rule is created, we give it a name and describe the type, the source collections and the destination collection. +Create one or more analytics rules. You can send a single rule object or an array of rule objects. ### Parameters Name | Type | Description | Required | Notes ------------- | ------------- | ------------- | ------------- | ------------- -**analytics_rule_schema** | [**AnalyticsRuleSchema**](AnalyticsRuleSchema.md) | The Analytics rule to be created | [required] | +**create_analytics_rule_request** | [**CreateAnalyticsRuleRequest**](CreateAnalyticsRuleRequest.md) | The analytics rule(s) to be created | [required] | ### Return type -[**crate::models::AnalyticsRuleSchema**](AnalyticsRuleSchema.md) +[**models::CreateAnalyticsRule200Response**](createAnalyticsRule_200_response.md) ### Authorization @@ -43,7 +78,7 @@ Name | Type | Description | Required | Notes ## delete_analytics_rule -> crate::models::AnalyticsRuleSchema delete_analytics_rule(rule_name) +> models::AnalyticsRule delete_analytics_rule(rule_name) Delete an analytics rule Permanently deletes an analytics rule, given it's name @@ -57,7 +92,93 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::AnalyticsRuleSchema**](AnalyticsRuleSchema.md) +[**models::AnalyticsRule**](AnalyticsRule.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## flush_analytics + +> models::AnalyticsEventCreateResponse flush_analytics() +Flush in-memory analytics to disk + +Triggers a flush of analytics data to persistent storage. + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**models::AnalyticsEventCreateResponse**](AnalyticsEventCreateResponse.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## get_analytics_events + +> models::AnalyticsEventsResponse get_analytics_events(user_id, name, n) +Retrieve analytics events + +Retrieve the most recent events for a user and rule. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**user_id** | **String** | | [required] | +**name** | **String** | Analytics rule name | [required] | +**n** | **i32** | Number of events to return (max 1000) | [required] | + +### Return type + +[**models::AnalyticsEventsResponse**](AnalyticsEventsResponse.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## get_analytics_status + +> models::AnalyticsStatus get_analytics_status() +Get analytics subsystem status + +Returns sizes of internal analytics buffers and queues. + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**models::AnalyticsStatus**](AnalyticsStatus.md) ### Authorization @@ -73,7 +194,7 @@ Name | Type | Description | Required | Notes ## retrieve_analytics_rule -> crate::models::AnalyticsRuleSchema retrieve_analytics_rule(rule_name) +> models::AnalyticsRule retrieve_analytics_rule(rule_name) Retrieves an analytics rule Retrieve the details of an analytics rule, given it's name @@ -87,7 +208,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::AnalyticsRuleSchema**](AnalyticsRuleSchema.md) +[**models::AnalyticsRule**](AnalyticsRule.md) ### Authorization @@ -103,18 +224,21 @@ Name | Type | Description | Required | Notes ## retrieve_analytics_rules -> crate::models::AnalyticsRulesRetrieveSchema retrieve_analytics_rules() -Retrieves all analytics rules +> Vec retrieve_analytics_rules(rule_tag) +Retrieve analytics rules -Retrieve the details of all analytics rules +Retrieve all analytics rules. Use the optional rule_tag filter to narrow down results. ### Parameters -This endpoint does not need any parameter. + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**rule_tag** | Option<**String**> | Filter rules by rule_tag | | ### Return type -[**crate::models::AnalyticsRulesRetrieveSchema**](AnalyticsRulesRetrieveSchema.md) +[**Vec**](AnalyticsRule.md) ### Authorization @@ -127,3 +251,34 @@ This endpoint does not need any parameter. [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +## upsert_analytics_rule + +> models::AnalyticsRule upsert_analytics_rule(rule_name, analytics_rule_update) +Upserts an analytics rule + +Upserts an analytics rule with the given name. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**rule_name** | **String** | The name of the analytics rule to upsert | [required] | +**analytics_rule_update** | [**AnalyticsRuleUpdate**](AnalyticsRuleUpdate.md) | The Analytics rule to be upserted | [required] | + +### Return type + +[**models::AnalyticsRule**](AnalyticsRule.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/typesense_codegen/docs/AnalyticsEvent.md b/typesense_codegen/docs/AnalyticsEvent.md new file mode 100644 index 0000000..9fdacec --- /dev/null +++ b/typesense_codegen/docs/AnalyticsEvent.md @@ -0,0 +1,13 @@ +# AnalyticsEvent + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | Name of the analytics rule this event corresponds to | +**event_type** | **String** | Type of event (e.g., click, conversion, query, visit) | +**data** | [**models::AnalyticsEventData**](AnalyticsEvent_data.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsEventCreateResponse.md b/typesense_codegen/docs/AnalyticsEventCreateResponse.md new file mode 100644 index 0000000..321be7b --- /dev/null +++ b/typesense_codegen/docs/AnalyticsEventCreateResponse.md @@ -0,0 +1,11 @@ +# AnalyticsEventCreateResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ok** | **bool** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsEventCreateSchema.md b/typesense_codegen/docs/AnalyticsEventCreateSchema.md new file mode 100644 index 0000000..97c07cc --- /dev/null +++ b/typesense_codegen/docs/AnalyticsEventCreateSchema.md @@ -0,0 +1,13 @@ +# AnalyticsEventCreateSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#type** | **String** | | +**name** | **String** | | +**data** | [**serde_json::Value**](.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsEventData.md b/typesense_codegen/docs/AnalyticsEventData.md new file mode 100644 index 0000000..22c8b02 --- /dev/null +++ b/typesense_codegen/docs/AnalyticsEventData.md @@ -0,0 +1,15 @@ +# AnalyticsEventData + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**user_id** | Option<**String**> | | [optional] +**doc_id** | Option<**String**> | | [optional] +**doc_ids** | Option<**Vec**> | | [optional] +**q** | Option<**String**> | | [optional] +**analytics_tag** | Option<**String**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsEventsResponse.md b/typesense_codegen/docs/AnalyticsEventsResponse.md new file mode 100644 index 0000000..ff6dbba --- /dev/null +++ b/typesense_codegen/docs/AnalyticsEventsResponse.md @@ -0,0 +1,11 @@ +# AnalyticsEventsResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**events** | [**Vec**](AnalyticsEventsResponse_events_inner.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsEventsResponseEventsInner.md b/typesense_codegen/docs/AnalyticsEventsResponseEventsInner.md new file mode 100644 index 0000000..1d65b60 --- /dev/null +++ b/typesense_codegen/docs/AnalyticsEventsResponseEventsInner.md @@ -0,0 +1,18 @@ +# AnalyticsEventsResponseEventsInner + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | Option<**String**> | | [optional] +**event_type** | Option<**String**> | | [optional] +**collection** | Option<**String**> | | [optional] +**timestamp** | Option<**i64**> | | [optional] +**user_id** | Option<**String**> | | [optional] +**doc_id** | Option<**String**> | | [optional] +**doc_ids** | Option<**Vec**> | | [optional] +**query** | Option<**String**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsRule.md b/typesense_codegen/docs/AnalyticsRule.md new file mode 100644 index 0000000..3e28b5c --- /dev/null +++ b/typesense_codegen/docs/AnalyticsRule.md @@ -0,0 +1,16 @@ +# AnalyticsRule + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | +**r#type** | **String** | | +**collection** | **String** | | +**event_type** | **String** | | +**rule_tag** | Option<**String**> | | [optional] +**params** | Option<[**models::AnalyticsRuleCreateParams**](AnalyticsRuleCreate_params.md)> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsRuleCreate.md b/typesense_codegen/docs/AnalyticsRuleCreate.md new file mode 100644 index 0000000..9fff80d --- /dev/null +++ b/typesense_codegen/docs/AnalyticsRuleCreate.md @@ -0,0 +1,16 @@ +# AnalyticsRuleCreate + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | +**r#type** | **String** | | +**collection** | **String** | | +**event_type** | **String** | | +**rule_tag** | Option<**String**> | | [optional] +**params** | Option<[**models::AnalyticsRuleCreateParams**](AnalyticsRuleCreate_params.md)> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsRuleCreateParams.md b/typesense_codegen/docs/AnalyticsRuleCreateParams.md new file mode 100644 index 0000000..eba962c --- /dev/null +++ b/typesense_codegen/docs/AnalyticsRuleCreateParams.md @@ -0,0 +1,17 @@ +# AnalyticsRuleCreateParams + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**destination_collection** | Option<**String**> | | [optional] +**limit** | Option<**i32**> | | [optional] +**capture_search_requests** | Option<**bool**> | | [optional] +**meta_fields** | Option<**Vec**> | | [optional] +**expand_query** | Option<**bool**> | | [optional] +**counter_field** | Option<**String**> | | [optional] +**weight** | Option<**i32**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsRuleDeleteResponse.md b/typesense_codegen/docs/AnalyticsRuleDeleteResponse.md new file mode 100644 index 0000000..bd7512f --- /dev/null +++ b/typesense_codegen/docs/AnalyticsRuleDeleteResponse.md @@ -0,0 +1,11 @@ +# AnalyticsRuleDeleteResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsRuleParameters.md b/typesense_codegen/docs/AnalyticsRuleParameters.md index 31b4ac4..9be9eeb 100644 --- a/typesense_codegen/docs/AnalyticsRuleParameters.md +++ b/typesense_codegen/docs/AnalyticsRuleParameters.md @@ -4,9 +4,10 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**source** | [**crate::models::AnalyticsRuleParametersSource**](AnalyticsRuleParameters_source.md) | | -**destination** | [**crate::models::AnalyticsRuleParametersDestination**](AnalyticsRuleParameters_destination.md) | | -**limit** | **i32** | | +**source** | [**models::AnalyticsRuleParametersSource**](AnalyticsRuleParametersSource.md) | | +**destination** | [**models::AnalyticsRuleParametersDestination**](AnalyticsRuleParametersDestination.md) | | +**limit** | Option<**i32**> | | [optional] +**expand_query** | Option<**bool**> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/AnalyticsRuleParametersDestination.md b/typesense_codegen/docs/AnalyticsRuleParametersDestination.md index 6bf99e5..e5efc9b 100644 --- a/typesense_codegen/docs/AnalyticsRuleParametersDestination.md +++ b/typesense_codegen/docs/AnalyticsRuleParametersDestination.md @@ -4,7 +4,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**collection** | Option<**String**> | | [optional] +**collection** | **String** | | +**counter_field** | Option<**String**> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/AnalyticsRuleParametersSource.md b/typesense_codegen/docs/AnalyticsRuleParametersSource.md index b6a042b..05ab04d 100644 --- a/typesense_codegen/docs/AnalyticsRuleParametersSource.md +++ b/typesense_codegen/docs/AnalyticsRuleParametersSource.md @@ -4,7 +4,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**collections** | Option<**Vec**> | | [optional] +**collections** | **Vec** | | +**events** | Option<[**Vec**](AnalyticsRuleParametersSource_events_inner.md)> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/AnalyticsRuleParametersSourceEventsInner.md b/typesense_codegen/docs/AnalyticsRuleParametersSourceEventsInner.md new file mode 100644 index 0000000..31264d2 --- /dev/null +++ b/typesense_codegen/docs/AnalyticsRuleParametersSourceEventsInner.md @@ -0,0 +1,13 @@ +# AnalyticsRuleParametersSourceEventsInner + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#type** | **String** | | +**weight** | **f32** | | +**name** | **String** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsRuleSchema.md b/typesense_codegen/docs/AnalyticsRuleSchema.md index 359d489..4afdcd4 100644 --- a/typesense_codegen/docs/AnalyticsRuleSchema.md +++ b/typesense_codegen/docs/AnalyticsRuleSchema.md @@ -4,9 +4,9 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**name** | **String** | | **r#type** | **String** | | -**params** | [**crate::models::AnalyticsRuleParameters**](AnalyticsRuleParameters.md) | | +**params** | [**models::AnalyticsRuleParameters**](AnalyticsRuleParameters.md) | | +**name** | **String** | | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/AnalyticsRuleUpdate.md b/typesense_codegen/docs/AnalyticsRuleUpdate.md new file mode 100644 index 0000000..7814cad --- /dev/null +++ b/typesense_codegen/docs/AnalyticsRuleUpdate.md @@ -0,0 +1,13 @@ +# AnalyticsRuleUpdate + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | Option<**String**> | | [optional] +**rule_tag** | Option<**String**> | | [optional] +**params** | Option<[**models::AnalyticsRuleCreateParams**](AnalyticsRuleCreate_params.md)> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsRuleUpsertSchema.md b/typesense_codegen/docs/AnalyticsRuleUpsertSchema.md new file mode 100644 index 0000000..fa21e43 --- /dev/null +++ b/typesense_codegen/docs/AnalyticsRuleUpsertSchema.md @@ -0,0 +1,12 @@ +# AnalyticsRuleUpsertSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#type** | **String** | | +**params** | [**models::AnalyticsRuleParameters**](AnalyticsRuleParameters.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsRulesRetrieveSchema.md b/typesense_codegen/docs/AnalyticsRulesRetrieveSchema.md index f20cf77..c310473 100644 --- a/typesense_codegen/docs/AnalyticsRulesRetrieveSchema.md +++ b/typesense_codegen/docs/AnalyticsRulesRetrieveSchema.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**rules** | Option<[**Vec**](AnalyticsRuleSchema.md)> | | [optional] +**rules** | Option<[**Vec**](AnalyticsRuleSchema.md)> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/AnalyticsStatus.md b/typesense_codegen/docs/AnalyticsStatus.md new file mode 100644 index 0000000..9bbc3c6 --- /dev/null +++ b/typesense_codegen/docs/AnalyticsStatus.md @@ -0,0 +1,17 @@ +# AnalyticsStatus + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**popular_prefix_queries** | Option<**i32**> | | [optional] +**nohits_prefix_queries** | Option<**i32**> | | [optional] +**log_prefix_queries** | Option<**i32**> | | [optional] +**query_log_events** | Option<**i32**> | | [optional] +**query_counter_events** | Option<**i32**> | | [optional] +**doc_log_events** | Option<**i32**> | | [optional] +**doc_counter_events** | Option<**i32**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/ApiKeyDeleteResponse.md b/typesense_codegen/docs/ApiKeyDeleteResponse.md new file mode 100644 index 0000000..8c38f9e --- /dev/null +++ b/typesense_codegen/docs/ApiKeyDeleteResponse.md @@ -0,0 +1,11 @@ +# ApiKeyDeleteResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **i64** | The id of the API key that was deleted | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/ApiKeysResponse.md b/typesense_codegen/docs/ApiKeysResponse.md index 1eac36f..c3e6c3d 100644 --- a/typesense_codegen/docs/ApiKeysResponse.md +++ b/typesense_codegen/docs/ApiKeysResponse.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**keys** | [**Vec**](ApiKey.md) | | +**keys** | [**Vec**](ApiKey.md) | | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/ApiStatsResponse.md b/typesense_codegen/docs/ApiStatsResponse.md new file mode 100644 index 0000000..c2569e7 --- /dev/null +++ b/typesense_codegen/docs/ApiStatsResponse.md @@ -0,0 +1,23 @@ +# ApiStatsResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**delete_latency_ms** | Option<**f64**> | | [optional] +**delete_requests_per_second** | Option<**f64**> | | [optional] +**import_latency_ms** | Option<**f64**> | | [optional] +**import_requests_per_second** | Option<**f64**> | | [optional] +**latency_ms** | Option<[**serde_json::Value**](.md)> | | [optional] +**overloaded_requests_per_second** | Option<**f64**> | | [optional] +**pending_write_batches** | Option<**f64**> | | [optional] +**requests_per_second** | Option<[**serde_json::Value**](.md)> | | [optional] +**search_latency_ms** | Option<**f64**> | | [optional] +**search_requests_per_second** | Option<**f64**> | | [optional] +**total_requests_per_second** | Option<**f64**> | | [optional] +**write_latency_ms** | Option<**f64**> | | [optional] +**write_requests_per_second** | Option<**f64**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/CollectionAliasesResponse.md b/typesense_codegen/docs/CollectionAliasesResponse.md index b8a0399..285708c 100644 --- a/typesense_codegen/docs/CollectionAliasesResponse.md +++ b/typesense_codegen/docs/CollectionAliasesResponse.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**aliases** | [**Vec**](CollectionAlias.md) | | +**aliases** | [**Vec**](CollectionAlias.md) | | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/CollectionResponse.md b/typesense_codegen/docs/CollectionResponse.md index aeb74a4..28b03da 100644 --- a/typesense_codegen/docs/CollectionResponse.md +++ b/typesense_codegen/docs/CollectionResponse.md @@ -5,11 +5,14 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **String** | Name of the collection | -**fields** | [**Vec**](Field.md) | A list of fields for querying, filtering and faceting | +**fields** | [**Vec**](Field.md) | A list of fields for querying, filtering and faceting | **default_sorting_field** | Option<**String**> | The name of an int32 / float field that determines the order in which the search results are ranked when a sort_by clause is not provided during searching. This field must indicate some kind of popularity. | [optional][default to ] -**token_separators** | Option<**Vec**> | List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. | [optional][default to []] +**token_separators** | Option<**Vec**> | List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. | [optional][default to []] +**synonym_sets** | Option<**Vec**> | List of synonym set names to associate with this collection | [optional] **enable_nested_fields** | Option<**bool**> | Enables experimental support at a collection level for nested object or object array fields. This field is only available if the Typesense server is version `0.24.0.rcn34` or later. | [optional][default to false] **symbols_to_index** | Option<**Vec**> | List of symbols or special characters to be indexed. | [optional][default to []] +**voice_query_model** | Option<[**models::VoiceQueryModelCollectionConfig**](VoiceQueryModelCollectionConfig.md)> | | [optional] +**metadata** | Option<[**serde_json::Value**](.md)> | Optional details about the collection, e.g., when it was created, who created it etc. | [optional] **num_documents** | **i64** | Number of documents in the collection | [readonly] **created_at** | **i64** | Timestamp of when the collection was created (Unix epoch in seconds) | [readonly] diff --git a/typesense_codegen/docs/CollectionSchema.md b/typesense_codegen/docs/CollectionSchema.md index 1f78262..bca7415 100644 --- a/typesense_codegen/docs/CollectionSchema.md +++ b/typesense_codegen/docs/CollectionSchema.md @@ -5,11 +5,14 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **String** | Name of the collection | -**fields** | [**Vec**](Field.md) | A list of fields for querying, filtering and faceting | +**fields** | [**Vec**](Field.md) | A list of fields for querying, filtering and faceting | **default_sorting_field** | Option<**String**> | The name of an int32 / float field that determines the order in which the search results are ranked when a sort_by clause is not provided during searching. This field must indicate some kind of popularity. | [optional][default to ] -**token_separators** | Option<**Vec**> | List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. | [optional][default to []] +**token_separators** | Option<**Vec**> | List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. | [optional][default to []] +**synonym_sets** | Option<**Vec**> | List of synonym set names to associate with this collection | [optional] **enable_nested_fields** | Option<**bool**> | Enables experimental support at a collection level for nested object or object array fields. This field is only available if the Typesense server is version `0.24.0.rcn34` or later. | [optional][default to false] **symbols_to_index** | Option<**Vec**> | List of symbols or special characters to be indexed. | [optional][default to []] +**voice_query_model** | Option<[**models::VoiceQueryModelCollectionConfig**](VoiceQueryModelCollectionConfig.md)> | | [optional] +**metadata** | Option<[**serde_json::Value**](.md)> | Optional details about the collection, e.g., when it was created, who created it etc. | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/CollectionUpdateSchema.md b/typesense_codegen/docs/CollectionUpdateSchema.md index d40d070..6167d13 100644 --- a/typesense_codegen/docs/CollectionUpdateSchema.md +++ b/typesense_codegen/docs/CollectionUpdateSchema.md @@ -4,7 +4,9 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**fields** | [**Vec**](Field.md) | A list of fields for querying, filtering and faceting | +**fields** | [**Vec**](Field.md) | A list of fields for querying, filtering and faceting | +**synonym_sets** | Option<**Vec**> | List of synonym set names to associate with this collection | [optional] +**metadata** | Option<[**serde_json::Value**](.md)> | Optional details about the collection, e.g., when it was created, who created it etc. | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/CollectionsApi.md b/typesense_codegen/docs/CollectionsApi.md index 14cb336..4dc1cdf 100644 --- a/typesense_codegen/docs/CollectionsApi.md +++ b/typesense_codegen/docs/CollectionsApi.md @@ -1,6 +1,6 @@ # \CollectionsApi -All URIs are relative to *http://localhost* +All URIs are relative to *http://localhost:8108* Method | HTTP request | Description ------------- | ------------- | ------------- @@ -18,7 +18,7 @@ Method | HTTP request | Description ## create_collection -> crate::models::CollectionResponse create_collection(collection_schema) +> models::CollectionResponse create_collection(collection_schema) Create a new collection When a collection is created, we give it a name and describe the fields that will be indexed from the documents added to the collection. @@ -32,7 +32,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::CollectionResponse**](CollectionResponse.md) +[**models::CollectionResponse**](CollectionResponse.md) ### Authorization @@ -48,7 +48,7 @@ Name | Type | Description | Required | Notes ## delete_alias -> crate::models::CollectionAlias delete_alias(alias_name) +> models::CollectionAlias delete_alias(alias_name) Delete an alias ### Parameters @@ -60,7 +60,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::CollectionAlias**](CollectionAlias.md) +[**models::CollectionAlias**](CollectionAlias.md) ### Authorization @@ -76,7 +76,7 @@ Name | Type | Description | Required | Notes ## delete_collection -> crate::models::CollectionResponse delete_collection(collection_name) +> models::CollectionResponse delete_collection(collection_name) Delete a collection Permanently drops a collection. This action cannot be undone. For large collections, this might have an impact on read latencies. @@ -90,7 +90,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::CollectionResponse**](CollectionResponse.md) +[**models::CollectionResponse**](CollectionResponse.md) ### Authorization @@ -106,7 +106,7 @@ Name | Type | Description | Required | Notes ## get_alias -> crate::models::CollectionAlias get_alias(alias_name) +> models::CollectionAlias get_alias(alias_name) Retrieve an alias Find out which collection an alias points to by fetching it @@ -120,7 +120,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::CollectionAlias**](CollectionAlias.md) +[**models::CollectionAlias**](CollectionAlias.md) ### Authorization @@ -136,7 +136,7 @@ Name | Type | Description | Required | Notes ## get_aliases -> crate::models::CollectionAliasesResponse get_aliases() +> models::CollectionAliasesResponse get_aliases() List all aliases List all aliases and the corresponding collections that they map to. @@ -147,7 +147,7 @@ This endpoint does not need any parameter. ### Return type -[**crate::models::CollectionAliasesResponse**](CollectionAliasesResponse.md) +[**models::CollectionAliasesResponse**](CollectionAliasesResponse.md) ### Authorization @@ -163,7 +163,7 @@ This endpoint does not need any parameter. ## get_collection -> crate::models::CollectionResponse get_collection(collection_name) +> models::CollectionResponse get_collection(collection_name) Retrieve a single collection Retrieve the details of a collection, given its name. @@ -177,7 +177,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::CollectionResponse**](CollectionResponse.md) +[**models::CollectionResponse**](CollectionResponse.md) ### Authorization @@ -193,18 +193,23 @@ Name | Type | Description | Required | Notes ## get_collections -> Vec get_collections() +> Vec get_collections(exclude_fields, limit, offset) List all collections Returns a summary of all your collections. The collections are returned sorted by creation date, with the most recent collections appearing first. ### Parameters -This endpoint does not need any parameter. + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**exclude_fields** | Option<**String**> | | | +**limit** | Option<**i32**> | | | +**offset** | Option<**i32**> | | | ### Return type -[**Vec**](CollectionResponse.md) +[**Vec**](CollectionResponse.md) ### Authorization @@ -220,7 +225,7 @@ This endpoint does not need any parameter. ## update_collection -> crate::models::CollectionUpdateSchema update_collection(collection_name, collection_update_schema) +> models::CollectionUpdateSchema update_collection(collection_name, collection_update_schema) Update a collection Update a collection's schema to modify the fields and their types. @@ -235,7 +240,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::CollectionUpdateSchema**](CollectionUpdateSchema.md) +[**models::CollectionUpdateSchema**](CollectionUpdateSchema.md) ### Authorization @@ -251,7 +256,7 @@ Name | Type | Description | Required | Notes ## upsert_alias -> crate::models::CollectionAlias upsert_alias(alias_name, collection_alias_schema) +> models::CollectionAlias upsert_alias(alias_name, collection_alias_schema) Create or update a collection alias Create or update a collection alias. An alias is a virtual collection name that points to a real collection. If you're familiar with symbolic links on Linux, it's very similar to that. Aliases are useful when you want to reindex your data in the background on a new collection and switch your application to it without any changes to your code. @@ -266,7 +271,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::CollectionAlias**](CollectionAlias.md) +[**models::CollectionAlias**](CollectionAlias.md) ### Authorization diff --git a/typesense_codegen/docs/ConversationModelCreateSchema.md b/typesense_codegen/docs/ConversationModelCreateSchema.md new file mode 100644 index 0000000..a8d70c5 --- /dev/null +++ b/typesense_codegen/docs/ConversationModelCreateSchema.md @@ -0,0 +1,19 @@ +# ConversationModelCreateSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | Option<**String**> | An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. | [optional] +**model_name** | **String** | Name of the LLM model offered by OpenAI, Cloudflare or vLLM | +**api_key** | Option<**String**> | The LLM service's API Key | [optional] +**history_collection** | **String** | Typesense collection that stores the historical conversations | +**account_id** | Option<**String**> | LLM service's account ID (only applicable for Cloudflare) | [optional] +**system_prompt** | Option<**String**> | The system prompt that contains special instructions to the LLM | [optional] +**ttl** | Option<**i32**> | Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) | [optional] +**max_bytes** | **i32** | The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. | +**vllm_url** | Option<**String**> | URL of vLLM service | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/ConversationModelSchema.md b/typesense_codegen/docs/ConversationModelSchema.md new file mode 100644 index 0000000..f9fe0d2 --- /dev/null +++ b/typesense_codegen/docs/ConversationModelSchema.md @@ -0,0 +1,19 @@ +# ConversationModelSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **String** | An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. | +**model_name** | **String** | Name of the LLM model offered by OpenAI, Cloudflare or vLLM | +**api_key** | Option<**String**> | The LLM service's API Key | [optional] +**history_collection** | **String** | Typesense collection that stores the historical conversations | +**account_id** | Option<**String**> | LLM service's account ID (only applicable for Cloudflare) | [optional] +**system_prompt** | Option<**String**> | The system prompt that contains special instructions to the LLM | [optional] +**ttl** | Option<**i32**> | Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) | [optional] +**max_bytes** | **i32** | The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. | +**vllm_url** | Option<**String**> | URL of vLLM service | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/ConversationModelUpdateSchema.md b/typesense_codegen/docs/ConversationModelUpdateSchema.md new file mode 100644 index 0000000..a9471ce --- /dev/null +++ b/typesense_codegen/docs/ConversationModelUpdateSchema.md @@ -0,0 +1,19 @@ +# ConversationModelUpdateSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | Option<**String**> | An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. | [optional] +**model_name** | Option<**String**> | Name of the LLM model offered by OpenAI, Cloudflare or vLLM | [optional] +**api_key** | Option<**String**> | The LLM service's API Key | [optional] +**history_collection** | Option<**String**> | Typesense collection that stores the historical conversations | [optional] +**account_id** | Option<**String**> | LLM service's account ID (only applicable for Cloudflare) | [optional] +**system_prompt** | Option<**String**> | The system prompt that contains special instructions to the LLM | [optional] +**ttl** | Option<**i32**> | Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) | [optional] +**max_bytes** | Option<**i32**> | The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. | [optional] +**vllm_url** | Option<**String**> | URL of vLLM service | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/ConversationsApi.md b/typesense_codegen/docs/ConversationsApi.md new file mode 100644 index 0000000..4d4d581 --- /dev/null +++ b/typesense_codegen/docs/ConversationsApi.md @@ -0,0 +1,161 @@ +# \ConversationsApi + +All URIs are relative to *http://localhost:8108* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**create_conversation_model**](ConversationsApi.md#create_conversation_model) | **POST** /conversations/models | Create a conversation model +[**delete_conversation_model**](ConversationsApi.md#delete_conversation_model) | **DELETE** /conversations/models/{modelId} | Delete a conversation model +[**retrieve_all_conversation_models**](ConversationsApi.md#retrieve_all_conversation_models) | **GET** /conversations/models | List all conversation models +[**retrieve_conversation_model**](ConversationsApi.md#retrieve_conversation_model) | **GET** /conversations/models/{modelId} | Retrieve a conversation model +[**update_conversation_model**](ConversationsApi.md#update_conversation_model) | **PUT** /conversations/models/{modelId} | Update a conversation model + + + +## create_conversation_model + +> models::ConversationModelSchema create_conversation_model(conversation_model_create_schema) +Create a conversation model + +Create a Conversation Model + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**conversation_model_create_schema** | [**ConversationModelCreateSchema**](ConversationModelCreateSchema.md) | | [required] | + +### Return type + +[**models::ConversationModelSchema**](ConversationModelSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## delete_conversation_model + +> models::ConversationModelSchema delete_conversation_model(model_id) +Delete a conversation model + +Delete a conversation model + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**model_id** | **String** | The id of the conversation model to delete | [required] | + +### Return type + +[**models::ConversationModelSchema**](ConversationModelSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_all_conversation_models + +> Vec retrieve_all_conversation_models() +List all conversation models + +Retrieve all conversation models + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**Vec**](ConversationModelSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_conversation_model + +> models::ConversationModelSchema retrieve_conversation_model(model_id) +Retrieve a conversation model + +Retrieve a conversation model + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**model_id** | **String** | The id of the conversation model to retrieve | [required] | + +### Return type + +[**models::ConversationModelSchema**](ConversationModelSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## update_conversation_model + +> models::ConversationModelSchema update_conversation_model(model_id, conversation_model_update_schema) +Update a conversation model + +Update a conversation model + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**model_id** | **String** | The id of the conversation model to update | [required] | +**conversation_model_update_schema** | [**ConversationModelUpdateSchema**](ConversationModelUpdateSchema.md) | | [required] | + +### Return type + +[**models::ConversationModelSchema**](ConversationModelSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/typesense_codegen/docs/CreateAnalyticsRule200Response.md b/typesense_codegen/docs/CreateAnalyticsRule200Response.md new file mode 100644 index 0000000..ed4affd --- /dev/null +++ b/typesense_codegen/docs/CreateAnalyticsRule200Response.md @@ -0,0 +1,12 @@ +# CreateAnalyticsRule200Response + +## Enum Variants + +| Name | Description | +|---- | -----| +| AnalyticsRule | | +| Vec | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/CreateAnalyticsRule200ResponseOneOfInner.md b/typesense_codegen/docs/CreateAnalyticsRule200ResponseOneOfInner.md new file mode 100644 index 0000000..d2f71ed --- /dev/null +++ b/typesense_codegen/docs/CreateAnalyticsRule200ResponseOneOfInner.md @@ -0,0 +1,17 @@ +# CreateAnalyticsRule200ResponseOneOfInner + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | +**r#type** | **String** | | +**collection** | **String** | | +**event_type** | **String** | | +**rule_tag** | Option<**String**> | | [optional] +**params** | Option<[**models::AnalyticsRuleCreateParams**](AnalyticsRuleCreate_params.md)> | | [optional] +**error** | Option<**String**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/CreateAnalyticsRule200ResponseOneOfInnerAnyOf.md b/typesense_codegen/docs/CreateAnalyticsRule200ResponseOneOfInnerAnyOf.md new file mode 100644 index 0000000..030113b --- /dev/null +++ b/typesense_codegen/docs/CreateAnalyticsRule200ResponseOneOfInnerAnyOf.md @@ -0,0 +1,11 @@ +# CreateAnalyticsRule200ResponseOneOfInnerAnyOf + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**error** | Option<**String**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/CreateAnalyticsRuleRequest.md b/typesense_codegen/docs/CreateAnalyticsRuleRequest.md new file mode 100644 index 0000000..89c4bdc --- /dev/null +++ b/typesense_codegen/docs/CreateAnalyticsRuleRequest.md @@ -0,0 +1,12 @@ +# CreateAnalyticsRuleRequest + +## Enum Variants + +| Name | Description | +|---- | -----| +| AnalyticsRuleCreate | | +| Vec | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/PromoteApi.md b/typesense_codegen/docs/CurationApi.md similarity index 70% rename from typesense_codegen/docs/PromoteApi.md rename to typesense_codegen/docs/CurationApi.md index 948b093..bb8afc5 100644 --- a/typesense_codegen/docs/PromoteApi.md +++ b/typesense_codegen/docs/CurationApi.md @@ -1,18 +1,18 @@ -# \PromoteApi +# \CurationApi -All URIs are relative to *http://localhost* +All URIs are relative to *http://localhost:8108* Method | HTTP request | Description ------------- | ------------- | ------------- -[**delete_search_override**](PromoteApi.md#delete_search_override) | **DELETE** /collections/{collectionName}/overrides/{overrideId} | Delete an override associated with a collection -[**get_search_overrides**](PromoteApi.md#get_search_overrides) | **GET** /collections/{collectionName}/overrides | List all collection overrides -[**upsert_search_override**](PromoteApi.md#upsert_search_override) | **PUT** /collections/{collectionName}/overrides/{overrideId} | Create or update an override to promote certain documents over others +[**delete_search_override**](CurationApi.md#delete_search_override) | **DELETE** /collections/{collectionName}/overrides/{overrideId} | Delete an override associated with a collection +[**get_search_overrides**](CurationApi.md#get_search_overrides) | **GET** /collections/{collectionName}/overrides | List all collection overrides +[**upsert_search_override**](CurationApi.md#upsert_search_override) | **PUT** /collections/{collectionName}/overrides/{overrideId} | Create or update an override to promote certain documents over others ## delete_search_override -> crate::models::SearchOverride delete_search_override(collection_name, override_id) +> models::SearchOverrideDeleteResponse delete_search_override(collection_name, override_id) Delete an override associated with a collection ### Parameters @@ -25,7 +25,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::SearchOverride**](SearchOverride.md) +[**models::SearchOverrideDeleteResponse**](SearchOverrideDeleteResponse.md) ### Authorization @@ -41,7 +41,7 @@ Name | Type | Description | Required | Notes ## get_search_overrides -> crate::models::SearchOverridesResponse get_search_overrides(collection_name) +> models::SearchOverridesResponse get_search_overrides(collection_name) List all collection overrides ### Parameters @@ -53,7 +53,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::SearchOverridesResponse**](SearchOverridesResponse.md) +[**models::SearchOverridesResponse**](SearchOverridesResponse.md) ### Authorization @@ -69,7 +69,7 @@ Name | Type | Description | Required | Notes ## upsert_search_override -> crate::models::SearchOverride upsert_search_override(collection_name, override_id, search_override_schema) +> models::SearchOverride upsert_search_override(collection_name, override_id, search_override_schema) Create or update an override to promote certain documents over others Create or update an override to promote certain documents over others. Using overrides, you can include or exclude specific documents for a given query. @@ -85,7 +85,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::SearchOverride**](SearchOverride.md) +[**models::SearchOverride**](SearchOverride.md) ### Authorization diff --git a/typesense_codegen/docs/DebugApi.md b/typesense_codegen/docs/DebugApi.md index a1f8c0f..58e8833 100644 --- a/typesense_codegen/docs/DebugApi.md +++ b/typesense_codegen/docs/DebugApi.md @@ -1,6 +1,6 @@ # \DebugApi -All URIs are relative to *http://localhost* +All URIs are relative to *http://localhost:8108* Method | HTTP request | Description ------------- | ------------- | ------------- @@ -10,7 +10,7 @@ Method | HTTP request | Description ## debug -> crate::models::Debug200Response debug() +> models::Debug200Response debug() Print debugging information Print debugging information @@ -21,7 +21,7 @@ This endpoint does not need any parameter. ### Return type -[**crate::models::Debug200Response**](debug_200_response.md) +[**models::Debug200Response**](debug_200_response.md) ### Authorization diff --git a/typesense_codegen/docs/DeleteDocumentsDeleteDocumentsParametersParameter.md b/typesense_codegen/docs/DeleteDocumentsDeleteDocumentsParametersParameter.md index 433c2be..ca66c4a 100644 --- a/typesense_codegen/docs/DeleteDocumentsDeleteDocumentsParametersParameter.md +++ b/typesense_codegen/docs/DeleteDocumentsDeleteDocumentsParametersParameter.md @@ -4,8 +4,10 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**filter_by** | Option<**String**> | | [optional] +**filter_by** | **String** | | **batch_size** | Option<**i32**> | Batch size parameter controls the number of documents that should be deleted at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. | [optional] +**ignore_not_found** | Option<**bool**> | | [optional] +**truncate** | Option<**bool**> | When true, removes all documents from the collection while preserving the collection and its schema. | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/DeleteDocumentsParameters.md b/typesense_codegen/docs/DeleteDocumentsParameters.md new file mode 100644 index 0000000..f960189 --- /dev/null +++ b/typesense_codegen/docs/DeleteDocumentsParameters.md @@ -0,0 +1,14 @@ +# DeleteDocumentsParameters + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**filter_by** | **String** | | +**batch_size** | Option<**i32**> | Batch size parameter controls the number of documents that should be deleted at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. | [optional] +**ignore_not_found** | Option<**bool**> | | [optional] +**truncate** | Option<**bool**> | When true, removes all documents from the collection while preserving the collection and its schema. | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/DeleteStopwordsSet200Response.md b/typesense_codegen/docs/DeleteStopwordsSet200Response.md new file mode 100644 index 0000000..919a663 --- /dev/null +++ b/typesense_codegen/docs/DeleteStopwordsSet200Response.md @@ -0,0 +1,11 @@ +# DeleteStopwordsSet200Response + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **String** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/DirtyValues.md b/typesense_codegen/docs/DirtyValues.md new file mode 100644 index 0000000..50492e1 --- /dev/null +++ b/typesense_codegen/docs/DirtyValues.md @@ -0,0 +1,15 @@ +# DirtyValues + +## Enum Variants + +| Name | Value | +|---- | -----| +| CoerceOrReject | coerce_or_reject | +| CoerceOrDrop | coerce_or_drop | +| Drop | drop | +| Reject | reject | + + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/DocumentIndexParameters.md b/typesense_codegen/docs/DocumentIndexParameters.md new file mode 100644 index 0000000..08f8e95 --- /dev/null +++ b/typesense_codegen/docs/DocumentIndexParameters.md @@ -0,0 +1,11 @@ +# DocumentIndexParameters + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**dirty_values** | Option<[**models::DirtyValues**](DirtyValues.md)> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/DocumentsApi.md b/typesense_codegen/docs/DocumentsApi.md index eebec19..9b5858f 100644 --- a/typesense_codegen/docs/DocumentsApi.md +++ b/typesense_codegen/docs/DocumentsApi.md @@ -1,19 +1,16 @@ # \DocumentsApi -All URIs are relative to *http://localhost* +All URIs are relative to *http://localhost:8108* Method | HTTP request | Description ------------- | ------------- | ------------- [**delete_document**](DocumentsApi.md#delete_document) | **DELETE** /collections/{collectionName}/documents/{documentId} | Delete a document [**delete_documents**](DocumentsApi.md#delete_documents) | **DELETE** /collections/{collectionName}/documents | Delete a bunch of documents [**delete_search_override**](DocumentsApi.md#delete_search_override) | **DELETE** /collections/{collectionName}/overrides/{overrideId} | Delete an override associated with a collection -[**delete_search_synonym**](DocumentsApi.md#delete_search_synonym) | **DELETE** /collections/{collectionName}/synonyms/{synonymId} | Delete a synonym associated with a collection [**export_documents**](DocumentsApi.md#export_documents) | **GET** /collections/{collectionName}/documents/export | Export all documents in a collection -[**get_document**](DocumentsApi.md#get_document) | **GET** /collections/{collectionName}/documents/{documentId} | Retreive a document +[**get_document**](DocumentsApi.md#get_document) | **GET** /collections/{collectionName}/documents/{documentId} | Retrieve a document [**get_search_override**](DocumentsApi.md#get_search_override) | **GET** /collections/{collectionName}/overrides/{overrideId} | Retrieve a single search override [**get_search_overrides**](DocumentsApi.md#get_search_overrides) | **GET** /collections/{collectionName}/overrides | List all collection overrides -[**get_search_synonym**](DocumentsApi.md#get_search_synonym) | **GET** /collections/{collectionName}/synonyms/{synonymId} | Retrieve a single search synonym -[**get_search_synonyms**](DocumentsApi.md#get_search_synonyms) | **GET** /collections/{collectionName}/synonyms | List all collection synonyms [**import_documents**](DocumentsApi.md#import_documents) | **POST** /collections/{collectionName}/documents/import | Import documents into a collection [**index_document**](DocumentsApi.md#index_document) | **POST** /collections/{collectionName}/documents | Index a document [**multi_search**](DocumentsApi.md#multi_search) | **POST** /multi_search | send multiple search requests in a single HTTP request @@ -21,7 +18,6 @@ Method | HTTP request | Description [**update_document**](DocumentsApi.md#update_document) | **PATCH** /collections/{collectionName}/documents/{documentId} | Update a document [**update_documents**](DocumentsApi.md#update_documents) | **PATCH** /collections/{collectionName}/documents | Update documents with conditional query [**upsert_search_override**](DocumentsApi.md#upsert_search_override) | **PUT** /collections/{collectionName}/overrides/{overrideId} | Create or update an override to promote certain documents over others -[**upsert_search_synonym**](DocumentsApi.md#upsert_search_synonym) | **PUT** /collections/{collectionName}/synonyms/{synonymId} | Create or update a synonym @@ -58,7 +54,7 @@ Name | Type | Description | Required | Notes ## delete_documents -> crate::models::DeleteDocuments200Response delete_documents(collection_name, delete_documents_parameters) +> models::DeleteDocuments200Response delete_documents(collection_name, filter_by, batch_size, ignore_not_found, truncate) Delete a bunch of documents Delete a bunch of documents that match a specific filter condition. Use the `batch_size` parameter to control the number of documents that should deleted at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. @@ -69,11 +65,14 @@ Delete a bunch of documents that match a specific filter condition. Use the `bat Name | Type | Description | Required | Notes ------------- | ------------- | ------------- | ------------- | ------------- **collection_name** | **String** | The name of the collection to delete documents from | [required] | -**delete_documents_parameters** | Option<[**DeleteDocumentsDeleteDocumentsParametersParameter**](.md)> | | | +**filter_by** | Option<**String**> | | | +**batch_size** | Option<**i32**> | | | +**ignore_not_found** | Option<**bool**> | | | +**truncate** | Option<**bool**> | | | ### Return type -[**crate::models::DeleteDocuments200Response**](deleteDocuments_200_response.md) +[**models::DeleteDocuments200Response**](deleteDocuments_200_response.md) ### Authorization @@ -89,7 +88,7 @@ Name | Type | Description | Required | Notes ## delete_search_override -> crate::models::SearchOverride delete_search_override(collection_name, override_id) +> models::SearchOverrideDeleteResponse delete_search_override(collection_name, override_id) Delete an override associated with a collection ### Parameters @@ -102,36 +101,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::SearchOverride**](SearchOverride.md) - -### Authorization - -[api_key_header](../README.md#api_key_header) - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - - -## delete_search_synonym - -> crate::models::SearchSynonym delete_search_synonym(collection_name, synonym_id) -Delete a synonym associated with a collection - -### Parameters - - -Name | Type | Description | Required | Notes -------------- | ------------- | ------------- | ------------- | ------------- -**collection_name** | **String** | The name of the collection | [required] | -**synonym_id** | **String** | The ID of the search synonym to delete | [required] | - -### Return type - -[**crate::models::SearchSynonym**](SearchSynonym.md) +[**models::SearchOverrideDeleteResponse**](SearchOverrideDeleteResponse.md) ### Authorization @@ -147,7 +117,7 @@ Name | Type | Description | Required | Notes ## export_documents -> String export_documents(collection_name, export_documents_parameters) +> String export_documents(collection_name, filter_by, include_fields, exclude_fields) Export all documents in a collection Export all documents in a collection in JSON lines format. @@ -158,7 +128,9 @@ Export all documents in a collection in JSON lines format. Name | Type | Description | Required | Notes ------------- | ------------- | ------------- | ------------- | ------------- **collection_name** | **String** | The name of the collection | [required] | -**export_documents_parameters** | Option<[**ExportDocumentsExportDocumentsParametersParameter**](.md)> | | | +**filter_by** | Option<**String**> | | | +**include_fields** | Option<**String**> | | | +**exclude_fields** | Option<**String**> | | | ### Return type @@ -179,7 +151,7 @@ Name | Type | Description | Required | Notes ## get_document > serde_json::Value get_document(collection_name, document_id) -Retreive a document +Retrieve a document Fetch an individual document from a collection by using its ID. @@ -209,7 +181,7 @@ Name | Type | Description | Required | Notes ## get_search_override -> crate::models::SearchOverride get_search_override(collection_name, override_id) +> models::SearchOverride get_search_override(collection_name, override_id) Retrieve a single search override Retrieve the details of a search override, given its id. @@ -224,7 +196,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::SearchOverride**](SearchOverride.md) +[**models::SearchOverride**](SearchOverride.md) ### Authorization @@ -240,7 +212,7 @@ Name | Type | Description | Required | Notes ## get_search_overrides -> crate::models::SearchOverridesResponse get_search_overrides(collection_name) +> models::SearchOverridesResponse get_search_overrides(collection_name) List all collection overrides ### Parameters @@ -252,66 +224,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::SearchOverridesResponse**](SearchOverridesResponse.md) - -### Authorization - -[api_key_header](../README.md#api_key_header) - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - - -## get_search_synonym - -> crate::models::SearchSynonym get_search_synonym(collection_name, synonym_id) -Retrieve a single search synonym - -Retrieve the details of a search synonym, given its id. - -### Parameters - - -Name | Type | Description | Required | Notes -------------- | ------------- | ------------- | ------------- | ------------- -**collection_name** | **String** | The name of the collection | [required] | -**synonym_id** | **String** | The id of the search synonym | [required] | - -### Return type - -[**crate::models::SearchSynonym**](SearchSynonym.md) - -### Authorization - -[api_key_header](../README.md#api_key_header) - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - - -## get_search_synonyms - -> crate::models::SearchSynonymsResponse get_search_synonyms(collection_name) -List all collection synonyms - -### Parameters - - -Name | Type | Description | Required | Notes -------------- | ------------- | ------------- | ------------- | ------------- -**collection_name** | **String** | The name of the collection | [required] | - -### Return type - -[**crate::models::SearchSynonymsResponse**](SearchSynonymsResponse.md) +[**models::SearchOverridesResponse**](SearchOverridesResponse.md) ### Authorization @@ -327,7 +240,7 @@ Name | Type | Description | Required | Notes ## import_documents -> String import_documents(collection_name, body, import_documents_parameters) +> String import_documents(collection_name, body, batch_size, return_id, remote_embedding_batch_size, return_doc, action, dirty_values) Import documents into a collection The documents to be imported must be formatted in a newline delimited JSON structure. You can feed the output file from a Typesense export operation directly as import. @@ -339,7 +252,12 @@ Name | Type | Description | Required | Notes ------------- | ------------- | ------------- | ------------- | ------------- **collection_name** | **String** | The name of the collection | [required] | **body** | **String** | The json array of documents or the JSONL file to import | [required] | -**import_documents_parameters** | Option<[**ImportDocumentsImportDocumentsParametersParameter**](.md)> | | | +**batch_size** | Option<**i32**> | | | +**return_id** | Option<**bool**> | | | +**remote_embedding_batch_size** | Option<**i32**> | | | +**return_doc** | Option<**bool**> | | | +**action** | Option<[**IndexAction**](.md)> | | | +**dirty_values** | Option<[**DirtyValues**](.md)> | | | ### Return type @@ -359,7 +277,7 @@ Name | Type | Description | Required | Notes ## index_document -> serde_json::Value index_document(collection_name, body, action) +> serde_json::Value index_document(collection_name, body, action, dirty_values) Index a document A document to be indexed in a given collection must conform to the schema of the collection. @@ -371,7 +289,8 @@ Name | Type | Description | Required | Notes ------------- | ------------- | ------------- | ------------- | ------------- **collection_name** | **String** | The name of the collection to add the document to | [required] | **body** | **serde_json::Value** | The document object to be indexed | [required] | -**action** | Option<**String**> | Additional action to perform | | +**action** | Option<**IndexAction**> | Additional action to perform | | +**dirty_values** | Option<[**DirtyValues**](.md)> | Dealing with Dirty Data | | ### Return type @@ -391,7 +310,7 @@ Name | Type | Description | Required | Notes ## multi_search -> crate::models::MultiSearchResult multi_search(multi_search_parameters, multi_search_searches_parameter) +> models::MultiSearchResult multi_search(q, query_by, query_by_weights, text_match_type, prefix, infix, max_extra_prefix, max_extra_suffix, filter_by, sort_by, facet_by, max_facet_values, facet_query, num_typos, page, per_page, limit, offset, group_by, group_limit, group_missing_values, include_fields, exclude_fields, highlight_full_fields, highlight_affix_num_tokens, highlight_start_tag, highlight_end_tag, snippet_threshold, drop_tokens_threshold, drop_tokens_mode, typo_tokens_threshold, enable_typos_for_alpha_numerical_tokens, filter_curated_hits, enable_synonyms, enable_analytics, synonym_prefix, synonym_num_typos, pinned_hits, hidden_hits, override_tags, highlight_fields, pre_segmented_query, preset, enable_overrides, prioritize_exact_match, prioritize_token_position, prioritize_num_matching_fields, enable_typos_for_numerical_tokens, exhaustive_search, search_cutoff_ms, use_cache, cache_ttl, min_len_1typo, min_len_2typo, vector_query, remote_embedding_timeout_ms, remote_embedding_num_tries, facet_strategy, stopwords, facet_return_parent, voice_query, conversation, conversation_model_id, conversation_id, multi_search_searches_parameter) send multiple search requests in a single HTTP request This is especially useful to avoid round-trip network latencies incurred otherwise if each of these requests are sent in separate HTTP requests. You can also use this feature to do a federated search across multiple collections in a single HTTP request. @@ -401,12 +320,75 @@ This is especially useful to avoid round-trip network latencies incurred otherwi Name | Type | Description | Required | Notes ------------- | ------------- | ------------- | ------------- | ------------- -**multi_search_parameters** | [**MultiSearchParameters**](.md) | | [required] | +**q** | Option<**String**> | | | +**query_by** | Option<**String**> | | | +**query_by_weights** | Option<**String**> | | | +**text_match_type** | Option<**String**> | | | +**prefix** | Option<**String**> | | | +**infix** | Option<**String**> | | | +**max_extra_prefix** | Option<**i32**> | | | +**max_extra_suffix** | Option<**i32**> | | | +**filter_by** | Option<**String**> | | | +**sort_by** | Option<**String**> | | | +**facet_by** | Option<**String**> | | | +**max_facet_values** | Option<**i32**> | | | +**facet_query** | Option<**String**> | | | +**num_typos** | Option<**String**> | | | +**page** | Option<**i32**> | | | +**per_page** | Option<**i32**> | | | +**limit** | Option<**i32**> | | | +**offset** | Option<**i32**> | | | +**group_by** | Option<**String**> | | | +**group_limit** | Option<**i32**> | | | +**group_missing_values** | Option<**bool**> | | | +**include_fields** | Option<**String**> | | | +**exclude_fields** | Option<**String**> | | | +**highlight_full_fields** | Option<**String**> | | | +**highlight_affix_num_tokens** | Option<**i32**> | | | +**highlight_start_tag** | Option<**String**> | | | +**highlight_end_tag** | Option<**String**> | | | +**snippet_threshold** | Option<**i32**> | | | +**drop_tokens_threshold** | Option<**i32**> | | | +**drop_tokens_mode** | Option<[**DropTokensMode**](.md)> | | | +**typo_tokens_threshold** | Option<**i32**> | | | +**enable_typos_for_alpha_numerical_tokens** | Option<**bool**> | | | +**filter_curated_hits** | Option<**bool**> | | | +**enable_synonyms** | Option<**bool**> | | | +**enable_analytics** | Option<**bool**> | | |[default to true] +**synonym_prefix** | Option<**bool**> | | | +**synonym_num_typos** | Option<**i32**> | | | +**pinned_hits** | Option<**String**> | | | +**hidden_hits** | Option<**String**> | | | +**override_tags** | Option<**String**> | | | +**highlight_fields** | Option<**String**> | | | +**pre_segmented_query** | Option<**bool**> | | |[default to false] +**preset** | Option<**String**> | | | +**enable_overrides** | Option<**bool**> | | |[default to false] +**prioritize_exact_match** | Option<**bool**> | | |[default to true] +**prioritize_token_position** | Option<**bool**> | | |[default to false] +**prioritize_num_matching_fields** | Option<**bool**> | | |[default to true] +**enable_typos_for_numerical_tokens** | Option<**bool**> | | |[default to true] +**exhaustive_search** | Option<**bool**> | | | +**search_cutoff_ms** | Option<**i32**> | | | +**use_cache** | Option<**bool**> | | | +**cache_ttl** | Option<**i32**> | | | +**min_len_1typo** | Option<**i32**> | | | +**min_len_2typo** | Option<**i32**> | | | +**vector_query** | Option<**String**> | | | +**remote_embedding_timeout_ms** | Option<**i32**> | | | +**remote_embedding_num_tries** | Option<**i32**> | | | +**facet_strategy** | Option<**String**> | | | +**stopwords** | Option<**String**> | | | +**facet_return_parent** | Option<**String**> | | | +**voice_query** | Option<**String**> | | | +**conversation** | Option<**bool**> | | | +**conversation_model_id** | Option<**String**> | | | +**conversation_id** | Option<**String**> | | | **multi_search_searches_parameter** | Option<[**MultiSearchSearchesParameter**](MultiSearchSearchesParameter.md)> | | | ### Return type -[**crate::models::MultiSearchResult**](MultiSearchResult.md) +[**models::MultiSearchResult**](MultiSearchResult.md) ### Authorization @@ -422,7 +404,7 @@ Name | Type | Description | Required | Notes ## search_collection -> crate::models::SearchResult search_collection(collection_name, search_parameters) +> models::SearchResult search_collection(collection_name, q, query_by, nl_query, nl_model_id, query_by_weights, text_match_type, prefix, infix, max_extra_prefix, max_extra_suffix, filter_by, max_filter_by_candidates, sort_by, facet_by, max_facet_values, facet_query, num_typos, page, per_page, limit, offset, group_by, group_limit, group_missing_values, include_fields, exclude_fields, highlight_full_fields, highlight_affix_num_tokens, highlight_start_tag, highlight_end_tag, enable_highlight_v1, enable_analytics, snippet_threshold, synonym_sets, drop_tokens_threshold, drop_tokens_mode, typo_tokens_threshold, enable_typos_for_alpha_numerical_tokens, filter_curated_hits, enable_synonyms, synonym_prefix, synonym_num_typos, pinned_hits, hidden_hits, override_tags, highlight_fields, split_join_tokens, pre_segmented_query, preset, enable_overrides, prioritize_exact_match, max_candidates, prioritize_token_position, prioritize_num_matching_fields, enable_typos_for_numerical_tokens, exhaustive_search, search_cutoff_ms, use_cache, cache_ttl, min_len_1typo, min_len_2typo, vector_query, remote_embedding_timeout_ms, remote_embedding_num_tries, facet_strategy, stopwords, facet_return_parent, voice_query, conversation, conversation_model_id, conversation_id) Search for documents in a collection Search for documents in a collection that match the search criteria. @@ -433,11 +415,81 @@ Search for documents in a collection that match the search criteria. Name | Type | Description | Required | Notes ------------- | ------------- | ------------- | ------------- | ------------- **collection_name** | **String** | The name of the collection to search for the document under | [required] | -**search_parameters** | [**SearchParameters**](.md) | | [required] | +**q** | Option<**String**> | | | +**query_by** | Option<**String**> | | | +**nl_query** | Option<**bool**> | | | +**nl_model_id** | Option<**String**> | | | +**query_by_weights** | Option<**String**> | | | +**text_match_type** | Option<**String**> | | | +**prefix** | Option<**String**> | | | +**infix** | Option<**String**> | | | +**max_extra_prefix** | Option<**i32**> | | | +**max_extra_suffix** | Option<**i32**> | | | +**filter_by** | Option<**String**> | | | +**max_filter_by_candidates** | Option<**i32**> | | | +**sort_by** | Option<**String**> | | | +**facet_by** | Option<**String**> | | | +**max_facet_values** | Option<**i32**> | | | +**facet_query** | Option<**String**> | | | +**num_typos** | Option<**String**> | | | +**page** | Option<**i32**> | | | +**per_page** | Option<**i32**> | | | +**limit** | Option<**i32**> | | | +**offset** | Option<**i32**> | | | +**group_by** | Option<**String**> | | | +**group_limit** | Option<**i32**> | | | +**group_missing_values** | Option<**bool**> | | | +**include_fields** | Option<**String**> | | | +**exclude_fields** | Option<**String**> | | | +**highlight_full_fields** | Option<**String**> | | | +**highlight_affix_num_tokens** | Option<**i32**> | | | +**highlight_start_tag** | Option<**String**> | | | +**highlight_end_tag** | Option<**String**> | | | +**enable_highlight_v1** | Option<**bool**> | | |[default to true] +**enable_analytics** | Option<**bool**> | | |[default to true] +**snippet_threshold** | Option<**i32**> | | | +**synonym_sets** | Option<**String**> | | | +**drop_tokens_threshold** | Option<**i32**> | | | +**drop_tokens_mode** | Option<[**DropTokensMode**](.md)> | | | +**typo_tokens_threshold** | Option<**i32**> | | | +**enable_typos_for_alpha_numerical_tokens** | Option<**bool**> | | | +**filter_curated_hits** | Option<**bool**> | | | +**enable_synonyms** | Option<**bool**> | | | +**synonym_prefix** | Option<**bool**> | | | +**synonym_num_typos** | Option<**i32**> | | | +**pinned_hits** | Option<**String**> | | | +**hidden_hits** | Option<**String**> | | | +**override_tags** | Option<**String**> | | | +**highlight_fields** | Option<**String**> | | | +**split_join_tokens** | Option<**String**> | | | +**pre_segmented_query** | Option<**bool**> | | | +**preset** | Option<**String**> | | | +**enable_overrides** | Option<**bool**> | | |[default to false] +**prioritize_exact_match** | Option<**bool**> | | |[default to true] +**max_candidates** | Option<**i32**> | | | +**prioritize_token_position** | Option<**bool**> | | |[default to false] +**prioritize_num_matching_fields** | Option<**bool**> | | |[default to true] +**enable_typos_for_numerical_tokens** | Option<**bool**> | | |[default to true] +**exhaustive_search** | Option<**bool**> | | | +**search_cutoff_ms** | Option<**i32**> | | | +**use_cache** | Option<**bool**> | | | +**cache_ttl** | Option<**i32**> | | | +**min_len_1typo** | Option<**i32**> | | | +**min_len_2typo** | Option<**i32**> | | | +**vector_query** | Option<**String**> | | | +**remote_embedding_timeout_ms** | Option<**i32**> | | | +**remote_embedding_num_tries** | Option<**i32**> | | | +**facet_strategy** | Option<**String**> | | | +**stopwords** | Option<**String**> | | | +**facet_return_parent** | Option<**String**> | | | +**voice_query** | Option<**String**> | | | +**conversation** | Option<**bool**> | | | +**conversation_model_id** | Option<**String**> | | | +**conversation_id** | Option<**String**> | | | ### Return type -[**crate::models::SearchResult**](SearchResult.md) +[**models::SearchResult**](SearchResult.md) ### Authorization @@ -453,7 +505,7 @@ Name | Type | Description | Required | Notes ## update_document -> serde_json::Value update_document(collection_name, document_id, body) +> serde_json::Value update_document(collection_name, document_id, body, dirty_values) Update a document Update an individual document from a collection by using its ID. The update can be partial. @@ -466,6 +518,7 @@ Name | Type | Description | Required | Notes **collection_name** | **String** | The name of the collection to search for the document under | [required] | **document_id** | **String** | The Document ID | [required] | **body** | **serde_json::Value** | The document object with fields to be updated | [required] | +**dirty_values** | Option<[**DirtyValues**](.md)> | Dealing with Dirty Data | | ### Return type @@ -485,7 +538,7 @@ Name | Type | Description | Required | Notes ## update_documents -> crate::models::UpdateDocuments200Response update_documents(collection_name, body, update_documents_parameters) +> models::UpdateDocuments200Response update_documents(collection_name, body, filter_by) Update documents with conditional query The filter_by query parameter is used to filter to specify a condition against which the documents are matched. The request body contains the fields that should be updated for any documents that match the filter condition. This endpoint is only available if the Typesense server is version `0.25.0.rc12` or later. @@ -497,11 +550,11 @@ Name | Type | Description | Required | Notes ------------- | ------------- | ------------- | ------------- | ------------- **collection_name** | **String** | The name of the collection to update documents in | [required] | **body** | **serde_json::Value** | The document fields to be updated | [required] | -**update_documents_parameters** | Option<[**UpdateDocumentsUpdateDocumentsParametersParameter**](.md)> | | | +**filter_by** | Option<**String**> | | | ### Return type -[**crate::models::UpdateDocuments200Response**](updateDocuments_200_response.md) +[**models::UpdateDocuments200Response**](updateDocuments_200_response.md) ### Authorization @@ -517,7 +570,7 @@ Name | Type | Description | Required | Notes ## upsert_search_override -> crate::models::SearchOverride upsert_search_override(collection_name, override_id, search_override_schema) +> models::SearchOverride upsert_search_override(collection_name, override_id, search_override_schema) Create or update an override to promote certain documents over others Create or update an override to promote certain documents over others. Using overrides, you can include or exclude specific documents for a given query. @@ -533,39 +586,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::SearchOverride**](SearchOverride.md) - -### Authorization - -[api_key_header](../README.md#api_key_header) - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - - -## upsert_search_synonym - -> crate::models::SearchSynonym upsert_search_synonym(collection_name, synonym_id, search_synonym_schema) -Create or update a synonym - -Create or update a synonym to define search terms that should be considered equivalent. - -### Parameters - - -Name | Type | Description | Required | Notes -------------- | ------------- | ------------- | ------------- | ------------- -**collection_name** | **String** | The name of the collection | [required] | -**synonym_id** | **String** | The ID of the search synonym to create/update | [required] | -**search_synonym_schema** | [**SearchSynonymSchema**](SearchSynonymSchema.md) | The search synonym object to be created/updated | [required] | - -### Return type - -[**crate::models::SearchSynonym**](SearchSynonym.md) +[**models::SearchOverride**](SearchOverride.md) ### Authorization diff --git a/typesense_codegen/docs/DropTokensMode.md b/typesense_codegen/docs/DropTokensMode.md new file mode 100644 index 0000000..f6da263 --- /dev/null +++ b/typesense_codegen/docs/DropTokensMode.md @@ -0,0 +1,14 @@ +# DropTokensMode + +## Enum Variants + +| Name | Value | +|---- | -----| +| RightToLeft | right_to_left | +| LeftToRight | left_to_right | +| BothSidesColon3 | both_sides:3 | + + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/ExportDocumentsExportDocumentsParametersParameter.md b/typesense_codegen/docs/ExportDocumentsExportDocumentsParametersParameter.md index 14b7aaa..553431f 100644 --- a/typesense_codegen/docs/ExportDocumentsExportDocumentsParametersParameter.md +++ b/typesense_codegen/docs/ExportDocumentsExportDocumentsParametersParameter.md @@ -5,8 +5,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **filter_by** | Option<**String**> | Filter conditions for refining your search results. Separate multiple conditions with &&. | [optional] -**include_fields** | **String** | List of fields from the document to include in the search result | -**exclude_fields** | **String** | List of fields from the document to exclude in the search result | +**include_fields** | Option<**String**> | List of fields from the document to include in the search result | [optional] +**exclude_fields** | Option<**String**> | List of fields from the document to exclude in the search result | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/ExportDocumentsParameters.md b/typesense_codegen/docs/ExportDocumentsParameters.md new file mode 100644 index 0000000..25c7dc7 --- /dev/null +++ b/typesense_codegen/docs/ExportDocumentsParameters.md @@ -0,0 +1,13 @@ +# ExportDocumentsParameters + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**filter_by** | Option<**String**> | Filter conditions for refining your search results. Separate multiple conditions with &&. | [optional] +**include_fields** | Option<**String**> | List of fields from the document to include in the search result | [optional] +**exclude_fields** | Option<**String**> | List of fields from the document to exclude in the search result | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/FacetCounts.md b/typesense_codegen/docs/FacetCounts.md index e850701..4b170c1 100644 --- a/typesense_codegen/docs/FacetCounts.md +++ b/typesense_codegen/docs/FacetCounts.md @@ -4,9 +4,9 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**counts** | Option<[**Vec**](FacetCounts_counts_inner.md)> | | [optional] +**counts** | Option<[**Vec**](FacetCounts_counts_inner.md)> | | [optional] **field_name** | Option<**String**> | | [optional] -**stats** | Option<[**crate::models::FacetCountsStats**](FacetCounts_stats.md)> | | [optional] +**stats** | Option<[**models::FacetCountsStats**](FacetCounts_stats.md)> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/FacetCountsCountsInner.md b/typesense_codegen/docs/FacetCountsCountsInner.md index 23befac..3733448 100644 --- a/typesense_codegen/docs/FacetCountsCountsInner.md +++ b/typesense_codegen/docs/FacetCountsCountsInner.md @@ -7,6 +7,7 @@ Name | Type | Description | Notes **count** | Option<**i32**> | | [optional] **highlighted** | Option<**String**> | | [optional] **value** | Option<**String**> | | [optional] +**parent** | Option<[**serde_json::Value**](.md)> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/Field.md b/typesense_codegen/docs/Field.md index dbf6a9e..17afabd 100644 --- a/typesense_codegen/docs/Field.md +++ b/typesense_codegen/docs/Field.md @@ -12,9 +12,17 @@ Name | Type | Description | Notes **locale** | Option<**String**> | | [optional] **sort** | Option<**bool**> | | [optional] **infix** | Option<**bool**> | | [optional][default to false] +**reference** | Option<**String**> | Name of a field in another collection that should be linked to this collection so that it can be joined during query. | [optional] **num_dim** | Option<**i32**> | | [optional] **drop** | Option<**bool**> | | [optional] -**embed** | Option<[**crate::models::FieldEmbed**](Field_embed.md)> | | [optional] +**store** | Option<**bool**> | When set to false, the field value will not be stored on disk. Default: true. | [optional] +**vec_dist** | Option<**String**> | The distance metric to be used for vector search. Default: `cosine`. You can also use `ip` for inner product. | [optional] +**range_index** | Option<**bool**> | Enables an index optimized for range filtering on numerical fields (e.g. rating:>3.5). Default: false. | [optional] +**stem** | Option<**bool**> | Values are stemmed before indexing in-memory. Default: false. | [optional] +**stem_dictionary** | Option<**String**> | Name of the stemming dictionary to use for this field | [optional] +**token_separators** | Option<**Vec**> | List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. | [optional][default to []] +**symbols_to_index** | Option<**Vec**> | List of symbols or special characters to be indexed. | [optional][default to []] +**embed** | Option<[**models::FieldEmbed**](Field_embed.md)> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/FieldEmbed.md b/typesense_codegen/docs/FieldEmbed.md index b1dc03b..dca3983 100644 --- a/typesense_codegen/docs/FieldEmbed.md +++ b/typesense_codegen/docs/FieldEmbed.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **from** | **Vec** | | -**model_config** | [**crate::models::FieldEmbedModelConfig**](Field_embed_model_config.md) | | +**model_config** | [**models::FieldEmbedModelConfig**](Field_embed_model_config.md) | | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/FieldEmbedModelConfig.md b/typesense_codegen/docs/FieldEmbedModelConfig.md index 88c03af..8ee1235 100644 --- a/typesense_codegen/docs/FieldEmbedModelConfig.md +++ b/typesense_codegen/docs/FieldEmbedModelConfig.md @@ -6,10 +6,14 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **model_name** | **String** | | **api_key** | Option<**String**> | | [optional] +**url** | Option<**String**> | | [optional] **access_token** | Option<**String**> | | [optional] +**refresh_token** | Option<**String**> | | [optional] **client_id** | Option<**String**> | | [optional] **client_secret** | Option<**String**> | | [optional] **project_id** | Option<**String**> | | [optional] +**indexing_prefix** | Option<**String**> | | [optional] +**query_prefix** | Option<**String**> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/GetCollectionsGetCollectionsParametersParameter.md b/typesense_codegen/docs/GetCollectionsGetCollectionsParametersParameter.md new file mode 100644 index 0000000..f4fef66 --- /dev/null +++ b/typesense_codegen/docs/GetCollectionsGetCollectionsParametersParameter.md @@ -0,0 +1,13 @@ +# GetCollectionsGetCollectionsParametersParameter + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**exclude_fields** | Option<**String**> | Comma-separated list of fields from the collection to exclude from the response | [optional] +**limit** | Option<**i32**> | Number of collections to fetch. Default: returns all collections. | [optional] +**offset** | Option<**i32**> | Identifies the starting point to return collections when paginating. | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/GetCollectionsParameters.md b/typesense_codegen/docs/GetCollectionsParameters.md new file mode 100644 index 0000000..d1f2a68 --- /dev/null +++ b/typesense_codegen/docs/GetCollectionsParameters.md @@ -0,0 +1,13 @@ +# GetCollectionsParameters + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**exclude_fields** | Option<**String**> | Comma-separated list of fields from the collection to exclude from the response | [optional] +**limit** | Option<**i32**> | Number of collections to fetch. Default: returns all collections. | [optional] +**offset** | Option<**i32**> | Identifies the starting point to return collections when paginating. | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/HealthApi.md b/typesense_codegen/docs/HealthApi.md index 8c4d523..cdc7c9f 100644 --- a/typesense_codegen/docs/HealthApi.md +++ b/typesense_codegen/docs/HealthApi.md @@ -1,6 +1,6 @@ # \HealthApi -All URIs are relative to *http://localhost* +All URIs are relative to *http://localhost:8108* Method | HTTP request | Description ------------- | ------------- | ------------- @@ -10,7 +10,7 @@ Method | HTTP request | Description ## health -> crate::models::HealthStatus health() +> models::HealthStatus health() Checks if Typesense server is ready to accept requests. Checks if Typesense server is ready to accept requests. @@ -21,7 +21,7 @@ This endpoint does not need any parameter. ### Return type -[**crate::models::HealthStatus**](HealthStatus.md) +[**models::HealthStatus**](HealthStatus.md) ### Authorization diff --git a/typesense_codegen/docs/ImportDocumentsImportDocumentsParametersParameter.md b/typesense_codegen/docs/ImportDocumentsImportDocumentsParametersParameter.md index aea6558..185baaa 100644 --- a/typesense_codegen/docs/ImportDocumentsImportDocumentsParametersParameter.md +++ b/typesense_codegen/docs/ImportDocumentsImportDocumentsParametersParameter.md @@ -4,10 +4,12 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**action** | Option<**String**> | | [optional] **batch_size** | Option<**i32**> | | [optional] -**dirty_values** | Option<**String**> | | [optional] +**return_id** | Option<**bool**> | Returning the id of the imported documents. If you want the import response to return the ingested document's id in the response, you can use the return_id parameter. | [optional] **remote_embedding_batch_size** | Option<**i32**> | | [optional] +**return_doc** | Option<**bool**> | | [optional] +**action** | Option<[**models::IndexAction**](IndexAction.md)> | | [optional] +**dirty_values** | Option<[**models::DirtyValues**](DirtyValues.md)> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/ImportDocumentsParameters.md b/typesense_codegen/docs/ImportDocumentsParameters.md new file mode 100644 index 0000000..67099eb --- /dev/null +++ b/typesense_codegen/docs/ImportDocumentsParameters.md @@ -0,0 +1,16 @@ +# ImportDocumentsParameters + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**batch_size** | Option<**i32**> | | [optional] +**return_id** | Option<**bool**> | Returning the id of the imported documents. If you want the import response to return the ingested document's id in the response, you can use the return_id parameter. | [optional] +**remote_embedding_batch_size** | Option<**i32**> | | [optional] +**return_doc** | Option<**bool**> | | [optional] +**action** | Option<[**models::IndexAction**](IndexAction.md)> | | [optional] +**dirty_values** | Option<[**models::DirtyValues**](DirtyValues.md)> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/IndexAction.md b/typesense_codegen/docs/IndexAction.md new file mode 100644 index 0000000..7c450eb --- /dev/null +++ b/typesense_codegen/docs/IndexAction.md @@ -0,0 +1,15 @@ +# IndexAction + +## Enum Variants + +| Name | Value | +|---- | -----| +| Create | create | +| Update | update | +| Upsert | upsert | +| Emplace | emplace | + + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/KeysApi.md b/typesense_codegen/docs/KeysApi.md index 422c127..dd5f01d 100644 --- a/typesense_codegen/docs/KeysApi.md +++ b/typesense_codegen/docs/KeysApi.md @@ -1,6 +1,6 @@ # \KeysApi -All URIs are relative to *http://localhost* +All URIs are relative to *http://localhost:8108* Method | HTTP request | Description ------------- | ------------- | ------------- @@ -13,7 +13,7 @@ Method | HTTP request | Description ## create_key -> crate::models::ApiKey create_key(api_key_schema) +> models::ApiKey create_key(api_key_schema) Create an API Key Create an API Key with fine-grain access control. You can restrict access on both a per-collection and per-action level. The generated key is returned only during creation. You want to store this key carefully in a secure place. @@ -27,7 +27,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::ApiKey**](ApiKey.md) +[**models::ApiKey**](ApiKey.md) ### Authorization @@ -43,7 +43,7 @@ Name | Type | Description | Required | Notes ## delete_key -> crate::models::ApiKey delete_key(key_id) +> models::ApiKeyDeleteResponse delete_key(key_id) Delete an API key given its ID. ### Parameters @@ -55,7 +55,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::ApiKey**](ApiKey.md) +[**models::ApiKeyDeleteResponse**](ApiKeyDeleteResponse.md) ### Authorization @@ -71,7 +71,7 @@ Name | Type | Description | Required | Notes ## get_key -> crate::models::ApiKey get_key(key_id) +> models::ApiKey get_key(key_id) Retrieve (metadata about) a key Retrieve (metadata about) a key. Only the key prefix is returned when you retrieve a key. Due to security reasons, only the create endpoint returns the full API key. @@ -85,7 +85,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::ApiKey**](ApiKey.md) +[**models::ApiKey**](ApiKey.md) ### Authorization @@ -101,7 +101,7 @@ Name | Type | Description | Required | Notes ## get_keys -> crate::models::ApiKeysResponse get_keys() +> models::ApiKeysResponse get_keys() Retrieve (metadata about) all keys. ### Parameters @@ -110,7 +110,7 @@ This endpoint does not need any parameter. ### Return type -[**crate::models::ApiKeysResponse**](ApiKeysResponse.md) +[**models::ApiKeysResponse**](ApiKeysResponse.md) ### Authorization diff --git a/typesense_codegen/docs/ListStemmingDictionaries200Response.md b/typesense_codegen/docs/ListStemmingDictionaries200Response.md new file mode 100644 index 0000000..d56a82d --- /dev/null +++ b/typesense_codegen/docs/ListStemmingDictionaries200Response.md @@ -0,0 +1,11 @@ +# ListStemmingDictionaries200Response + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**dictionaries** | Option<**Vec**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/MultiSearchCollectionParameters.md b/typesense_codegen/docs/MultiSearchCollectionParameters.md index 07be3ee..b2bbf1f 100644 --- a/typesense_codegen/docs/MultiSearchCollectionParameters.md +++ b/typesense_codegen/docs/MultiSearchCollectionParameters.md @@ -20,10 +20,11 @@ Name | Type | Description | Notes **num_typos** | Option<**String**> | The number of typographical errors (1 or 2) that would be tolerated. Default: 2 | [optional] **page** | Option<**i32**> | Results from this specific page number would be fetched. | [optional] **per_page** | Option<**i32**> | Number of results to fetch per page. Default: 10 | [optional] -**limit** | Option<**i32**> | Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. | [optional] +**limit** | Option<**i32**> | Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. | [optional] **offset** | Option<**i32**> | Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. | [optional] **group_by** | Option<**String**> | You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. | [optional] **group_limit** | Option<**i32**> | Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 | [optional] +**group_missing_values** | Option<**bool**> | Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true | [optional] **include_fields** | Option<**String**> | List of fields from the document to include in the search result | [optional] **exclude_fields** | Option<**String**> | List of fields from the document to exclude in the search result | [optional] **highlight_full_fields** | Option<**String**> | List of fields which should be highlighted fully without snippeting | [optional] @@ -32,24 +33,44 @@ Name | Type | Description | Notes **highlight_end_tag** | Option<**String**> | The end tag used for the highlighted snippets. Default: `` | [optional] **snippet_threshold** | Option<**i32**> | Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 | [optional] **drop_tokens_threshold** | Option<**i32**> | If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 | [optional] +**drop_tokens_mode** | Option<[**models::DropTokensMode**](DropTokensMode.md)> | | [optional] **typo_tokens_threshold** | Option<**i32**> | If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 | [optional] -**pinned_hits** | Option<**String**> | A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. | [optional] +**enable_typos_for_alpha_numerical_tokens** | Option<**bool**> | Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. | [optional] +**filter_curated_hits** | Option<**bool**> | Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false | [optional] +**enable_synonyms** | Option<**bool**> | If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true | [optional] +**enable_analytics** | Option<**bool**> | Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). | [optional][default to true] +**synonym_prefix** | Option<**bool**> | Allow synonym resolution on word prefixes in the query. Default: false | [optional] +**synonym_num_typos** | Option<**i32**> | Allow synonym resolution on typo-corrected words in the query. Default: 0 | [optional] +**pinned_hits** | Option<**String**> | A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. | [optional] **hidden_hits** | Option<**String**> | A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. | [optional] -**highlight_fields** | Option<**String**> | A list of custom fields that must be highlighted even if you don't query for them | [optional] -**pre_segmented_query** | Option<**bool**> | You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same | [optional] +**override_tags** | Option<**String**> | Comma separated list of tags to trigger the curations rules that match the tags. | [optional] +**highlight_fields** | Option<**String**> | A list of custom fields that must be highlighted even if you don't query for them | [optional] +**pre_segmented_query** | Option<**bool**> | You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same | [optional][default to false] **preset** | Option<**String**> | Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. | [optional] -**enable_overrides** | Option<**bool**> | If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false | [optional] -**prioritize_exact_match** | Option<**bool**> | Set this parameter to true to ensure that an exact match is ranked above the others | [optional] -**exhaustive_search** | Option<**bool**> | Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). | [optional] -**search_cutoff_ms** | Option<**i32**> | Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. | [optional] +**enable_overrides** | Option<**bool**> | If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false | [optional][default to false] +**prioritize_exact_match** | Option<**bool**> | Set this parameter to true to ensure that an exact match is ranked above the others | [optional][default to true] +**prioritize_token_position** | Option<**bool**> | Make Typesense prioritize documents where the query words appear earlier in the text. | [optional][default to false] +**prioritize_num_matching_fields** | Option<**bool**> | Make Typesense prioritize documents where the query words appear in more number of fields. | [optional][default to true] +**enable_typos_for_numerical_tokens** | Option<**bool**> | Make Typesense disable typos for numerical tokens. | [optional][default to true] +**exhaustive_search** | Option<**bool**> | Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). | [optional] +**search_cutoff_ms** | Option<**i32**> | Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. | [optional] **use_cache** | Option<**bool**> | Enable server side caching of search query results. By default, caching is disabled. | [optional] -**cache_ttl** | Option<**i32**> | The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. | [optional] -**min_len_1typo** | Option<**i32**> | Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] -**min_len_2typo** | Option<**i32**> | Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] +**cache_ttl** | Option<**i32**> | The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. | [optional] +**min_len_1typo** | Option<**i32**> | Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] +**min_len_2typo** | Option<**i32**> | Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] **vector_query** | Option<**String**> | Vector query expression for fetching documents \"closest\" to a given query/document vector. | [optional] **remote_embedding_timeout_ms** | Option<**i32**> | Timeout (in milliseconds) for fetching remote embeddings. | [optional] **remote_embedding_num_tries** | Option<**i32**> | Number of times to retry fetching remote embeddings. | [optional] -**collection** | **String** | The collection to search in. | +**facet_strategy** | Option<**String**> | Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). | [optional] +**stopwords** | Option<**String**> | Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. | [optional] +**facet_return_parent** | Option<**String**> | Comma separated string of nested facet fields whose parent object should be returned in facet response. | [optional] +**voice_query** | Option<**String**> | The base64 encoded audio file in 16 khz 16-bit WAV format. | [optional] +**conversation** | Option<**bool**> | Enable conversational search. | [optional] +**conversation_model_id** | Option<**String**> | The Id of Conversation Model to be used. | [optional] +**conversation_id** | Option<**String**> | The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. | [optional] +**collection** | Option<**String**> | The collection to search in. | [optional] +**x_typesense_api_key** | Option<**String**> | A separate search API key for each search within a multi_search request | [optional] +**rerank_hybrid_matches** | Option<**bool**> | When true, computes both text match and vector distance scores for all matches in hybrid search. Documents found only through keyword search will get a vector distance score, and documents found only through vector search will get a text match score. | [optional][default to false] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/MultiSearchParameters.md b/typesense_codegen/docs/MultiSearchParameters.md index 20a33a7..5041bca 100644 --- a/typesense_codegen/docs/MultiSearchParameters.md +++ b/typesense_codegen/docs/MultiSearchParameters.md @@ -20,10 +20,11 @@ Name | Type | Description | Notes **num_typos** | Option<**String**> | The number of typographical errors (1 or 2) that would be tolerated. Default: 2 | [optional] **page** | Option<**i32**> | Results from this specific page number would be fetched. | [optional] **per_page** | Option<**i32**> | Number of results to fetch per page. Default: 10 | [optional] -**limit** | Option<**i32**> | Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. | [optional] +**limit** | Option<**i32**> | Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. | [optional] **offset** | Option<**i32**> | Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. | [optional] **group_by** | Option<**String**> | You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. | [optional] **group_limit** | Option<**i32**> | Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 | [optional] +**group_missing_values** | Option<**bool**> | Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true | [optional] **include_fields** | Option<**String**> | List of fields from the document to include in the search result | [optional] **exclude_fields** | Option<**String**> | List of fields from the document to exclude in the search result | [optional] **highlight_full_fields** | Option<**String**> | List of fields which should be highlighted fully without snippeting | [optional] @@ -32,23 +33,41 @@ Name | Type | Description | Notes **highlight_end_tag** | Option<**String**> | The end tag used for the highlighted snippets. Default: `` | [optional] **snippet_threshold** | Option<**i32**> | Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 | [optional] **drop_tokens_threshold** | Option<**i32**> | If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 | [optional] +**drop_tokens_mode** | Option<[**models::DropTokensMode**](DropTokensMode.md)> | | [optional] **typo_tokens_threshold** | Option<**i32**> | If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 | [optional] -**pinned_hits** | Option<**String**> | A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. | [optional] +**enable_typos_for_alpha_numerical_tokens** | Option<**bool**> | Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. | [optional] +**filter_curated_hits** | Option<**bool**> | Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false | [optional] +**enable_synonyms** | Option<**bool**> | If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true | [optional] +**enable_analytics** | Option<**bool**> | Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). | [optional][default to true] +**synonym_prefix** | Option<**bool**> | Allow synonym resolution on word prefixes in the query. Default: false | [optional] +**synonym_num_typos** | Option<**i32**> | Allow synonym resolution on typo-corrected words in the query. Default: 0 | [optional] +**pinned_hits** | Option<**String**> | A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. | [optional] **hidden_hits** | Option<**String**> | A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. | [optional] -**highlight_fields** | Option<**String**> | A list of custom fields that must be highlighted even if you don't query for them | [optional] -**pre_segmented_query** | Option<**bool**> | You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same | [optional] +**override_tags** | Option<**String**> | Comma separated list of tags to trigger the curations rules that match the tags. | [optional] +**highlight_fields** | Option<**String**> | A list of custom fields that must be highlighted even if you don't query for them | [optional] +**pre_segmented_query** | Option<**bool**> | You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same | [optional][default to false] **preset** | Option<**String**> | Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. | [optional] -**enable_overrides** | Option<**bool**> | If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false | [optional] -**prioritize_exact_match** | Option<**bool**> | Set this parameter to true to ensure that an exact match is ranked above the others | [optional] -**exhaustive_search** | Option<**bool**> | Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). | [optional] -**search_cutoff_ms** | Option<**i32**> | Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. | [optional] +**enable_overrides** | Option<**bool**> | If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false | [optional][default to false] +**prioritize_exact_match** | Option<**bool**> | Set this parameter to true to ensure that an exact match is ranked above the others | [optional][default to true] +**prioritize_token_position** | Option<**bool**> | Make Typesense prioritize documents where the query words appear earlier in the text. | [optional][default to false] +**prioritize_num_matching_fields** | Option<**bool**> | Make Typesense prioritize documents where the query words appear in more number of fields. | [optional][default to true] +**enable_typos_for_numerical_tokens** | Option<**bool**> | Make Typesense disable typos for numerical tokens. | [optional][default to true] +**exhaustive_search** | Option<**bool**> | Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). | [optional] +**search_cutoff_ms** | Option<**i32**> | Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. | [optional] **use_cache** | Option<**bool**> | Enable server side caching of search query results. By default, caching is disabled. | [optional] -**cache_ttl** | Option<**i32**> | The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. | [optional] -**min_len_1typo** | Option<**i32**> | Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] -**min_len_2typo** | Option<**i32**> | Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] +**cache_ttl** | Option<**i32**> | The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. | [optional] +**min_len_1typo** | Option<**i32**> | Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] +**min_len_2typo** | Option<**i32**> | Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] **vector_query** | Option<**String**> | Vector query expression for fetching documents \"closest\" to a given query/document vector. | [optional] **remote_embedding_timeout_ms** | Option<**i32**> | Timeout (in milliseconds) for fetching remote embeddings. | [optional] **remote_embedding_num_tries** | Option<**i32**> | Number of times to retry fetching remote embeddings. | [optional] +**facet_strategy** | Option<**String**> | Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). | [optional] +**stopwords** | Option<**String**> | Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. | [optional] +**facet_return_parent** | Option<**String**> | Comma separated string of nested facet fields whose parent object should be returned in facet response. | [optional] +**voice_query** | Option<**String**> | The base64 encoded audio file in 16 khz 16-bit WAV format. | [optional] +**conversation** | Option<**bool**> | Enable conversational search. | [optional] +**conversation_model_id** | Option<**String**> | The Id of Conversation Model to be used. | [optional] +**conversation_id** | Option<**String**> | The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/MultiSearchResult.md b/typesense_codegen/docs/MultiSearchResult.md index d9f399c..55bad9d 100644 --- a/typesense_codegen/docs/MultiSearchResult.md +++ b/typesense_codegen/docs/MultiSearchResult.md @@ -4,7 +4,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**results** | [**Vec**](SearchResult.md) | | +**results** | [**Vec**](MultiSearchResultItem.md) | | +**conversation** | Option<[**models::SearchResultConversation**](SearchResultConversation.md)> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/MultiSearchResultItem.md b/typesense_codegen/docs/MultiSearchResultItem.md new file mode 100644 index 0000000..0f306be --- /dev/null +++ b/typesense_codegen/docs/MultiSearchResultItem.md @@ -0,0 +1,24 @@ +# MultiSearchResultItem + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**facet_counts** | Option<[**Vec**](FacetCounts.md)> | | [optional] +**found** | Option<**i32**> | The number of documents found | [optional] +**found_docs** | Option<**i32**> | | [optional] +**search_time_ms** | Option<**i32**> | The number of milliseconds the search took | [optional] +**out_of** | Option<**i32**> | The total number of documents in the collection | [optional] +**search_cutoff** | Option<**bool**> | Whether the search was cut off | [optional] +**page** | Option<**i32**> | The search result page number | [optional] +**grouped_hits** | Option<[**Vec**](SearchGroupedHit.md)> | | [optional] +**hits** | Option<[**Vec**](SearchResultHit.md)> | The documents that matched the search query | [optional] +**request_params** | Option<[**models::SearchRequestParams**](SearchRequestParams.md)> | | [optional] +**conversation** | Option<[**models::SearchResultConversation**](SearchResultConversation.md)> | | [optional] +**union_request_params** | Option<[**Vec**](SearchRequestParams.md)> | Returned only for union query response. | [optional] +**code** | Option<**i64**> | HTTP error code | [optional] +**error** | Option<**String**> | Error description | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/MultiSearchSearchesParameter.md b/typesense_codegen/docs/MultiSearchSearchesParameter.md index aee8e7f..5bfd345 100644 --- a/typesense_codegen/docs/MultiSearchSearchesParameter.md +++ b/typesense_codegen/docs/MultiSearchSearchesParameter.md @@ -4,7 +4,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**searches** | [**Vec**](MultiSearchCollectionParameters.md) | | +**union** | Option<**bool**> | When true, merges the search results from each search query into a single ordered set of hits. | [optional][default to false] +**searches** | [**Vec**](MultiSearchCollectionParameters.md) | | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/NlSearchModelBase.md b/typesense_codegen/docs/NlSearchModelBase.md new file mode 100644 index 0000000..b331895 --- /dev/null +++ b/typesense_codegen/docs/NlSearchModelBase.md @@ -0,0 +1,28 @@ +# NlSearchModelBase + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**model_name** | Option<**String**> | Name of the NL model to use | [optional] +**api_key** | Option<**String**> | API key for the NL model service | [optional] +**api_url** | Option<**String**> | Custom API URL for the NL model service | [optional] +**max_bytes** | Option<**i32**> | Maximum number of bytes to process | [optional] +**temperature** | Option<**f64**> | Temperature parameter for the NL model | [optional] +**system_prompt** | Option<**String**> | System prompt for the NL model | [optional] +**top_p** | Option<**f64**> | Top-p parameter for the NL model (Google-specific) | [optional] +**top_k** | Option<**i32**> | Top-k parameter for the NL model (Google-specific) | [optional] +**stop_sequences** | Option<**Vec**> | Stop sequences for the NL model (Google-specific) | [optional] +**api_version** | Option<**String**> | API version for the NL model service | [optional] +**project_id** | Option<**String**> | Project ID for GCP Vertex AI | [optional] +**access_token** | Option<**String**> | Access token for GCP Vertex AI | [optional] +**refresh_token** | Option<**String**> | Refresh token for GCP Vertex AI | [optional] +**client_id** | Option<**String**> | Client ID for GCP Vertex AI | [optional] +**client_secret** | Option<**String**> | Client secret for GCP Vertex AI | [optional] +**region** | Option<**String**> | Region for GCP Vertex AI | [optional] +**max_output_tokens** | Option<**i32**> | Maximum output tokens for GCP Vertex AI | [optional] +**account_id** | Option<**String**> | Account ID for Cloudflare-specific models | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/NlSearchModelCreateSchema.md b/typesense_codegen/docs/NlSearchModelCreateSchema.md new file mode 100644 index 0000000..6690186 --- /dev/null +++ b/typesense_codegen/docs/NlSearchModelCreateSchema.md @@ -0,0 +1,29 @@ +# NlSearchModelCreateSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**model_name** | Option<**String**> | Name of the NL model to use | [optional] +**api_key** | Option<**String**> | API key for the NL model service | [optional] +**api_url** | Option<**String**> | Custom API URL for the NL model service | [optional] +**max_bytes** | Option<**i32**> | Maximum number of bytes to process | [optional] +**temperature** | Option<**f64**> | Temperature parameter for the NL model | [optional] +**system_prompt** | Option<**String**> | System prompt for the NL model | [optional] +**top_p** | Option<**f64**> | Top-p parameter for the NL model (Google-specific) | [optional] +**top_k** | Option<**i32**> | Top-k parameter for the NL model (Google-specific) | [optional] +**stop_sequences** | Option<**Vec**> | Stop sequences for the NL model (Google-specific) | [optional] +**api_version** | Option<**String**> | API version for the NL model service | [optional] +**project_id** | Option<**String**> | Project ID for GCP Vertex AI | [optional] +**access_token** | Option<**String**> | Access token for GCP Vertex AI | [optional] +**refresh_token** | Option<**String**> | Refresh token for GCP Vertex AI | [optional] +**client_id** | Option<**String**> | Client ID for GCP Vertex AI | [optional] +**client_secret** | Option<**String**> | Client secret for GCP Vertex AI | [optional] +**region** | Option<**String**> | Region for GCP Vertex AI | [optional] +**max_output_tokens** | Option<**i32**> | Maximum output tokens for GCP Vertex AI | [optional] +**account_id** | Option<**String**> | Account ID for Cloudflare-specific models | [optional] +**id** | Option<**String**> | Optional ID for the NL search model | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/NlSearchModelDeleteSchema.md b/typesense_codegen/docs/NlSearchModelDeleteSchema.md new file mode 100644 index 0000000..97be1ac --- /dev/null +++ b/typesense_codegen/docs/NlSearchModelDeleteSchema.md @@ -0,0 +1,11 @@ +# NlSearchModelDeleteSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **String** | ID of the deleted NL search model | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/NlSearchModelSchema.md b/typesense_codegen/docs/NlSearchModelSchema.md new file mode 100644 index 0000000..24f870f --- /dev/null +++ b/typesense_codegen/docs/NlSearchModelSchema.md @@ -0,0 +1,29 @@ +# NlSearchModelSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**model_name** | Option<**String**> | Name of the NL model to use | [optional] +**api_key** | Option<**String**> | API key for the NL model service | [optional] +**api_url** | Option<**String**> | Custom API URL for the NL model service | [optional] +**max_bytes** | Option<**i32**> | Maximum number of bytes to process | [optional] +**temperature** | Option<**f64**> | Temperature parameter for the NL model | [optional] +**system_prompt** | Option<**String**> | System prompt for the NL model | [optional] +**top_p** | Option<**f64**> | Top-p parameter for the NL model (Google-specific) | [optional] +**top_k** | Option<**i32**> | Top-k parameter for the NL model (Google-specific) | [optional] +**stop_sequences** | Option<**Vec**> | Stop sequences for the NL model (Google-specific) | [optional] +**api_version** | Option<**String**> | API version for the NL model service | [optional] +**project_id** | Option<**String**> | Project ID for GCP Vertex AI | [optional] +**access_token** | Option<**String**> | Access token for GCP Vertex AI | [optional] +**refresh_token** | Option<**String**> | Refresh token for GCP Vertex AI | [optional] +**client_id** | Option<**String**> | Client ID for GCP Vertex AI | [optional] +**client_secret** | Option<**String**> | Client secret for GCP Vertex AI | [optional] +**region** | Option<**String**> | Region for GCP Vertex AI | [optional] +**max_output_tokens** | Option<**i32**> | Maximum output tokens for GCP Vertex AI | [optional] +**account_id** | Option<**String**> | Account ID for Cloudflare-specific models | [optional] +**id** | **String** | ID of the NL search model | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/NlSearchModelsApi.md b/typesense_codegen/docs/NlSearchModelsApi.md new file mode 100644 index 0000000..07d5448 --- /dev/null +++ b/typesense_codegen/docs/NlSearchModelsApi.md @@ -0,0 +1,161 @@ +# \NlSearchModelsApi + +All URIs are relative to *http://localhost:8108* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**create_nl_search_model**](NlSearchModelsApi.md#create_nl_search_model) | **POST** /nl_search_models | Create a NL search model +[**delete_nl_search_model**](NlSearchModelsApi.md#delete_nl_search_model) | **DELETE** /nl_search_models/{modelId} | Delete a NL search model +[**retrieve_all_nl_search_models**](NlSearchModelsApi.md#retrieve_all_nl_search_models) | **GET** /nl_search_models | List all NL search models +[**retrieve_nl_search_model**](NlSearchModelsApi.md#retrieve_nl_search_model) | **GET** /nl_search_models/{modelId} | Retrieve a NL search model +[**update_nl_search_model**](NlSearchModelsApi.md#update_nl_search_model) | **PUT** /nl_search_models/{modelId} | Update a NL search model + + + +## create_nl_search_model + +> models::NlSearchModelSchema create_nl_search_model(nl_search_model_create_schema) +Create a NL search model + +Create a new NL search model. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**nl_search_model_create_schema** | [**NlSearchModelCreateSchema**](NlSearchModelCreateSchema.md) | The NL search model to be created | [required] | + +### Return type + +[**models::NlSearchModelSchema**](NLSearchModelSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## delete_nl_search_model + +> models::NlSearchModelDeleteSchema delete_nl_search_model(model_id) +Delete a NL search model + +Delete a specific NL search model by its ID. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**model_id** | **String** | The ID of the NL search model to delete | [required] | + +### Return type + +[**models::NlSearchModelDeleteSchema**](NLSearchModelDeleteSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_all_nl_search_models + +> Vec retrieve_all_nl_search_models() +List all NL search models + +Retrieve all NL search models. + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**Vec**](NLSearchModelSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_nl_search_model + +> models::NlSearchModelSchema retrieve_nl_search_model(model_id) +Retrieve a NL search model + +Retrieve a specific NL search model by its ID. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**model_id** | **String** | The ID of the NL search model to retrieve | [required] | + +### Return type + +[**models::NlSearchModelSchema**](NLSearchModelSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## update_nl_search_model + +> models::NlSearchModelSchema update_nl_search_model(model_id, body) +Update a NL search model + +Update an existing NL search model. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**model_id** | **String** | The ID of the NL search model to update | [required] | +**body** | **models::NlSearchModelCreateSchema** | The NL search model fields to update | [required] | + +### Return type + +[**models::NlSearchModelSchema**](NLSearchModelSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/typesense_codegen/docs/OperationsApi.md b/typesense_codegen/docs/OperationsApi.md index 9a499de..86a6e6d 100644 --- a/typesense_codegen/docs/OperationsApi.md +++ b/typesense_codegen/docs/OperationsApi.md @@ -1,17 +1,158 @@ # \OperationsApi -All URIs are relative to *http://localhost* +All URIs are relative to *http://localhost:8108* Method | HTTP request | Description ------------- | ------------- | ------------- +[**clear_cache**](OperationsApi.md#clear_cache) | **POST** /operations/cache/clear | Clear the cached responses of search requests in the LRU cache. +[**compact_db**](OperationsApi.md#compact_db) | **POST** /operations/db/compact | Compacting the on-disk database +[**get_schema_changes**](OperationsApi.md#get_schema_changes) | **GET** /operations/schema_changes | Get the status of in-progress schema change operations +[**retrieve_api_stats**](OperationsApi.md#retrieve_api_stats) | **GET** /stats.json | Get stats about API endpoints. +[**retrieve_metrics**](OperationsApi.md#retrieve_metrics) | **GET** /metrics.json | Get current RAM, CPU, Disk & Network usage metrics. [**take_snapshot**](OperationsApi.md#take_snapshot) | **POST** /operations/snapshot | Creates a point-in-time snapshot of a Typesense node's state and data in the specified directory. +[**toggle_slow_request_log**](OperationsApi.md#toggle_slow_request_log) | **POST** /config | Toggle Slow Request Log [**vote**](OperationsApi.md#vote) | **POST** /operations/vote | Triggers a follower node to initiate the raft voting process, which triggers leader re-election. +## clear_cache + +> models::SuccessStatus clear_cache() +Clear the cached responses of search requests in the LRU cache. + +Clear the cached responses of search requests that are sent with `use_cache` parameter in the LRU cache. + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**models::SuccessStatus**](SuccessStatus.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## compact_db + +> models::SuccessStatus compact_db() +Compacting the on-disk database + +Typesense uses RocksDB to store your documents on the disk. If you do frequent writes or updates, you could benefit from running a compaction of the underlying RocksDB database. This could reduce the size of the database and decrease read latency. While the database will not block during this operation, we recommend running it during off-peak hours. + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**models::SuccessStatus**](SuccessStatus.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## get_schema_changes + +> Vec get_schema_changes() +Get the status of in-progress schema change operations + +Returns the status of any ongoing schema change operations. If no schema changes are in progress, returns an empty response. + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**Vec**](SchemaChangeStatus.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_api_stats + +> models::ApiStatsResponse retrieve_api_stats() +Get stats about API endpoints. + +Retrieve the stats about API endpoints. + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**models::ApiStatsResponse**](APIStatsResponse.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_metrics + +> serde_json::Value retrieve_metrics() +Get current RAM, CPU, Disk & Network usage metrics. + +Retrieve the metrics. + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**serde_json::Value**](serde_json::Value.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + ## take_snapshot -> crate::models::SuccessStatus take_snapshot(snapshot_path) +> models::SuccessStatus take_snapshot(snapshot_path) Creates a point-in-time snapshot of a Typesense node's state and data in the specified directory. Creates a point-in-time snapshot of a Typesense node's state and data in the specified directory. You can then backup the snapshot directory that gets created and later restore it as a data directory, as needed. @@ -25,7 +166,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::SuccessStatus**](SuccessStatus.md) +[**models::SuccessStatus**](SuccessStatus.md) ### Authorization @@ -39,9 +180,39 @@ Name | Type | Description | Required | Notes [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +## toggle_slow_request_log + +> models::SuccessStatus toggle_slow_request_log(toggle_slow_request_log_request) +Toggle Slow Request Log + +Enable logging of requests that take over a defined threshold of time. Default is `-1` which disables slow request logging. Slow requests are logged to the primary log file, with the prefix SLOW REQUEST. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**toggle_slow_request_log_request** | Option<[**ToggleSlowRequestLogRequest**](ToggleSlowRequestLogRequest.md)> | | | + +### Return type + +[**models::SuccessStatus**](SuccessStatus.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + ## vote -> crate::models::SuccessStatus vote() +> models::SuccessStatus vote() Triggers a follower node to initiate the raft voting process, which triggers leader re-election. Triggers a follower node to initiate the raft voting process, which triggers leader re-election. The follower node that you run this operation against will become the new leader, once this command succeeds. @@ -52,7 +223,7 @@ This endpoint does not need any parameter. ### Return type -[**crate::models::SuccessStatus**](SuccessStatus.md) +[**models::SuccessStatus**](SuccessStatus.md) ### Authorization diff --git a/typesense_codegen/docs/OverrideApi.md b/typesense_codegen/docs/OverrideApi.md index 02f1ca5..85e9cf3 100644 --- a/typesense_codegen/docs/OverrideApi.md +++ b/typesense_codegen/docs/OverrideApi.md @@ -1,6 +1,6 @@ # \OverrideApi -All URIs are relative to *http://localhost* +All URIs are relative to *http://localhost:8108* Method | HTTP request | Description ------------- | ------------- | ------------- @@ -10,7 +10,7 @@ Method | HTTP request | Description ## get_search_override -> crate::models::SearchOverride get_search_override(collection_name, override_id) +> models::SearchOverride get_search_override(collection_name, override_id) Retrieve a single search override Retrieve the details of a search override, given its id. @@ -25,7 +25,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::SearchOverride**](SearchOverride.md) +[**models::SearchOverride**](SearchOverride.md) ### Authorization diff --git a/typesense_codegen/docs/PresetDeleteSchema.md b/typesense_codegen/docs/PresetDeleteSchema.md new file mode 100644 index 0000000..36bbacf --- /dev/null +++ b/typesense_codegen/docs/PresetDeleteSchema.md @@ -0,0 +1,11 @@ +# PresetDeleteSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/PresetSchema.md b/typesense_codegen/docs/PresetSchema.md new file mode 100644 index 0000000..e1457b9 --- /dev/null +++ b/typesense_codegen/docs/PresetSchema.md @@ -0,0 +1,12 @@ +# PresetSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**value** | [**models::PresetUpsertSchemaValue**](PresetUpsertSchema_value.md) | | +**name** | **String** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/PresetUpsertSchema.md b/typesense_codegen/docs/PresetUpsertSchema.md new file mode 100644 index 0000000..ac9f9cd --- /dev/null +++ b/typesense_codegen/docs/PresetUpsertSchema.md @@ -0,0 +1,11 @@ +# PresetUpsertSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**value** | [**models::PresetUpsertSchemaValue**](PresetUpsertSchema_value.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/PresetUpsertSchemaValue.md b/typesense_codegen/docs/PresetUpsertSchemaValue.md new file mode 100644 index 0000000..073a07c --- /dev/null +++ b/typesense_codegen/docs/PresetUpsertSchemaValue.md @@ -0,0 +1,12 @@ +# PresetUpsertSchemaValue + +## Enum Variants + +| Name | Description | +|---- | -----| +| MultiSearchSearchesParameter | | +| SearchParameters | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/PresetsApi.md b/typesense_codegen/docs/PresetsApi.md new file mode 100644 index 0000000..4a22b05 --- /dev/null +++ b/typesense_codegen/docs/PresetsApi.md @@ -0,0 +1,130 @@ +# \PresetsApi + +All URIs are relative to *http://localhost:8108* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**delete_preset**](PresetsApi.md#delete_preset) | **DELETE** /presets/{presetId} | Delete a preset. +[**retrieve_all_presets**](PresetsApi.md#retrieve_all_presets) | **GET** /presets | Retrieves all presets. +[**retrieve_preset**](PresetsApi.md#retrieve_preset) | **GET** /presets/{presetId} | Retrieves a preset. +[**upsert_preset**](PresetsApi.md#upsert_preset) | **PUT** /presets/{presetId} | Upserts a preset. + + + +## delete_preset + +> models::PresetDeleteSchema delete_preset(preset_id) +Delete a preset. + +Permanently deletes a preset, given it's name. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**preset_id** | **String** | The ID of the preset to delete. | [required] | + +### Return type + +[**models::PresetDeleteSchema**](PresetDeleteSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_all_presets + +> models::PresetsRetrieveSchema retrieve_all_presets() +Retrieves all presets. + +Retrieve the details of all presets + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**models::PresetsRetrieveSchema**](PresetsRetrieveSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_preset + +> models::PresetSchema retrieve_preset(preset_id) +Retrieves a preset. + +Retrieve the details of a preset, given it's name. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**preset_id** | **String** | The ID of the preset to retrieve. | [required] | + +### Return type + +[**models::PresetSchema**](PresetSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## upsert_preset + +> models::PresetSchema upsert_preset(preset_id, preset_upsert_schema) +Upserts a preset. + +Create or update an existing preset. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**preset_id** | **String** | The name of the preset set to upsert. | [required] | +**preset_upsert_schema** | [**PresetUpsertSchema**](PresetUpsertSchema.md) | The stopwords set to upsert. | [required] | + +### Return type + +[**models::PresetSchema**](PresetSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/typesense_codegen/docs/PresetsRetrieveSchema.md b/typesense_codegen/docs/PresetsRetrieveSchema.md new file mode 100644 index 0000000..6c2ace3 --- /dev/null +++ b/typesense_codegen/docs/PresetsRetrieveSchema.md @@ -0,0 +1,11 @@ +# PresetsRetrieveSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**presets** | [**Vec**](PresetSchema.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SchemaChangeStatus.md b/typesense_codegen/docs/SchemaChangeStatus.md new file mode 100644 index 0000000..5a87798 --- /dev/null +++ b/typesense_codegen/docs/SchemaChangeStatus.md @@ -0,0 +1,13 @@ +# SchemaChangeStatus + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**collection** | Option<**String**> | Name of the collection being modified | [optional] +**validated_docs** | Option<**i32**> | Number of documents that have been validated | [optional] +**altered_docs** | Option<**i32**> | Number of documents that have been altered | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SearchGroupedHit.md b/typesense_codegen/docs/SearchGroupedHit.md index 996a423..1972f65 100644 --- a/typesense_codegen/docs/SearchGroupedHit.md +++ b/typesense_codegen/docs/SearchGroupedHit.md @@ -6,7 +6,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **found** | Option<**i32**> | | [optional] **group_key** | [**Vec**](serde_json::Value.md) | | -**hits** | [**Vec**](SearchResultHit.md) | The documents that matched the search query | +**hits** | [**Vec**](SearchResultHit.md) | The documents that matched the search query | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchOverride.md b/typesense_codegen/docs/SearchOverride.md index 0c0cbfc..1204992 100644 --- a/typesense_codegen/docs/SearchOverride.md +++ b/typesense_codegen/docs/SearchOverride.md @@ -4,11 +4,18 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**rule** | [**crate::models::SearchOverrideRule**](SearchOverrideRule.md) | | -**includes** | Option<[**Vec**](SearchOverrideInclude.md)> | List of document `id`s that should be included in the search results with their corresponding `position`s. | [optional] -**excludes** | Option<[**Vec**](SearchOverrideExclude.md)> | List of document `id`s that should be excluded from the search results. | [optional] +**rule** | [**models::SearchOverrideRule**](SearchOverrideRule.md) | | +**includes** | Option<[**Vec**](SearchOverrideInclude.md)> | List of document `id`s that should be included in the search results with their corresponding `position`s. | [optional] +**excludes** | Option<[**Vec**](SearchOverrideExclude.md)> | List of document `id`s that should be excluded from the search results. | [optional] **filter_by** | Option<**String**> | A filter by clause that is applied to any search query that matches the override rule. | [optional] **remove_matched_tokens** | Option<**bool**> | Indicates whether search query tokens that exist in the override's rule should be removed from the search query. | [optional] +**metadata** | Option<[**serde_json::Value**](.md)> | Return a custom JSON object in the Search API response, when this rule is triggered. This can can be used to display a pre-defined message (eg: a promotion banner) on the front-end when a particular rule is triggered. | [optional] +**sort_by** | Option<**String**> | A sort by clause that is applied to any search query that matches the override rule. | [optional] +**replace_query** | Option<**String**> | Replaces the current search query with this value, when the search query matches the override rule. | [optional] +**filter_curated_hits** | Option<**bool**> | When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. | [optional] +**effective_from_ts** | Option<**i32**> | A Unix timestamp that indicates the date/time from which the override will be active. You can use this to create override rules that start applying from a future point in time. | [optional] +**effective_to_ts** | Option<**i32**> | A Unix timestamp that indicates the date/time until which the override will be active. You can use this to create override rules that stop applying after a period of time. | [optional] +**stop_processing** | Option<**bool**> | When set to true, override processing will stop at the first matching rule. When set to false override processing will continue and multiple override actions will be triggered in sequence. Overrides are processed in the lexical sort order of their id field. Default: true. | [optional] **id** | **String** | | [readonly] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchOverrideDeleteResponse.md b/typesense_codegen/docs/SearchOverrideDeleteResponse.md new file mode 100644 index 0000000..3392bd0 --- /dev/null +++ b/typesense_codegen/docs/SearchOverrideDeleteResponse.md @@ -0,0 +1,11 @@ +# SearchOverrideDeleteResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **String** | The id of the override that was deleted | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SearchOverrideRule.md b/typesense_codegen/docs/SearchOverrideRule.md index f4ac180..2234944 100644 --- a/typesense_codegen/docs/SearchOverrideRule.md +++ b/typesense_codegen/docs/SearchOverrideRule.md @@ -4,8 +4,10 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**query** | **String** | Indicates what search queries should be overridden | -**r#match** | **String** | Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. | +**tags** | Option<**Vec**> | List of tag values to associate with this override rule. | [optional] +**query** | Option<**String**> | Indicates what search queries should be overridden | [optional] +**r#match** | Option<**String**> | Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. | [optional] +**filter_by** | Option<**String**> | Indicates that the override should apply when the filter_by parameter in a search query exactly matches the string specified here (including backticks, spaces, brackets, etc). | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchOverrideSchema.md b/typesense_codegen/docs/SearchOverrideSchema.md index 6aaad22..4da9648 100644 --- a/typesense_codegen/docs/SearchOverrideSchema.md +++ b/typesense_codegen/docs/SearchOverrideSchema.md @@ -4,11 +4,18 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**rule** | [**crate::models::SearchOverrideRule**](SearchOverrideRule.md) | | -**includes** | Option<[**Vec**](SearchOverrideInclude.md)> | List of document `id`s that should be included in the search results with their corresponding `position`s. | [optional] -**excludes** | Option<[**Vec**](SearchOverrideExclude.md)> | List of document `id`s that should be excluded from the search results. | [optional] +**rule** | [**models::SearchOverrideRule**](SearchOverrideRule.md) | | +**includes** | Option<[**Vec**](SearchOverrideInclude.md)> | List of document `id`s that should be included in the search results with their corresponding `position`s. | [optional] +**excludes** | Option<[**Vec**](SearchOverrideExclude.md)> | List of document `id`s that should be excluded from the search results. | [optional] **filter_by** | Option<**String**> | A filter by clause that is applied to any search query that matches the override rule. | [optional] **remove_matched_tokens** | Option<**bool**> | Indicates whether search query tokens that exist in the override's rule should be removed from the search query. | [optional] +**metadata** | Option<[**serde_json::Value**](.md)> | Return a custom JSON object in the Search API response, when this rule is triggered. This can can be used to display a pre-defined message (eg: a promotion banner) on the front-end when a particular rule is triggered. | [optional] +**sort_by** | Option<**String**> | A sort by clause that is applied to any search query that matches the override rule. | [optional] +**replace_query** | Option<**String**> | Replaces the current search query with this value, when the search query matches the override rule. | [optional] +**filter_curated_hits** | Option<**bool**> | When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. | [optional] +**effective_from_ts** | Option<**i32**> | A Unix timestamp that indicates the date/time from which the override will be active. You can use this to create override rules that start applying from a future point in time. | [optional] +**effective_to_ts** | Option<**i32**> | A Unix timestamp that indicates the date/time until which the override will be active. You can use this to create override rules that stop applying after a period of time. | [optional] +**stop_processing** | Option<**bool**> | When set to true, override processing will stop at the first matching rule. When set to false override processing will continue and multiple override actions will be triggered in sequence. Overrides are processed in the lexical sort order of their id field. Default: true. | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchOverridesResponse.md b/typesense_codegen/docs/SearchOverridesResponse.md index 422e1b3..4c3952b 100644 --- a/typesense_codegen/docs/SearchOverridesResponse.md +++ b/typesense_codegen/docs/SearchOverridesResponse.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**overrides** | [**Vec**](SearchOverride.md) | | +**overrides** | [**Vec**](SearchOverride.md) | | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchParameters.md b/typesense_codegen/docs/SearchParameters.md index 740eb30..b6ccf51 100644 --- a/typesense_codegen/docs/SearchParameters.md +++ b/typesense_codegen/docs/SearchParameters.md @@ -4,15 +4,18 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**q** | **String** | The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. | -**query_by** | **String** | A list of `string` fields that should be queried against. Multiple fields are separated with a comma. | +**q** | Option<**String**> | The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. | [optional] +**query_by** | Option<**String**> | A list of `string` fields that should be queried against. Multiple fields are separated with a comma. | [optional] +**nl_query** | Option<**bool**> | Whether to use natural language processing to parse the query. | [optional] +**nl_model_id** | Option<**String**> | The ID of the natural language model to use. | [optional] **query_by_weights** | Option<**String**> | The relative weight to give each `query_by` field when ranking results. This can be used to boost fields in priority, when looking for matches. Multiple fields are separated with a comma. | [optional] **text_match_type** | Option<**String**> | In a multi-field matching context, this parameter determines how the representative text match score of a record is calculated. Possible values are max_score (default) or max_weight. | [optional] **prefix** | Option<**String**> | Boolean field to indicate that the last word in the query should be treated as a prefix, and not as a whole word. This is used for building autocomplete and instant search interfaces. Defaults to true. | [optional] **infix** | Option<**String**> | If infix index is enabled for this field, infix searching can be done on a per-field basis by sending a comma separated string parameter called infix to the search query. This parameter can have 3 values; `off` infix search is disabled, which is default `always` infix search is performed along with regular search `fallback` infix search is performed if regular search does not produce results | [optional] **max_extra_prefix** | Option<**i32**> | There are also 2 parameters that allow you to control the extent of infix searching max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before or after the query that can be present in the token. For example query \"K2100\" has 2 extra symbols in \"6PK2100\". By default, any number of prefixes/suffixes can be present for a match. | [optional] **max_extra_suffix** | Option<**i32**> | There are also 2 parameters that allow you to control the extent of infix searching max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before or after the query that can be present in the token. For example query \"K2100\" has 2 extra symbols in \"6PK2100\". By default, any number of prefixes/suffixes can be present for a match. | [optional] -**filter_by** | Option<**String**> | Filter conditions for refining youropen api validator search results. Separate multiple conditions with &&. | [optional] +**filter_by** | Option<**String**> | Filter conditions for refining your open api validator search results. Separate multiple conditions with &&. | [optional] +**max_filter_by_candidates** | Option<**i32**> | Controls the number of similar words that Typesense considers during fuzzy search on filter_by values. Useful for controlling prefix matches like company_name:Acm*. | [optional] **sort_by** | Option<**String**> | A list of numerical fields and their corresponding sort orders that will be used for ordering your results. Up to 3 sort fields can be specified. The text similarity score is exposed as a special `_text_match` field that you can use in the list of sorting fields. If no `sort_by` parameter is specified, results are sorted by `_text_match:desc,default_sorting_field:desc` | [optional] **facet_by** | Option<**String**> | A list of fields that will be used for faceting your results on. Separate multiple fields with a comma. | [optional] **max_facet_values** | Option<**i32**> | Maximum number of facet values to be returned. | [optional] @@ -20,10 +23,11 @@ Name | Type | Description | Notes **num_typos** | Option<**String**> | The number of typographical errors (1 or 2) that would be tolerated. Default: 2 | [optional] **page** | Option<**i32**> | Results from this specific page number would be fetched. | [optional] **per_page** | Option<**i32**> | Number of results to fetch per page. Default: 10 | [optional] -**limit** | Option<**i32**> | Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. | [optional] +**limit** | Option<**i32**> | Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. | [optional] **offset** | Option<**i32**> | Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. | [optional] **group_by** | Option<**String**> | You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. | [optional] **group_limit** | Option<**i32**> | Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 | [optional] +**group_missing_values** | Option<**bool**> | Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true | [optional] **include_fields** | Option<**String**> | List of fields from the document to include in the search result | [optional] **exclude_fields** | Option<**String**> | List of fields from the document to exclude in the search result | [optional] **highlight_full_fields** | Option<**String**> | List of fields which should be highlighted fully without snippeting | [optional] @@ -31,28 +35,46 @@ Name | Type | Description | Notes **highlight_start_tag** | Option<**String**> | The start tag used for the highlighted snippets. Default: `` | [optional] **highlight_end_tag** | Option<**String**> | The end tag used for the highlighted snippets. Default: `` | [optional] **enable_highlight_v1** | Option<**bool**> | Flag for enabling/disabling the deprecated, old highlight structure in the response. Default: true | [optional][default to true] +**enable_analytics** | Option<**bool**> | Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). | [optional][default to true] **snippet_threshold** | Option<**i32**> | Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 | [optional] +**synonym_sets** | Option<**String**> | List of synonym set names to associate with this search query | [optional] **drop_tokens_threshold** | Option<**i32**> | If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 | [optional] +**drop_tokens_mode** | Option<[**models::DropTokensMode**](DropTokensMode.md)> | | [optional] **typo_tokens_threshold** | Option<**i32**> | If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 | [optional] -**pinned_hits** | Option<**String**> | A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. | [optional] +**enable_typos_for_alpha_numerical_tokens** | Option<**bool**> | Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. | [optional] +**filter_curated_hits** | Option<**bool**> | Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false | [optional] +**enable_synonyms** | Option<**bool**> | If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true | [optional] +**synonym_prefix** | Option<**bool**> | Allow synonym resolution on word prefixes in the query. Default: false | [optional] +**synonym_num_typos** | Option<**i32**> | Allow synonym resolution on typo-corrected words in the query. Default: 0 | [optional] +**pinned_hits** | Option<**String**> | A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. | [optional] **hidden_hits** | Option<**String**> | A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. | [optional] -**highlight_fields** | Option<**String**> | A list of custom fields that must be highlighted even if you don't query for them | [optional] +**override_tags** | Option<**String**> | Comma separated list of tags to trigger the curations rules that match the tags. | [optional] +**highlight_fields** | Option<**String**> | A list of custom fields that must be highlighted even if you don't query for them | [optional] **split_join_tokens** | Option<**String**> | Treat space as typo: search for q=basket ball if q=basketball is not found or vice-versa. Splitting/joining of tokens will only be attempted if the original query produces no results. To always trigger this behavior, set value to `always``. To disable, set value to `off`. Default is `fallback`. | [optional] -**pre_segmented_query** | Option<**bool**> | You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same | [optional] +**pre_segmented_query** | Option<**bool**> | You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same | [optional] **preset** | Option<**String**> | Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. | [optional] -**enable_overrides** | Option<**bool**> | If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false | [optional] -**prioritize_exact_match** | Option<**bool**> | Set this parameter to true to ensure that an exact match is ranked above the others | [optional] +**enable_overrides** | Option<**bool**> | If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false | [optional][default to false] +**prioritize_exact_match** | Option<**bool**> | Set this parameter to true to ensure that an exact match is ranked above the others | [optional][default to true] **max_candidates** | Option<**i32**> | Control the number of words that Typesense considers for typo and prefix searching. | [optional] -**prioritize_token_position** | Option<**bool**> | Make Typesense prioritize documents where the query words appear earlier in the text. | [optional] -**exhaustive_search** | Option<**bool**> | Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). | [optional] -**search_cutoff_ms** | Option<**i32**> | Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. | [optional] +**prioritize_token_position** | Option<**bool**> | Make Typesense prioritize documents where the query words appear earlier in the text. | [optional][default to false] +**prioritize_num_matching_fields** | Option<**bool**> | Make Typesense prioritize documents where the query words appear in more number of fields. | [optional][default to true] +**enable_typos_for_numerical_tokens** | Option<**bool**> | Make Typesense disable typos for numerical tokens. | [optional][default to true] +**exhaustive_search** | Option<**bool**> | Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). | [optional] +**search_cutoff_ms** | Option<**i32**> | Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. | [optional] **use_cache** | Option<**bool**> | Enable server side caching of search query results. By default, caching is disabled. | [optional] -**cache_ttl** | Option<**i32**> | The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. | [optional] -**min_len_1typo** | Option<**i32**> | Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] -**min_len_2typo** | Option<**i32**> | Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] +**cache_ttl** | Option<**i32**> | The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. | [optional] +**min_len_1typo** | Option<**i32**> | Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] +**min_len_2typo** | Option<**i32**> | Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] **vector_query** | Option<**String**> | Vector query expression for fetching documents \"closest\" to a given query/document vector. | [optional] **remote_embedding_timeout_ms** | Option<**i32**> | Timeout (in milliseconds) for fetching remote embeddings. | [optional] **remote_embedding_num_tries** | Option<**i32**> | Number of times to retry fetching remote embeddings. | [optional] +**facet_strategy** | Option<**String**> | Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). | [optional] +**stopwords** | Option<**String**> | Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. | [optional] +**facet_return_parent** | Option<**String**> | Comma separated string of nested facet fields whose parent object should be returned in facet response. | [optional] +**voice_query** | Option<**String**> | The base64 encoded audio file in 16 khz 16-bit WAV format. | [optional] +**conversation** | Option<**bool**> | Enable conversational search. | [optional] +**conversation_model_id** | Option<**String**> | The Id of Conversation Model to be used. | [optional] +**conversation_id** | Option<**String**> | The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchRequestParams.md b/typesense_codegen/docs/SearchRequestParams.md new file mode 100644 index 0000000..57bed91 --- /dev/null +++ b/typesense_codegen/docs/SearchRequestParams.md @@ -0,0 +1,14 @@ +# SearchRequestParams + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**collection_name** | **String** | | +**q** | **String** | | +**per_page** | **i32** | | +**voice_query** | Option<[**models::SearchRequestParamsVoiceQuery**](SearchRequestParams_voice_query.md)> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SearchRequestParamsVoiceQuery.md b/typesense_codegen/docs/SearchRequestParamsVoiceQuery.md new file mode 100644 index 0000000..92e217b --- /dev/null +++ b/typesense_codegen/docs/SearchRequestParamsVoiceQuery.md @@ -0,0 +1,11 @@ +# SearchRequestParamsVoiceQuery + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**transcribed_query** | Option<**String**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SearchResult.md b/typesense_codegen/docs/SearchResult.md index 857f5ea..0f3bb0f 100644 --- a/typesense_codegen/docs/SearchResult.md +++ b/typesense_codegen/docs/SearchResult.md @@ -4,15 +4,18 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**facet_counts** | Option<[**Vec**](FacetCounts.md)> | | [optional] +**facet_counts** | Option<[**Vec**](FacetCounts.md)> | | [optional] **found** | Option<**i32**> | The number of documents found | [optional] +**found_docs** | Option<**i32**> | | [optional] **search_time_ms** | Option<**i32**> | The number of milliseconds the search took | [optional] **out_of** | Option<**i32**> | The total number of documents in the collection | [optional] **search_cutoff** | Option<**bool**> | Whether the search was cut off | [optional] **page** | Option<**i32**> | The search result page number | [optional] -**grouped_hits** | Option<[**Vec**](SearchGroupedHit.md)> | | [optional] -**hits** | Option<[**Vec**](SearchResultHit.md)> | The documents that matched the search query | [optional] -**request_params** | Option<[**crate::models::SearchResultRequestParams**](SearchResult_request_params.md)> | | [optional] +**grouped_hits** | Option<[**Vec**](SearchGroupedHit.md)> | | [optional] +**hits** | Option<[**Vec**](SearchResultHit.md)> | The documents that matched the search query | [optional] +**request_params** | Option<[**models::SearchRequestParams**](SearchRequestParams.md)> | | [optional] +**conversation** | Option<[**models::SearchResultConversation**](SearchResultConversation.md)> | | [optional] +**union_request_params** | Option<[**Vec**](SearchRequestParams.md)> | Returned only for union query response. | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchResultConversation.md b/typesense_codegen/docs/SearchResultConversation.md new file mode 100644 index 0000000..2428ba7 --- /dev/null +++ b/typesense_codegen/docs/SearchResultConversation.md @@ -0,0 +1,14 @@ +# SearchResultConversation + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**answer** | **String** | | +**conversation_history** | [**Vec**](serde_json::Value.md) | | +**conversation_id** | **String** | | +**query** | **String** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SearchResultHit.md b/typesense_codegen/docs/SearchResultHit.md index 3b9d460..28d58a5 100644 --- a/typesense_codegen/docs/SearchResultHit.md +++ b/typesense_codegen/docs/SearchResultHit.md @@ -4,12 +4,15 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**highlights** | Option<[**Vec**](SearchHighlight.md)> | (Deprecated) Contains highlighted portions of the search fields | [optional] -**highlight** | Option<[**::std::collections::HashMap**](serde_json::Value.md)> | Highlighted version of the matching document | [optional] -**document** | Option<[**::std::collections::HashMap**](serde_json::Value.md)> | Can be any key-value pair | [optional] +**highlights** | Option<[**Vec**](SearchHighlight.md)> | (Deprecated) Contains highlighted portions of the search fields | [optional] +**highlight** | Option<[**std::collections::HashMap**](serde_json::Value.md)> | Highlighted version of the matching document | [optional] +**document** | Option<[**std::collections::HashMap**](serde_json::Value.md)> | Can be any key-value pair | [optional] **text_match** | Option<**i64**> | | [optional] -**geo_distance_meters** | Option<**::std::collections::HashMap**> | Can be any key-value pair | [optional] +**text_match_info** | Option<[**models::SearchResultHitTextMatchInfo**](SearchResultHit_text_match_info.md)> | | [optional] +**geo_distance_meters** | Option<**std::collections::HashMap**> | Can be any key-value pair | [optional] **vector_distance** | Option<**f32**> | Distance between the query vector and matching document's vector value | [optional] +**hybrid_search_info** | Option<[**models::SearchResultHitHybridSearchInfo**](SearchResultHit_hybrid_search_info.md)> | | [optional] +**search_index** | Option<**i32**> | Returned only for union query response. Indicates the index of the query which this document matched to. | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchResultHitHybridSearchInfo.md b/typesense_codegen/docs/SearchResultHitHybridSearchInfo.md new file mode 100644 index 0000000..99126fa --- /dev/null +++ b/typesense_codegen/docs/SearchResultHitHybridSearchInfo.md @@ -0,0 +1,11 @@ +# SearchResultHitHybridSearchInfo + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**rank_fusion_score** | Option<**f32**> | Combined score from rank fusion of text and vector search | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SearchResultHitTextMatchInfo.md b/typesense_codegen/docs/SearchResultHitTextMatchInfo.md new file mode 100644 index 0000000..21faffa --- /dev/null +++ b/typesense_codegen/docs/SearchResultHitTextMatchInfo.md @@ -0,0 +1,17 @@ +# SearchResultHitTextMatchInfo + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**best_field_score** | Option<**String**> | | [optional] +**best_field_weight** | Option<**i32**> | | [optional] +**fields_matched** | Option<**i32**> | | [optional] +**num_tokens_dropped** | Option<**i64**> | | [optional] +**score** | Option<**String**> | | [optional] +**tokens_matched** | Option<**i32**> | | [optional] +**typo_prefix_score** | Option<**i32**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SearchResultRequestParams.md b/typesense_codegen/docs/SearchResultRequestParams.md index 2ba855f..9eeb27e 100644 --- a/typesense_codegen/docs/SearchResultRequestParams.md +++ b/typesense_codegen/docs/SearchResultRequestParams.md @@ -7,6 +7,7 @@ Name | Type | Description | Notes **collection_name** | **String** | | **q** | **String** | | **per_page** | **i32** | | +**voice_query** | Option<[**models::SearchResultRequestParamsVoiceQuery**](SearchResult_request_params_voice_query.md)> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchResultRequestParamsVoiceQuery.md b/typesense_codegen/docs/SearchResultRequestParamsVoiceQuery.md new file mode 100644 index 0000000..e7293e7 --- /dev/null +++ b/typesense_codegen/docs/SearchResultRequestParamsVoiceQuery.md @@ -0,0 +1,11 @@ +# SearchResultRequestParamsVoiceQuery + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**transcribed_query** | Option<**String**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SearchSynonym.md b/typesense_codegen/docs/SearchSynonym.md index 4061c2b..70c9964 100644 --- a/typesense_codegen/docs/SearchSynonym.md +++ b/typesense_codegen/docs/SearchSynonym.md @@ -6,6 +6,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **root** | Option<**String**> | For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. | [optional] **synonyms** | **Vec** | Array of words that should be considered as synonyms. | +**locale** | Option<**String**> | Locale for the synonym, leave blank to use the standard tokenizer. | [optional] +**symbols_to_index** | Option<**Vec**> | By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is. | [optional] **id** | **String** | | [readonly] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchSynonymDeleteResponse.md b/typesense_codegen/docs/SearchSynonymDeleteResponse.md new file mode 100644 index 0000000..76ab57c --- /dev/null +++ b/typesense_codegen/docs/SearchSynonymDeleteResponse.md @@ -0,0 +1,11 @@ +# SearchSynonymDeleteResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **String** | The id of the synonym that was deleted | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SearchSynonymSchema.md b/typesense_codegen/docs/SearchSynonymSchema.md index bcb5956..bac8165 100644 --- a/typesense_codegen/docs/SearchSynonymSchema.md +++ b/typesense_codegen/docs/SearchSynonymSchema.md @@ -6,6 +6,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **root** | Option<**String**> | For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. | [optional] **synonyms** | **Vec** | Array of words that should be considered as synonyms. | +**locale** | Option<**String**> | Locale for the synonym, leave blank to use the standard tokenizer. | [optional] +**symbols_to_index** | Option<**Vec**> | By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is. | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchSynonymsResponse.md b/typesense_codegen/docs/SearchSynonymsResponse.md index f88f04c..6b946ee 100644 --- a/typesense_codegen/docs/SearchSynonymsResponse.md +++ b/typesense_codegen/docs/SearchSynonymsResponse.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**synonyms** | [**Vec**](SearchSynonym.md) | | +**synonyms** | [**Vec**](SearchSynonym.md) | | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/StemmingApi.md b/typesense_codegen/docs/StemmingApi.md new file mode 100644 index 0000000..be81156 --- /dev/null +++ b/typesense_codegen/docs/StemmingApi.md @@ -0,0 +1,99 @@ +# \StemmingApi + +All URIs are relative to *http://localhost:8108* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**get_stemming_dictionary**](StemmingApi.md#get_stemming_dictionary) | **GET** /stemming/dictionaries/{dictionaryId} | Retrieve a stemming dictionary +[**import_stemming_dictionary**](StemmingApi.md#import_stemming_dictionary) | **POST** /stemming/dictionaries/import | Import a stemming dictionary +[**list_stemming_dictionaries**](StemmingApi.md#list_stemming_dictionaries) | **GET** /stemming/dictionaries | List all stemming dictionaries + + + +## get_stemming_dictionary + +> models::StemmingDictionary get_stemming_dictionary(dictionary_id) +Retrieve a stemming dictionary + +Fetch details of a specific stemming dictionary. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**dictionary_id** | **String** | The ID of the dictionary to retrieve | [required] | + +### Return type + +[**models::StemmingDictionary**](StemmingDictionary.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## import_stemming_dictionary + +> String import_stemming_dictionary(id, body) +Import a stemming dictionary + +Upload a JSONL file containing word mappings to create or update a stemming dictionary. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**id** | **String** | The ID to assign to the dictionary | [required] | +**body** | **String** | The JSONL file containing word mappings | [required] | + +### Return type + +**String** + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/octet-stream, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## list_stemming_dictionaries + +> models::ListStemmingDictionaries200Response list_stemming_dictionaries() +List all stemming dictionaries + +Retrieve a list of all available stemming dictionaries. + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**models::ListStemmingDictionaries200Response**](listStemmingDictionaries_200_response.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/typesense_codegen/docs/StemmingDictionary.md b/typesense_codegen/docs/StemmingDictionary.md new file mode 100644 index 0000000..4aa3a3e --- /dev/null +++ b/typesense_codegen/docs/StemmingDictionary.md @@ -0,0 +1,12 @@ +# StemmingDictionary + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **String** | Unique identifier for the dictionary | +**words** | [**Vec**](StemmingDictionary_words_inner.md) | List of word mappings in the dictionary | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/StemmingDictionaryWordsInner.md b/typesense_codegen/docs/StemmingDictionaryWordsInner.md new file mode 100644 index 0000000..7d9a515 --- /dev/null +++ b/typesense_codegen/docs/StemmingDictionaryWordsInner.md @@ -0,0 +1,12 @@ +# StemmingDictionaryWordsInner + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**word** | **String** | The word form to be stemmed | +**root** | **String** | The root form of the word | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/StopwordsApi.md b/typesense_codegen/docs/StopwordsApi.md new file mode 100644 index 0000000..8166db2 --- /dev/null +++ b/typesense_codegen/docs/StopwordsApi.md @@ -0,0 +1,130 @@ +# \StopwordsApi + +All URIs are relative to *http://localhost:8108* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**delete_stopwords_set**](StopwordsApi.md#delete_stopwords_set) | **DELETE** /stopwords/{setId} | Delete a stopwords set. +[**retrieve_stopwords_set**](StopwordsApi.md#retrieve_stopwords_set) | **GET** /stopwords/{setId} | Retrieves a stopwords set. +[**retrieve_stopwords_sets**](StopwordsApi.md#retrieve_stopwords_sets) | **GET** /stopwords | Retrieves all stopwords sets. +[**upsert_stopwords_set**](StopwordsApi.md#upsert_stopwords_set) | **PUT** /stopwords/{setId} | Upserts a stopwords set. + + + +## delete_stopwords_set + +> models::DeleteStopwordsSet200Response delete_stopwords_set(set_id) +Delete a stopwords set. + +Permanently deletes a stopwords set, given it's name. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**set_id** | **String** | The ID of the stopwords set to delete. | [required] | + +### Return type + +[**models::DeleteStopwordsSet200Response**](deleteStopwordsSet_200_response.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_stopwords_set + +> models::StopwordsSetRetrieveSchema retrieve_stopwords_set(set_id) +Retrieves a stopwords set. + +Retrieve the details of a stopwords set, given it's name. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**set_id** | **String** | The ID of the stopwords set to retrieve. | [required] | + +### Return type + +[**models::StopwordsSetRetrieveSchema**](StopwordsSetRetrieveSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_stopwords_sets + +> models::StopwordsSetsRetrieveAllSchema retrieve_stopwords_sets() +Retrieves all stopwords sets. + +Retrieve the details of all stopwords sets + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**models::StopwordsSetsRetrieveAllSchema**](StopwordsSetsRetrieveAllSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## upsert_stopwords_set + +> models::StopwordsSetSchema upsert_stopwords_set(set_id, stopwords_set_upsert_schema) +Upserts a stopwords set. + +When an analytics rule is created, we give it a name and describe the type, the source collections and the destination collection. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**set_id** | **String** | The ID of the stopwords set to upsert. | [required] | +**stopwords_set_upsert_schema** | [**StopwordsSetUpsertSchema**](StopwordsSetUpsertSchema.md) | The stopwords set to upsert. | [required] | + +### Return type + +[**models::StopwordsSetSchema**](StopwordsSetSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/typesense_codegen/docs/StopwordsSetRetrieveSchema.md b/typesense_codegen/docs/StopwordsSetRetrieveSchema.md new file mode 100644 index 0000000..284a9ed --- /dev/null +++ b/typesense_codegen/docs/StopwordsSetRetrieveSchema.md @@ -0,0 +1,11 @@ +# StopwordsSetRetrieveSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**stopwords** | [**models::StopwordsSetSchema**](StopwordsSetSchema.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/StopwordsSetSchema.md b/typesense_codegen/docs/StopwordsSetSchema.md new file mode 100644 index 0000000..97d49dc --- /dev/null +++ b/typesense_codegen/docs/StopwordsSetSchema.md @@ -0,0 +1,13 @@ +# StopwordsSetSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **String** | | +**stopwords** | **Vec** | | +**locale** | Option<**String**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/StopwordsSetUpsertSchema.md b/typesense_codegen/docs/StopwordsSetUpsertSchema.md new file mode 100644 index 0000000..29082d9 --- /dev/null +++ b/typesense_codegen/docs/StopwordsSetUpsertSchema.md @@ -0,0 +1,12 @@ +# StopwordsSetUpsertSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**stopwords** | **Vec** | | +**locale** | Option<**String**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/StopwordsSetsRetrieveAllSchema.md b/typesense_codegen/docs/StopwordsSetsRetrieveAllSchema.md new file mode 100644 index 0000000..074531b --- /dev/null +++ b/typesense_codegen/docs/StopwordsSetsRetrieveAllSchema.md @@ -0,0 +1,11 @@ +# StopwordsSetsRetrieveAllSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**stopwords** | [**Vec**](StopwordsSetSchema.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SynonymItemSchema.md b/typesense_codegen/docs/SynonymItemSchema.md new file mode 100644 index 0000000..1e842d2 --- /dev/null +++ b/typesense_codegen/docs/SynonymItemSchema.md @@ -0,0 +1,15 @@ +# SynonymItemSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **String** | Unique identifier for the synonym item | +**synonyms** | **Vec** | Array of words that should be considered as synonyms | +**root** | Option<**String**> | For 1-way synonyms, indicates the root word that words in the synonyms parameter map to | [optional] +**locale** | Option<**String**> | Locale for the synonym, leave blank to use the standard tokenizer | [optional] +**symbols_to_index** | Option<**Vec**> | By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SynonymSetCreateSchema.md b/typesense_codegen/docs/SynonymSetCreateSchema.md new file mode 100644 index 0000000..d139f56 --- /dev/null +++ b/typesense_codegen/docs/SynonymSetCreateSchema.md @@ -0,0 +1,11 @@ +# SynonymSetCreateSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**items** | [**Vec**](SynonymItemSchema.md) | Array of synonym items | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SynonymSetDeleteSchema.md b/typesense_codegen/docs/SynonymSetDeleteSchema.md new file mode 100644 index 0000000..dfb8d24 --- /dev/null +++ b/typesense_codegen/docs/SynonymSetDeleteSchema.md @@ -0,0 +1,11 @@ +# SynonymSetDeleteSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | Name of the deleted synonym set | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SynonymSetSchema.md b/typesense_codegen/docs/SynonymSetSchema.md new file mode 100644 index 0000000..d859838 --- /dev/null +++ b/typesense_codegen/docs/SynonymSetSchema.md @@ -0,0 +1,12 @@ +# SynonymSetSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**items** | [**Vec**](SynonymItemSchema.md) | Array of synonym items | +**name** | **String** | Name of the synonym set | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SynonymSetsRetrieveSchema.md b/typesense_codegen/docs/SynonymSetsRetrieveSchema.md new file mode 100644 index 0000000..f18b08a --- /dev/null +++ b/typesense_codegen/docs/SynonymSetsRetrieveSchema.md @@ -0,0 +1,11 @@ +# SynonymSetsRetrieveSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**synonym_sets** | [**Vec**](SynonymSetSchema.md) | Array of synonym sets | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SynonymsApi.md b/typesense_codegen/docs/SynonymsApi.md new file mode 100644 index 0000000..d00c016 --- /dev/null +++ b/typesense_codegen/docs/SynonymsApi.md @@ -0,0 +1,130 @@ +# \SynonymsApi + +All URIs are relative to *http://localhost:8108* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**delete_synonym_set**](SynonymsApi.md#delete_synonym_set) | **DELETE** /synonym_sets/{synonymSetName} | Delete a synonym set +[**retrieve_synonym_set**](SynonymsApi.md#retrieve_synonym_set) | **GET** /synonym_sets/{synonymSetName} | Retrieve a synonym set +[**retrieve_synonym_sets**](SynonymsApi.md#retrieve_synonym_sets) | **GET** /synonym_sets | List all synonym sets +[**upsert_synonym_set**](SynonymsApi.md#upsert_synonym_set) | **PUT** /synonym_sets/{synonymSetName} | Create or update a synonym set + + + +## delete_synonym_set + +> models::SynonymSetDeleteSchema delete_synonym_set(synonym_set_name) +Delete a synonym set + +Delete a specific synonym set by its name + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**synonym_set_name** | **String** | The name of the synonym set to delete | [required] | + +### Return type + +[**models::SynonymSetDeleteSchema**](SynonymSetDeleteSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_synonym_set + +> models::SynonymSetCreateSchema retrieve_synonym_set(synonym_set_name) +Retrieve a synonym set + +Retrieve a specific synonym set by its name + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**synonym_set_name** | **String** | The name of the synonym set to retrieve | [required] | + +### Return type + +[**models::SynonymSetCreateSchema**](SynonymSetCreateSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_synonym_sets + +> Vec retrieve_synonym_sets() +List all synonym sets + +Retrieve all synonym sets + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**Vec**](SynonymSetSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## upsert_synonym_set + +> models::SynonymSetSchema upsert_synonym_set(synonym_set_name, synonym_set_create_schema) +Create or update a synonym set + +Create or update a synonym set with the given name + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**synonym_set_name** | **String** | The name of the synonym set to create/update | [required] | +**synonym_set_create_schema** | [**SynonymSetCreateSchema**](SynonymSetCreateSchema.md) | The synonym set to be created/updated | [required] | + +### Return type + +[**models::SynonymSetSchema**](SynonymSetSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/typesense_codegen/docs/ToggleSlowRequestLogRequest.md b/typesense_codegen/docs/ToggleSlowRequestLogRequest.md new file mode 100644 index 0000000..5e238c6 --- /dev/null +++ b/typesense_codegen/docs/ToggleSlowRequestLogRequest.md @@ -0,0 +1,11 @@ +# ToggleSlowRequestLogRequest + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**log_slow_requests_time_ms** | **i32** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/UpdateDocumentsParameters.md b/typesense_codegen/docs/UpdateDocumentsParameters.md new file mode 100644 index 0000000..31eef40 --- /dev/null +++ b/typesense_codegen/docs/UpdateDocumentsParameters.md @@ -0,0 +1,11 @@ +# UpdateDocumentsParameters + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**filter_by** | Option<**String**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/VoiceQueryModelCollectionConfig.md b/typesense_codegen/docs/VoiceQueryModelCollectionConfig.md new file mode 100644 index 0000000..24b0aa9 --- /dev/null +++ b/typesense_codegen/docs/VoiceQueryModelCollectionConfig.md @@ -0,0 +1,11 @@ +# VoiceQueryModelCollectionConfig + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**model_name** | Option<**String**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/src/apis/analytics_api.rs b/typesense_codegen/src/apis/analytics_api.rs index 04d5c87..b4a672d 100644 --- a/typesense_codegen/src/apis/analytics_api.rs +++ b/typesense_codegen/src/apis/analytics_api.rs @@ -3,19 +3,85 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ -use super::{Error, configuration}; -use crate::apis::ResponseContent; + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + +/// struct for passing parameters to the method [`create_analytics_event`] +#[derive(Clone, Debug)] +pub struct CreateAnalyticsEventParams { + /// The analytics event to be created + pub analytics_event: models::AnalyticsEvent +} + +/// struct for passing parameters to the method [`create_analytics_rule`] +#[derive(Clone, Debug)] +pub struct CreateAnalyticsRuleParams { + /// The analytics rule(s) to be created + pub create_analytics_rule_request: models::CreateAnalyticsRuleRequest +} + +/// struct for passing parameters to the method [`delete_analytics_rule`] +#[derive(Clone, Debug)] +pub struct DeleteAnalyticsRuleParams { + /// The name of the analytics rule to delete + pub rule_name: String +} + +/// struct for passing parameters to the method [`get_analytics_events`] +#[derive(Clone, Debug)] +pub struct GetAnalyticsEventsParams { + pub user_id: String, + /// Analytics rule name + pub name: String, + /// Number of events to return (max 1000) + pub n: i32 +} + +/// struct for passing parameters to the method [`retrieve_analytics_rule`] +#[derive(Clone, Debug)] +pub struct RetrieveAnalyticsRuleParams { + /// The name of the analytics rule to retrieve + pub rule_name: String +} + +/// struct for passing parameters to the method [`retrieve_analytics_rules`] +#[derive(Clone, Debug)] +pub struct RetrieveAnalyticsRulesParams { + /// Filter rules by rule_tag + pub rule_tag: Option +} + +/// struct for passing parameters to the method [`upsert_analytics_rule`] +#[derive(Clone, Debug)] +pub struct UpsertAnalyticsRuleParams { + /// The name of the analytics rule to upsert + pub rule_name: String, + /// The Analytics rule to be upserted + pub analytics_rule_update: models::AnalyticsRuleUpdate +} + + +/// struct for typed errors of method [`create_analytics_event`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum CreateAnalyticsEventError { + Status400(models::ApiResponse), + UnknownValue(serde_json::Value), +} /// struct for typed errors of method [`create_analytics_rule`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum CreateAnalyticsRuleError { - Status400(crate::models::ApiResponse), + Status400(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -23,7 +89,29 @@ pub enum CreateAnalyticsRuleError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum DeleteAnalyticsRuleError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`flush_analytics`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum FlushAnalyticsError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_analytics_events`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetAnalyticsEventsError { + Status400(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_analytics_status`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetAnalyticsStatusError { UnknownValue(serde_json::Value), } @@ -31,7 +119,7 @@ pub enum DeleteAnalyticsRuleError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum RetrieveAnalyticsRuleError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -42,198 +130,408 @@ pub enum RetrieveAnalyticsRulesError { UnknownValue(serde_json::Value), } -/// When an analytics rule is created, we give it a name and describe the type, the source collections and the destination collection. -pub async fn create_analytics_rule( - configuration: &configuration::Configuration, - analytics_rule_schema: crate::models::AnalyticsRuleSchema, -) -> Result> { - let local_var_configuration = configuration; +/// struct for typed errors of method [`upsert_analytics_rule`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum UpsertAnalyticsRuleError { + Status400(models::ApiResponse), + UnknownValue(serde_json::Value), +} + - let local_var_client = &local_var_configuration.client; +/// Submit a single analytics event. The event must correspond to an existing analytics rule by name. +pub async fn create_analytics_event(configuration: &configuration::Configuration, params: CreateAnalyticsEventParams) -> Result> { - let local_var_uri_str = format!("{}/analytics/rules", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); + let uri_str = format!("{}/analytics/events", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - local_var_req_builder = local_var_req_builder.json(&analytics_rule_schema); + req_builder = req_builder.json(¶ms.analytics_event); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; +/// Create one or more analytics rules. You can send a single rule object or an array of rule objects. +pub async fn create_analytics_rule(configuration: &configuration::Configuration, params: CreateAnalyticsRuleParams) -> Result> { - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + let uri_str = format!("{}/analytics/rules", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - Err(Error::ResponseError(local_var_error)) + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.create_analytics_rule_request); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CreateAnalyticsRule200Response`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CreateAnalyticsRule200Response`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Permanently deletes an analytics rule, given it's name -pub async fn delete_analytics_rule( - configuration: &configuration::Configuration, - rule_name: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/analytics/rules/{ruleName}", - local_var_configuration.base_path, - ruleName = crate::apis::urlencode(rule_name) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), +pub async fn delete_analytics_rule(configuration: &configuration::Configuration, params: DeleteAnalyticsRuleParams) -> Result> { + + let uri_str = format!("{}/analytics/rules/{ruleName}", configuration.base_path, ruleName=crate::apis::urlencode(params.rule_name)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsRule`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsRule`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Triggers a flush of analytics data to persistent storage. +pub async fn flush_analytics(configuration: &configuration::Configuration) -> Result> { - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + let uri_str = format!("{}/analytics/flush", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - Err(Error::ResponseError(local_var_error)) + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } -/// Retrieve the details of an analytics rule, given it's name -pub async fn retrieve_analytics_rule( - configuration: &configuration::Configuration, - rule_name: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/analytics/rules/{ruleName}", - local_var_configuration.base_path, - ruleName = crate::apis::urlencode(rule_name) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), +/// Retrieve the most recent events for a user and rule. +pub async fn get_analytics_events(configuration: &configuration::Configuration, params: GetAnalyticsEventsParams) -> Result> { + + let uri_str = format!("{}/analytics/events", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + req_builder = req_builder.query(&[("user_id", ¶ms.user_id.to_string())]); + req_builder = req_builder.query(&[("name", ¶ms.name.to_string())]); + req_builder = req_builder.query(&[("n", ¶ms.n.to_string())]); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsEventsResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsEventsResponse`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; +/// Returns sizes of internal analytics buffers and queues. +pub async fn get_analytics_status(configuration: &configuration::Configuration) -> Result> { - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, + let uri_str = format!("{}/analytics/status", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - Err(Error::ResponseError(local_var_error)) + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsStatus`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsStatus`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } -/// Retrieve the details of all analytics rules -pub async fn retrieve_analytics_rules( - configuration: &configuration::Configuration, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; +/// Retrieve the details of an analytics rule, given it's name +pub async fn retrieve_analytics_rule(configuration: &configuration::Configuration, params: RetrieveAnalyticsRuleParams) -> Result> { - let local_var_uri_str = format!("{}/analytics/rules", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + let uri_str = format!("{}/analytics/rules/{ruleName}", configuration.base_path, ruleName=crate::apis::urlencode(params.rule_name)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsRule`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsRule`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Retrieve all analytics rules. Use the optional rule_tag filter to narrow down results. +pub async fn retrieve_analytics_rules(configuration: &configuration::Configuration, params: RetrieveAnalyticsRulesParams) -> Result, Error> { - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + let uri_str = format!("{}/analytics/rules", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + if let Some(ref param_value) = params.rule_tag { + req_builder = req_builder.query(&[("rule_tag", ¶m_value.to_string())]); + } + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec<models::AnalyticsRule>`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec<models::AnalyticsRule>`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Upserts an analytics rule with the given name. +pub async fn upsert_analytics_rule(configuration: &configuration::Configuration, params: UpsertAnalyticsRuleParams) -> Result> { + + let uri_str = format!("{}/analytics/rules/{ruleName}", configuration.base_path, ruleName=crate::apis::urlencode(params.rule_name)); + let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - Err(Error::ResponseError(local_var_error)) + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.analytics_rule_update); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsRule`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsRule`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } + diff --git a/typesense_codegen/src/apis/collections_api.rs b/typesense_codegen/src/apis/collections_api.rs index 000dc71..9ee7a2d 100644 --- a/typesense_codegen/src/apis/collections_api.rs +++ b/typesense_codegen/src/apis/collections_api.rs @@ -3,20 +3,85 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ -use super::{Error, configuration}; -use crate::apis::ResponseContent; + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + +/// struct for passing parameters to the method [`create_collection`] +#[derive(Clone, Debug)] +pub struct CreateCollectionParams { + /// The collection object to be created + pub collection_schema: models::CollectionSchema +} + +/// struct for passing parameters to the method [`delete_alias`] +#[derive(Clone, Debug)] +pub struct DeleteAliasParams { + /// The name of the alias to delete + pub alias_name: String +} + +/// struct for passing parameters to the method [`delete_collection`] +#[derive(Clone, Debug)] +pub struct DeleteCollectionParams { + /// The name of the collection to delete + pub collection_name: String +} + +/// struct for passing parameters to the method [`get_alias`] +#[derive(Clone, Debug)] +pub struct GetAliasParams { + /// The name of the alias to retrieve + pub alias_name: String +} + +/// struct for passing parameters to the method [`get_collection`] +#[derive(Clone, Debug)] +pub struct GetCollectionParams { + /// The name of the collection to retrieve + pub collection_name: String +} + +/// struct for passing parameters to the method [`get_collections`] +#[derive(Clone, Debug)] +pub struct GetCollectionsParams { + pub exclude_fields: Option, + pub limit: Option, + pub offset: Option +} + +/// struct for passing parameters to the method [`update_collection`] +#[derive(Clone, Debug)] +pub struct UpdateCollectionParams { + /// The name of the collection to update + pub collection_name: String, + /// The document object with fields to be updated + pub collection_update_schema: models::CollectionUpdateSchema +} + +/// struct for passing parameters to the method [`upsert_alias`] +#[derive(Clone, Debug)] +pub struct UpsertAliasParams { + /// The name of the alias to create/update + pub alias_name: String, + /// Collection alias to be created/updated + pub collection_alias_schema: Option +} + /// struct for typed errors of method [`create_collection`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum CreateCollectionError { - Status400(crate::models::ApiResponse), - Status409(crate::models::ApiResponse), + Status400(models::ApiResponse), + Status409(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -24,7 +89,7 @@ pub enum CreateCollectionError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum DeleteAliasError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -32,7 +97,7 @@ pub enum DeleteAliasError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum DeleteCollectionError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -40,7 +105,7 @@ pub enum DeleteCollectionError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum GetAliasError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -55,7 +120,7 @@ pub enum GetAliasesError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum GetCollectionError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -70,8 +135,8 @@ pub enum GetCollectionsError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum UpdateCollectionError { - Status400(crate::models::ApiResponse), - Status404(crate::models::ApiResponse), + Status400(models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -79,455 +144,407 @@ pub enum UpdateCollectionError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum UpsertAliasError { - Status400(crate::models::ApiResponse), - Status404(crate::models::ApiResponse), + Status400(models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } -/// When a collection is created, we give it a name and describe the fields that will be indexed from the documents added to the collection. -pub async fn create_collection( - configuration: &configuration::Configuration, - collection_schema: crate::models::CollectionSchema, -) -> Result> { - let local_var_configuration = configuration; - let local_var_client = &local_var_configuration.client; +/// When a collection is created, we give it a name and describe the fields that will be indexed from the documents added to the collection. +pub async fn create_collection(configuration: &configuration::Configuration, params: CreateCollectionParams) -> Result> { - let local_var_uri_str = format!("{}/collections", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); + let uri_str = format!("{}/collections", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - local_var_req_builder = local_var_req_builder.json(&collection_schema); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + req_builder = req_builder.json(¶ms.collection_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionResponse`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } -pub async fn delete_alias( - configuration: &configuration::Configuration, - alias_name: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/aliases/{aliasName}", - local_var_configuration.base_path, - aliasName = crate::apis::urlencode(alias_name) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); +pub async fn delete_alias(configuration: &configuration::Configuration, params: DeleteAliasParams) -> Result> { + + let uri_str = format!("{}/aliases/{aliasName}", configuration.base_path, aliasName=crate::apis::urlencode(params.alias_name)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionAlias`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAlias`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Permanently drops a collection. This action cannot be undone. For large collections, this might have an impact on read latencies. -pub async fn delete_collection( - configuration: &configuration::Configuration, - collection_name: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); +pub async fn delete_collection(configuration: &configuration::Configuration, params: DeleteCollectionParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionResponse`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Find out which collection an alias points to by fetching it -pub async fn get_alias( - configuration: &configuration::Configuration, - alias_name: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/aliases/{aliasName}", - local_var_configuration.base_path, - aliasName = crate::apis::urlencode(alias_name) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); +pub async fn get_alias(configuration: &configuration::Configuration, params: GetAliasParams) -> Result> { + + let uri_str = format!("{}/aliases/{aliasName}", configuration.base_path, aliasName=crate::apis::urlencode(params.alias_name)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionAlias`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAlias`")))), + } } else { - let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// List all aliases and the corresponding collections that they map to. -pub async fn get_aliases( - configuration: &configuration::Configuration, -) -> Result> { - let local_var_configuration = configuration; +pub async fn get_aliases(configuration: &configuration::Configuration) -> Result> { - let local_var_client = &local_var_configuration.client; + let uri_str = format!("{}/aliases", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - let local_var_uri_str = format!("{}/aliases", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionAliasesResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAliasesResponse`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Retrieve the details of a collection, given its name. -pub async fn get_collection( - configuration: &configuration::Configuration, - collection_name: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); +pub async fn get_collection(configuration: &configuration::Configuration, params: GetCollectionParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionResponse`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Returns a summary of all your collections. The collections are returned sorted by creation date, with the most recent collections appearing first. -pub async fn get_collections( - configuration: &configuration::Configuration, -) -> Result, Error> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; +pub async fn get_collections(configuration: &configuration::Configuration, params: GetCollectionsParams) -> Result, Error> { - let local_var_uri_str = format!("{}/collections", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + let uri_str = format!("{}/collections", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref param_value) = params.exclude_fields { + req_builder = req_builder.query(&[("exclude_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.limit { + req_builder = req_builder.query(&[("limit", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.offset { + req_builder = req_builder.query(&[("offset", ¶m_value.to_string())]); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec<models::CollectionResponse>`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec<models::CollectionResponse>`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Update a collection's schema to modify the fields and their types. -pub async fn update_collection( - configuration: &configuration::Configuration, - collection_name: &str, - collection_update_schema: crate::models::CollectionUpdateSchema, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::PATCH, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); +pub async fn update_collection(configuration: &configuration::Configuration, params: UpdateCollectionParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); + let mut req_builder = configuration.client.request(reqwest::Method::PATCH, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - local_var_req_builder = local_var_req_builder.json(&collection_update_schema); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + req_builder = req_builder.json(¶ms.collection_update_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionUpdateSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionUpdateSchema`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Create or update a collection alias. An alias is a virtual collection name that points to a real collection. If you're familiar with symbolic links on Linux, it's very similar to that. Aliases are useful when you want to reindex your data in the background on a new collection and switch your application to it without any changes to your code. -pub async fn upsert_alias( - configuration: &configuration::Configuration, - alias_name: &str, - collection_alias_schema: Option, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/aliases/{aliasName}", - local_var_configuration.base_path, - aliasName = crate::apis::urlencode(alias_name) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::PUT, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); +pub async fn upsert_alias(configuration: &configuration::Configuration, params: UpsertAliasParams) -> Result> { + + let uri_str = format!("{}/aliases/{aliasName}", configuration.base_path, aliasName=crate::apis::urlencode(params.alias_name)); + let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - local_var_req_builder = local_var_req_builder.json(&collection_alias_schema); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + req_builder = req_builder.json(¶ms.collection_alias_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionAlias`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAlias`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } + diff --git a/typesense_codegen/src/apis/configuration.rs b/typesense_codegen/src/apis/configuration.rs index f5e29b4..d433e31 100644 --- a/typesense_codegen/src/apis/configuration.rs +++ b/typesense_codegen/src/apis/configuration.rs @@ -3,21 +3,27 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 28.0 * * Generated by: https://openapi-generator.tech */ +// This file was added to .openapi-generator-ignore so we can freely modify it. + +#[cfg(target_arch = "wasm32")] +pub type HttpClient = reqwest::Client; + +#[cfg(not(target_arch = "wasm32"))] +pub type HttpClient = reqwest_middleware::ClientWithMiddleware; #[derive(Debug, Clone)] pub struct Configuration { pub base_path: String, pub user_agent: Option, - pub client: reqwest::Client, + pub client: HttpClient, pub basic_auth: Option, pub oauth_access_token: Option, pub bearer_access_token: Option, pub api_key: Option, - // TODO: take an oauth2 token source, similar to the go one } pub type BasicAuth = (String, Option); @@ -36,10 +42,15 @@ impl Configuration { impl Default for Configuration { fn default() -> Self { + #[cfg(target_arch = "wasm32")] + let client = reqwest::Client::new(); + + #[cfg(not(target_arch = "wasm32"))] + let client = reqwest_middleware::ClientBuilder::new(reqwest::Client::new()).build(); Configuration { base_path: "http://localhost".to_owned(), - user_agent: Some("OpenAPI-Generator/0.25.0/rust".to_owned()), - client: reqwest::Client::new(), + user_agent: Some("OpenAPI-Generator/28.0/rust".to_owned()), + client, basic_auth: None, oauth_access_token: None, bearer_access_token: None, diff --git a/typesense_codegen/src/apis/conversations_api.rs b/typesense_codegen/src/apis/conversations_api.rs new file mode 100644 index 0000000..28b81f0 --- /dev/null +++ b/typesense_codegen/src/apis/conversations_api.rs @@ -0,0 +1,299 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + +/// struct for passing parameters to the method [`create_conversation_model`] +#[derive(Clone, Debug)] +pub struct CreateConversationModelParams { + pub conversation_model_create_schema: models::ConversationModelCreateSchema +} + +/// struct for passing parameters to the method [`delete_conversation_model`] +#[derive(Clone, Debug)] +pub struct DeleteConversationModelParams { + /// The id of the conversation model to delete + pub model_id: String +} + +/// struct for passing parameters to the method [`retrieve_conversation_model`] +#[derive(Clone, Debug)] +pub struct RetrieveConversationModelParams { + /// The id of the conversation model to retrieve + pub model_id: String +} + +/// struct for passing parameters to the method [`update_conversation_model`] +#[derive(Clone, Debug)] +pub struct UpdateConversationModelParams { + /// The id of the conversation model to update + pub model_id: String, + pub conversation_model_update_schema: models::ConversationModelUpdateSchema +} + + +/// struct for typed errors of method [`create_conversation_model`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum CreateConversationModelError { + Status400(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`delete_conversation_model`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum DeleteConversationModelError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_all_conversation_models`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveAllConversationModelsError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_conversation_model`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveConversationModelError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`update_conversation_model`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum UpdateConversationModelError { + UnknownValue(serde_json::Value), +} + + +/// Create a Conversation Model +pub async fn create_conversation_model(configuration: &configuration::Configuration, params: CreateConversationModelParams) -> Result> { + + let uri_str = format!("{}/conversations/models", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.conversation_model_create_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Delete a conversation model +pub async fn delete_conversation_model(configuration: &configuration::Configuration, params: DeleteConversationModelParams) -> Result> { + + let uri_str = format!("{}/conversations/models/{modelId}", configuration.base_path, modelId=crate::apis::urlencode(params.model_id)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Retrieve all conversation models +pub async fn retrieve_all_conversation_models(configuration: &configuration::Configuration) -> Result, Error> { + + let uri_str = format!("{}/conversations/models", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec<models::ConversationModelSchema>`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec<models::ConversationModelSchema>`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Retrieve a conversation model +pub async fn retrieve_conversation_model(configuration: &configuration::Configuration, params: RetrieveConversationModelParams) -> Result> { + + let uri_str = format!("{}/conversations/models/{modelId}", configuration.base_path, modelId=crate::apis::urlencode(params.model_id)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Update a conversation model +pub async fn update_conversation_model(configuration: &configuration::Configuration, params: UpdateConversationModelParams) -> Result> { + + let uri_str = format!("{}/conversations/models/{modelId}", configuration.base_path, modelId=crate::apis::urlencode(params.model_id)); + let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.conversation_model_update_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + diff --git a/typesense_codegen/src/apis/curation_api.rs b/typesense_codegen/src/apis/curation_api.rs new file mode 100644 index 0000000..9fde986 --- /dev/null +++ b/typesense_codegen/src/apis/curation_api.rs @@ -0,0 +1,196 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + +/// struct for passing parameters to the method [`delete_search_override`] +#[derive(Clone, Debug)] +pub struct DeleteSearchOverrideParams { + /// The name of the collection + pub collection_name: String, + /// The ID of the search override to delete + pub override_id: String +} + +/// struct for passing parameters to the method [`get_search_overrides`] +#[derive(Clone, Debug)] +pub struct GetSearchOverridesParams { + /// The name of the collection + pub collection_name: String +} + +/// struct for passing parameters to the method [`upsert_search_override`] +#[derive(Clone, Debug)] +pub struct UpsertSearchOverrideParams { + /// The name of the collection + pub collection_name: String, + /// The ID of the search override to create/update + pub override_id: String, + /// The search override object to be created/updated + pub search_override_schema: models::SearchOverrideSchema +} + + +/// struct for typed errors of method [`delete_search_override`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum DeleteSearchOverrideError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_search_overrides`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetSearchOverridesError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`upsert_search_override`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum UpsertSearchOverrideError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + + +pub async fn delete_search_override(configuration: &configuration::Configuration, params: DeleteSearchOverrideParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), overrideId=crate::apis::urlencode(params.override_id)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +pub async fn get_search_overrides(configuration: &configuration::Configuration, params: GetSearchOverridesParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}/overrides", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverridesResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverridesResponse`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Create or update an override to promote certain documents over others. Using overrides, you can include or exclude specific documents for a given query. +pub async fn upsert_search_override(configuration: &configuration::Configuration, params: UpsertSearchOverrideParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), overrideId=crate::apis::urlencode(params.override_id)); + let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.search_override_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverride`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + diff --git a/typesense_codegen/src/apis/debug_api.rs b/typesense_codegen/src/apis/debug_api.rs index 5f4dd0f..42d0e88 100644 --- a/typesense_codegen/src/apis/debug_api.rs +++ b/typesense_codegen/src/apis/debug_api.rs @@ -3,13 +3,17 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ -use super::{Error, configuration}; -use crate::apis::ResponseContent; + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + /// struct for typed errors of method [`debug`] #[derive(Debug, Clone, Serialize, Deserialize)] @@ -18,47 +22,47 @@ pub enum DebugError { UnknownValue(serde_json::Value), } -/// Print debugging information -pub async fn debug( - configuration: &configuration::Configuration, -) -> Result> { - let local_var_configuration = configuration; - let local_var_client = &local_var_configuration.client; +/// Print debugging information +pub async fn debug(configuration: &configuration::Configuration) -> Result> { - let local_var_uri_str = format!("{}/debug", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + let uri_str = format!("{}/debug", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::Debug200Response`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::Debug200Response`")))), + } } else { - let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } + diff --git a/typesense_codegen/src/apis/documents_api.rs b/typesense_codegen/src/apis/documents_api.rs index f19502b..9400aa3 100644 --- a/typesense_codegen/src/apis/documents_api.rs +++ b/typesense_codegen/src/apis/documents_api.rs @@ -3,19 +3,297 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ -use super::{Error, configuration}; -use crate::apis::ResponseContent; + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + +/// struct for passing parameters to the method [`delete_document`] +#[derive(Clone, Debug)] +pub struct DeleteDocumentParams { + /// The name of the collection to search for the document under + pub collection_name: String, + /// The Document ID + pub document_id: String +} + +/// struct for passing parameters to the method [`delete_documents`] +#[derive(Clone, Debug)] +pub struct DeleteDocumentsParams { + /// The name of the collection to delete documents from + pub collection_name: String, + pub filter_by: Option, + pub batch_size: Option, + pub ignore_not_found: Option, + pub truncate: Option +} + +/// struct for passing parameters to the method [`delete_search_override`] +#[derive(Clone, Debug)] +pub struct DeleteSearchOverrideParams { + /// The name of the collection + pub collection_name: String, + /// The ID of the search override to delete + pub override_id: String +} + +/// struct for passing parameters to the method [`export_documents`] +#[derive(Clone, Debug)] +pub struct ExportDocumentsParams { + /// The name of the collection + pub collection_name: String, + pub filter_by: Option, + pub include_fields: Option, + pub exclude_fields: Option +} + +/// struct for passing parameters to the method [`get_document`] +#[derive(Clone, Debug)] +pub struct GetDocumentParams { + /// The name of the collection to search for the document under + pub collection_name: String, + /// The Document ID + pub document_id: String +} + +/// struct for passing parameters to the method [`get_search_override`] +#[derive(Clone, Debug)] +pub struct GetSearchOverrideParams { + /// The name of the collection + pub collection_name: String, + /// The id of the search override + pub override_id: String +} + +/// struct for passing parameters to the method [`get_search_overrides`] +#[derive(Clone, Debug)] +pub struct GetSearchOverridesParams { + /// The name of the collection + pub collection_name: String +} + +/// struct for passing parameters to the method [`import_documents`] +#[derive(Clone, Debug)] +pub struct ImportDocumentsParams { + /// The name of the collection + pub collection_name: String, + /// The json array of documents or the JSONL file to import + pub body: String, + pub batch_size: Option, + pub return_id: Option, + pub remote_embedding_batch_size: Option, + pub return_doc: Option, + pub action: Option, + pub dirty_values: Option +} + +/// struct for passing parameters to the method [`index_document`] +#[derive(Clone, Debug)] +pub struct IndexDocumentParams { + /// The name of the collection to add the document to + pub collection_name: String, + /// The document object to be indexed + pub body: serde_json::Value, + /// Additional action to perform + pub action: Option, + /// Dealing with Dirty Data + pub dirty_values: Option +} + +/// struct for passing parameters to the method [`multi_search`] +#[derive(Clone, Debug)] +pub struct MultiSearchParams { + pub q: Option, + pub query_by: Option, + pub query_by_weights: Option, + pub text_match_type: Option, + pub prefix: Option, + pub infix: Option, + pub max_extra_prefix: Option, + pub max_extra_suffix: Option, + pub filter_by: Option, + pub sort_by: Option, + pub facet_by: Option, + pub max_facet_values: Option, + pub facet_query: Option, + pub num_typos: Option, + pub page: Option, + pub per_page: Option, + pub limit: Option, + pub offset: Option, + pub group_by: Option, + pub group_limit: Option, + pub group_missing_values: Option, + pub include_fields: Option, + pub exclude_fields: Option, + pub highlight_full_fields: Option, + pub highlight_affix_num_tokens: Option, + pub highlight_start_tag: Option, + pub highlight_end_tag: Option, + pub snippet_threshold: Option, + pub drop_tokens_threshold: Option, + pub drop_tokens_mode: Option, + pub typo_tokens_threshold: Option, + pub enable_typos_for_alpha_numerical_tokens: Option, + pub filter_curated_hits: Option, + pub enable_synonyms: Option, + pub enable_analytics: Option, + pub synonym_prefix: Option, + pub synonym_num_typos: Option, + pub pinned_hits: Option, + pub hidden_hits: Option, + pub override_tags: Option, + pub highlight_fields: Option, + pub pre_segmented_query: Option, + pub preset: Option, + pub enable_overrides: Option, + pub prioritize_exact_match: Option, + pub prioritize_token_position: Option, + pub prioritize_num_matching_fields: Option, + pub enable_typos_for_numerical_tokens: Option, + pub exhaustive_search: Option, + pub search_cutoff_ms: Option, + pub use_cache: Option, + pub cache_ttl: Option, + pub min_len_1typo: Option, + pub min_len_2typo: Option, + pub vector_query: Option, + pub remote_embedding_timeout_ms: Option, + pub remote_embedding_num_tries: Option, + pub facet_strategy: Option, + pub stopwords: Option, + pub facet_return_parent: Option, + pub voice_query: Option, + pub conversation: Option, + pub conversation_model_id: Option, + pub conversation_id: Option, + pub multi_search_searches_parameter: Option +} + +/// struct for passing parameters to the method [`search_collection`] +#[derive(Clone, Debug)] +pub struct SearchCollectionParams { + /// The name of the collection to search for the document under + pub collection_name: String, + pub q: Option, + pub query_by: Option, + pub nl_query: Option, + pub nl_model_id: Option, + pub query_by_weights: Option, + pub text_match_type: Option, + pub prefix: Option, + pub infix: Option, + pub max_extra_prefix: Option, + pub max_extra_suffix: Option, + pub filter_by: Option, + pub max_filter_by_candidates: Option, + pub sort_by: Option, + pub facet_by: Option, + pub max_facet_values: Option, + pub facet_query: Option, + pub num_typos: Option, + pub page: Option, + pub per_page: Option, + pub limit: Option, + pub offset: Option, + pub group_by: Option, + pub group_limit: Option, + pub group_missing_values: Option, + pub include_fields: Option, + pub exclude_fields: Option, + pub highlight_full_fields: Option, + pub highlight_affix_num_tokens: Option, + pub highlight_start_tag: Option, + pub highlight_end_tag: Option, + pub enable_highlight_v1: Option, + pub enable_analytics: Option, + pub snippet_threshold: Option, + pub synonym_sets: Option, + pub drop_tokens_threshold: Option, + pub drop_tokens_mode: Option, + pub typo_tokens_threshold: Option, + pub enable_typos_for_alpha_numerical_tokens: Option, + pub filter_curated_hits: Option, + pub enable_synonyms: Option, + pub synonym_prefix: Option, + pub synonym_num_typos: Option, + pub pinned_hits: Option, + pub hidden_hits: Option, + pub override_tags: Option, + pub highlight_fields: Option, + pub split_join_tokens: Option, + pub pre_segmented_query: Option, + pub preset: Option, + pub enable_overrides: Option, + pub prioritize_exact_match: Option, + pub max_candidates: Option, + pub prioritize_token_position: Option, + pub prioritize_num_matching_fields: Option, + pub enable_typos_for_numerical_tokens: Option, + pub exhaustive_search: Option, + pub search_cutoff_ms: Option, + pub use_cache: Option, + pub cache_ttl: Option, + pub min_len_1typo: Option, + pub min_len_2typo: Option, + pub vector_query: Option, + pub remote_embedding_timeout_ms: Option, + pub remote_embedding_num_tries: Option, + pub facet_strategy: Option, + pub stopwords: Option, + pub facet_return_parent: Option, + pub voice_query: Option, + pub conversation: Option, + pub conversation_model_id: Option, + pub conversation_id: Option +} + +/// struct for passing parameters to the method [`update_document`] +#[derive(Clone, Debug)] +pub struct UpdateDocumentParams { + /// The name of the collection to search for the document under + pub collection_name: String, + /// The Document ID + pub document_id: String, + /// The document object with fields to be updated + pub body: serde_json::Value, + /// Dealing with Dirty Data + pub dirty_values: Option +} + +/// struct for passing parameters to the method [`update_documents`] +#[derive(Clone, Debug)] +pub struct UpdateDocumentsParams { + /// The name of the collection to update documents in + pub collection_name: String, + /// The document fields to be updated + pub body: serde_json::Value, + pub filter_by: Option +} + +/// struct for passing parameters to the method [`upsert_search_override`] +#[derive(Clone, Debug)] +pub struct UpsertSearchOverrideParams { + /// The name of the collection + pub collection_name: String, + /// The ID of the search override to create/update + pub override_id: String, + /// The search override object to be created/updated + pub search_override_schema: models::SearchOverrideSchema +} + /// struct for typed errors of method [`delete_document`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum DeleteDocumentError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -23,7 +301,7 @@ pub enum DeleteDocumentError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum DeleteDocumentsError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -31,15 +309,7 @@ pub enum DeleteDocumentsError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum DeleteSearchOverrideError { - Status404(crate::models::ApiResponse), - UnknownValue(serde_json::Value), -} - -/// struct for typed errors of method [`delete_search_synonym`] -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub enum DeleteSearchSynonymError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -47,7 +317,7 @@ pub enum DeleteSearchSynonymError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum ExportDocumentsError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -55,7 +325,7 @@ pub enum ExportDocumentsError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum GetDocumentError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -73,28 +343,12 @@ pub enum GetSearchOverridesError { UnknownValue(serde_json::Value), } -/// struct for typed errors of method [`get_search_synonym`] -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub enum GetSearchSynonymError { - Status404(crate::models::ApiResponse), - UnknownValue(serde_json::Value), -} - -/// struct for typed errors of method [`get_search_synonyms`] -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub enum GetSearchSynonymsError { - Status404(crate::models::ApiResponse), - UnknownValue(serde_json::Value), -} - /// struct for typed errors of method [`import_documents`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum ImportDocumentsError { - Status400(crate::models::ApiResponse), - Status404(crate::models::ApiResponse), + Status400(models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -102,7 +356,7 @@ pub enum ImportDocumentsError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum IndexDocumentError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -110,7 +364,7 @@ pub enum IndexDocumentError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum MultiSearchError { - Status400(crate::models::ApiResponse), + Status400(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -118,8 +372,8 @@ pub enum MultiSearchError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum SearchCollectionError { - Status400(crate::models::ApiResponse), - Status404(crate::models::ApiResponse), + Status400(models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -127,7 +381,7 @@ pub enum SearchCollectionError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum UpdateDocumentError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -135,8 +389,8 @@ pub enum UpdateDocumentError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum UpdateDocumentsError { - Status400(crate::models::ApiResponse), - Status404(crate::models::ApiResponse), + Status400(models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -144,990 +398,1070 @@ pub enum UpdateDocumentsError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum UpsertSearchOverrideError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } -/// struct for typed errors of method [`upsert_search_synonym`] -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub enum UpsertSearchSynonymError { - Status404(crate::models::ApiResponse), - UnknownValue(serde_json::Value), -} /// Delete an individual document from a collection by using its ID. -pub async fn delete_document( - configuration: &configuration::Configuration, - collection_name: &str, - document_id: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/documents/{documentId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - documentId = crate::apis::urlencode(document_id) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; +pub async fn delete_document(configuration: &configuration::Configuration, params: DeleteDocumentParams) -> Result> { - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; + let uri_str = format!("{}/collections/{collectionName}/documents/{documentId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), documentId=crate::apis::urlencode(params.document_id)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `serde_json::Value`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Delete a bunch of documents that match a specific filter condition. Use the `batch_size` parameter to control the number of documents that should deleted at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. -pub async fn delete_documents( - configuration: &configuration::Configuration, - collection_name: &str, - delete_documents_parameters: Option< - crate::models::DeleteDocumentsDeleteDocumentsParametersParameter, - >, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/documents", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); - - if let Some(ref delete_documents_parameters_ref) = delete_documents_parameters { - local_var_req_builder = local_var_req_builder.query(&delete_documents_parameters_ref); - } - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; +pub async fn delete_documents(configuration: &configuration::Configuration, params: DeleteDocumentsParams) -> Result> { - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + let uri_str = format!("{}/collections/{collectionName}/documents", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + if let Some(ref param_value) = params.filter_by { + req_builder = req_builder.query(&[("filter_by", ¶m_value.to_string())]); } -} - -pub async fn delete_search_override( - configuration: &configuration::Configuration, - collection_name: &str, - override_id: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/overrides/{overrideId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - overrideId = crate::apis::urlencode(override_id) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref param_value) = params.batch_size { + req_builder = req_builder.query(&[("batch_size", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.ignore_not_found { + req_builder = req_builder.query(&[("ignore_not_found", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.truncate { + req_builder = req_builder.query(&[("truncate", ¶m_value.to_string())]); + } + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::DeleteDocuments200Response`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::DeleteDocuments200Response`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } -pub async fn delete_search_synonym( - configuration: &configuration::Configuration, - collection_name: &str, - synonym_id: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/synonyms/{synonymId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - synonymId = crate::apis::urlencode(synonym_id) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; +pub async fn delete_search_override(configuration: &configuration::Configuration, params: DeleteSearchOverrideParams) -> Result> { - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; + let uri_str = format!("{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), overrideId=crate::apis::urlencode(params.override_id)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Export all documents in a collection in JSON lines format. -pub async fn export_documents( - configuration: &configuration::Configuration, - collection_name: &str, - export_documents_parameters: Option< - crate::models::ExportDocumentsExportDocumentsParametersParameter, - >, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/documents/export", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref export_documents_parameters_ref) = export_documents_parameters { - local_var_req_builder = local_var_req_builder.query(&export_documents_parameters_ref); - } - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; +pub async fn export_documents(configuration: &configuration::Configuration, params: ExportDocumentsParams) -> Result> { - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; + let uri_str = format!("{}/collections/{collectionName}/documents/export", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + if let Some(ref param_value) = params.filter_by { + req_builder = req_builder.query(&[("filter_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.include_fields { + req_builder = req_builder.query(&[("include_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.exclude_fields { + req_builder = req_builder.query(&[("exclude_fields", ¶m_value.to_string())]); + } + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `String`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `String`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Fetch an individual document from a collection by using its ID. -pub async fn get_document( - configuration: &configuration::Configuration, - collection_name: &str, - document_id: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/documents/{documentId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - documentId = crate::apis::urlencode(document_id) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; +pub async fn get_document(configuration: &configuration::Configuration, params: GetDocumentParams) -> Result> { - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; + let uri_str = format!("{}/collections/{collectionName}/documents/{documentId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), documentId=crate::apis::urlencode(params.document_id)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `serde_json::Value`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Retrieve the details of a search override, given its id. -pub async fn get_search_override( - configuration: &configuration::Configuration, - collection_name: &str, - override_id: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/overrides/{overrideId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - overrideId = crate::apis::urlencode(override_id) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; +pub async fn get_search_override(configuration: &configuration::Configuration, params: GetSearchOverrideParams) -> Result> { - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; + let uri_str = format!("{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), overrideId=crate::apis::urlencode(params.override_id)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } -} - -pub async fn get_search_overrides( - configuration: &configuration::Configuration, - collection_name: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/overrides", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverride`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } -/// Retrieve the details of a search synonym, given its id. -pub async fn get_search_synonym( - configuration: &configuration::Configuration, - collection_name: &str, - synonym_id: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/synonyms/{synonymId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - synonymId = crate::apis::urlencode(synonym_id) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; +pub async fn get_search_overrides(configuration: &configuration::Configuration, params: GetSearchOverridesParams) -> Result> { - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + let uri_str = format!("{}/collections/{collectionName}/overrides", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } -} - -pub async fn get_search_synonyms( - configuration: &configuration::Configuration, - collection_name: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/synonyms", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverridesResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverridesResponse`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// The documents to be imported must be formatted in a newline delimited JSON structure. You can feed the output file from a Typesense export operation directly as import. -pub async fn import_documents( - configuration: &configuration::Configuration, - collection_name: &str, - body: String, - import_documents_parameters: Option< - crate::models::ImportDocumentsImportDocumentsParametersParameter, - >, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/documents/import", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); - - if let Some(ref import_documents_parameters_ref) = import_documents_parameters { - local_var_req_builder = local_var_req_builder.query(&import_documents_parameters_ref); - } - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; - // was changed by hand - local_var_req_builder = local_var_req_builder.body(body); +pub async fn import_documents(configuration: &configuration::Configuration, params: ImportDocumentsParams) -> Result> { - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; + let uri_str = format!("{}/collections/{collectionName}/documents/import", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - // was changed by hand - Ok(local_var_content) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, + if let Some(ref param_value) = params.batch_size { + req_builder = req_builder.query(&[("batch_size", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.return_id { + req_builder = req_builder.query(&[("return_id", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.remote_embedding_batch_size { + req_builder = req_builder.query(&[("remote_embedding_batch_size", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.return_doc { + req_builder = req_builder.query(&[("return_doc", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.action { + req_builder = req_builder.query(&[("action", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.dirty_values { + req_builder = req_builder.query(&[("dirty_values", ¶m_value.to_string())]); + } + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - Err(Error::ResponseError(local_var_error)) + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.body); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `String`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `String`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// A document to be indexed in a given collection must conform to the schema of the collection. -pub async fn index_document( - configuration: &configuration::Configuration, - collection_name: &str, - body: serde_json::Value, - action: Option<&str>, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/documents", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); - - if let Some(ref local_var_str) = action { - local_var_req_builder = - local_var_req_builder.query(&[("action", &local_var_str.to_string())]); - } - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; - local_var_req_builder = local_var_req_builder.json(&body); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; +pub async fn index_document(configuration: &configuration::Configuration, params: IndexDocumentParams) -> Result> { - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + let uri_str = format!("{}/collections/{collectionName}/documents", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, + if let Some(ref param_value) = params.action { + req_builder = req_builder.query(&[("action", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.dirty_values { + req_builder = req_builder.query(&[("dirty_values", ¶m_value.to_string())]); + } + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - Err(Error::ResponseError(local_var_error)) + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.body); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `serde_json::Value`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// This is especially useful to avoid round-trip network latencies incurred otherwise if each of these requests are sent in separate HTTP requests. You can also use this feature to do a federated search across multiple collections in a single HTTP request. -pub async fn multi_search serde::Deserialize<'d>>( - configuration: &configuration::Configuration, - multi_search_parameters: crate::models::MultiSearchParameters, - multi_search_searches_parameter: Option, -) -> Result, Error> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!("{}/multi_search", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); - - local_var_req_builder = local_var_req_builder.query(&multi_search_parameters); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; - local_var_req_builder = local_var_req_builder.json(&multi_search_searches_parameter); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; +pub async fn multi_search(configuration: &configuration::Configuration, params: MultiSearchParams) -> Result> { - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + let uri_str = format!("{}/multi_search", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, + if let Some(ref param_value) = params.q { + req_builder = req_builder.query(&[("q", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.query_by { + req_builder = req_builder.query(&[("query_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.query_by_weights { + req_builder = req_builder.query(&[("query_by_weights", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.text_match_type { + req_builder = req_builder.query(&[("text_match_type", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.prefix { + req_builder = req_builder.query(&[("prefix", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.infix { + req_builder = req_builder.query(&[("infix", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.max_extra_prefix { + req_builder = req_builder.query(&[("max_extra_prefix", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.max_extra_suffix { + req_builder = req_builder.query(&[("max_extra_suffix", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.filter_by { + req_builder = req_builder.query(&[("filter_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.sort_by { + req_builder = req_builder.query(&[("sort_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.facet_by { + req_builder = req_builder.query(&[("facet_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.max_facet_values { + req_builder = req_builder.query(&[("max_facet_values", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.facet_query { + req_builder = req_builder.query(&[("facet_query", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.num_typos { + req_builder = req_builder.query(&[("num_typos", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.page { + req_builder = req_builder.query(&[("page", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.per_page { + req_builder = req_builder.query(&[("per_page", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.limit { + req_builder = req_builder.query(&[("limit", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.offset { + req_builder = req_builder.query(&[("offset", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.group_by { + req_builder = req_builder.query(&[("group_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.group_limit { + req_builder = req_builder.query(&[("group_limit", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.group_missing_values { + req_builder = req_builder.query(&[("group_missing_values", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.include_fields { + req_builder = req_builder.query(&[("include_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.exclude_fields { + req_builder = req_builder.query(&[("exclude_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.highlight_full_fields { + req_builder = req_builder.query(&[("highlight_full_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.highlight_affix_num_tokens { + req_builder = req_builder.query(&[("highlight_affix_num_tokens", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.highlight_start_tag { + req_builder = req_builder.query(&[("highlight_start_tag", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.highlight_end_tag { + req_builder = req_builder.query(&[("highlight_end_tag", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.snippet_threshold { + req_builder = req_builder.query(&[("snippet_threshold", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.drop_tokens_threshold { + req_builder = req_builder.query(&[("drop_tokens_threshold", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.drop_tokens_mode { + req_builder = req_builder.query(&[("drop_tokens_mode", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.typo_tokens_threshold { + req_builder = req_builder.query(&[("typo_tokens_threshold", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_typos_for_alpha_numerical_tokens { + req_builder = req_builder.query(&[("enable_typos_for_alpha_numerical_tokens", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.filter_curated_hits { + req_builder = req_builder.query(&[("filter_curated_hits", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_synonyms { + req_builder = req_builder.query(&[("enable_synonyms", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_analytics { + req_builder = req_builder.query(&[("enable_analytics", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.synonym_prefix { + req_builder = req_builder.query(&[("synonym_prefix", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.synonym_num_typos { + req_builder = req_builder.query(&[("synonym_num_typos", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.pinned_hits { + req_builder = req_builder.query(&[("pinned_hits", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.hidden_hits { + req_builder = req_builder.query(&[("hidden_hits", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.override_tags { + req_builder = req_builder.query(&[("override_tags", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.highlight_fields { + req_builder = req_builder.query(&[("highlight_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.pre_segmented_query { + req_builder = req_builder.query(&[("pre_segmented_query", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.preset { + req_builder = req_builder.query(&[("preset", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_overrides { + req_builder = req_builder.query(&[("enable_overrides", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.prioritize_exact_match { + req_builder = req_builder.query(&[("prioritize_exact_match", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.prioritize_token_position { + req_builder = req_builder.query(&[("prioritize_token_position", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.prioritize_num_matching_fields { + req_builder = req_builder.query(&[("prioritize_num_matching_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_typos_for_numerical_tokens { + req_builder = req_builder.query(&[("enable_typos_for_numerical_tokens", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.exhaustive_search { + req_builder = req_builder.query(&[("exhaustive_search", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.search_cutoff_ms { + req_builder = req_builder.query(&[("search_cutoff_ms", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.use_cache { + req_builder = req_builder.query(&[("use_cache", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.cache_ttl { + req_builder = req_builder.query(&[("cache_ttl", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.min_len_1typo { + req_builder = req_builder.query(&[("min_len_1typo", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.min_len_2typo { + req_builder = req_builder.query(&[("min_len_2typo", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.vector_query { + req_builder = req_builder.query(&[("vector_query", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.remote_embedding_timeout_ms { + req_builder = req_builder.query(&[("remote_embedding_timeout_ms", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.remote_embedding_num_tries { + req_builder = req_builder.query(&[("remote_embedding_num_tries", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.facet_strategy { + req_builder = req_builder.query(&[("facet_strategy", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.stopwords { + req_builder = req_builder.query(&[("stopwords", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.facet_return_parent { + req_builder = req_builder.query(&[("facet_return_parent", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.voice_query { + req_builder = req_builder.query(&[("voice_query", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.conversation { + req_builder = req_builder.query(&[("conversation", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.conversation_model_id { + req_builder = req_builder.query(&[("conversation_model_id", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.conversation_id { + req_builder = req_builder.query(&[("conversation_id", ¶m_value.to_string())]); + } + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - Err(Error::ResponseError(local_var_error)) + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.multi_search_searches_parameter); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::MultiSearchResult`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::MultiSearchResult`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Search for documents in a collection that match the search criteria. -pub async fn search_collection serde::Deserialize<'d>>( - configuration: &configuration::Configuration, - collection_name: &str, - search_parameters: crate::models::SearchParameters, -) -> Result, Error> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/documents/search", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - local_var_req_builder = local_var_req_builder.query(&search_parameters); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; +pub async fn search_collection(configuration: &configuration::Configuration, params: SearchCollectionParams) -> Result> { - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; + let uri_str = format!("{}/collections/{collectionName}/documents/search", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + if let Some(ref param_value) = params.q { + req_builder = req_builder.query(&[("q", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.query_by { + req_builder = req_builder.query(&[("query_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.nl_query { + req_builder = req_builder.query(&[("nl_query", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.nl_model_id { + req_builder = req_builder.query(&[("nl_model_id", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.query_by_weights { + req_builder = req_builder.query(&[("query_by_weights", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.text_match_type { + req_builder = req_builder.query(&[("text_match_type", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.prefix { + req_builder = req_builder.query(&[("prefix", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.infix { + req_builder = req_builder.query(&[("infix", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.max_extra_prefix { + req_builder = req_builder.query(&[("max_extra_prefix", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.max_extra_suffix { + req_builder = req_builder.query(&[("max_extra_suffix", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.filter_by { + req_builder = req_builder.query(&[("filter_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.max_filter_by_candidates { + req_builder = req_builder.query(&[("max_filter_by_candidates", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.sort_by { + req_builder = req_builder.query(&[("sort_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.facet_by { + req_builder = req_builder.query(&[("facet_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.max_facet_values { + req_builder = req_builder.query(&[("max_facet_values", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.facet_query { + req_builder = req_builder.query(&[("facet_query", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.num_typos { + req_builder = req_builder.query(&[("num_typos", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.page { + req_builder = req_builder.query(&[("page", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.per_page { + req_builder = req_builder.query(&[("per_page", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.limit { + req_builder = req_builder.query(&[("limit", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.offset { + req_builder = req_builder.query(&[("offset", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.group_by { + req_builder = req_builder.query(&[("group_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.group_limit { + req_builder = req_builder.query(&[("group_limit", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.group_missing_values { + req_builder = req_builder.query(&[("group_missing_values", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.include_fields { + req_builder = req_builder.query(&[("include_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.exclude_fields { + req_builder = req_builder.query(&[("exclude_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.highlight_full_fields { + req_builder = req_builder.query(&[("highlight_full_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.highlight_affix_num_tokens { + req_builder = req_builder.query(&[("highlight_affix_num_tokens", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.highlight_start_tag { + req_builder = req_builder.query(&[("highlight_start_tag", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.highlight_end_tag { + req_builder = req_builder.query(&[("highlight_end_tag", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_highlight_v1 { + req_builder = req_builder.query(&[("enable_highlight_v1", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_analytics { + req_builder = req_builder.query(&[("enable_analytics", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.snippet_threshold { + req_builder = req_builder.query(&[("snippet_threshold", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.synonym_sets { + req_builder = req_builder.query(&[("synonym_sets", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.drop_tokens_threshold { + req_builder = req_builder.query(&[("drop_tokens_threshold", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.drop_tokens_mode { + req_builder = req_builder.query(&[("drop_tokens_mode", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.typo_tokens_threshold { + req_builder = req_builder.query(&[("typo_tokens_threshold", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_typos_for_alpha_numerical_tokens { + req_builder = req_builder.query(&[("enable_typos_for_alpha_numerical_tokens", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.filter_curated_hits { + req_builder = req_builder.query(&[("filter_curated_hits", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_synonyms { + req_builder = req_builder.query(&[("enable_synonyms", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.synonym_prefix { + req_builder = req_builder.query(&[("synonym_prefix", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.synonym_num_typos { + req_builder = req_builder.query(&[("synonym_num_typos", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.pinned_hits { + req_builder = req_builder.query(&[("pinned_hits", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.hidden_hits { + req_builder = req_builder.query(&[("hidden_hits", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.override_tags { + req_builder = req_builder.query(&[("override_tags", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.highlight_fields { + req_builder = req_builder.query(&[("highlight_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.split_join_tokens { + req_builder = req_builder.query(&[("split_join_tokens", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.pre_segmented_query { + req_builder = req_builder.query(&[("pre_segmented_query", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.preset { + req_builder = req_builder.query(&[("preset", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_overrides { + req_builder = req_builder.query(&[("enable_overrides", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.prioritize_exact_match { + req_builder = req_builder.query(&[("prioritize_exact_match", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.max_candidates { + req_builder = req_builder.query(&[("max_candidates", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.prioritize_token_position { + req_builder = req_builder.query(&[("prioritize_token_position", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.prioritize_num_matching_fields { + req_builder = req_builder.query(&[("prioritize_num_matching_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_typos_for_numerical_tokens { + req_builder = req_builder.query(&[("enable_typos_for_numerical_tokens", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.exhaustive_search { + req_builder = req_builder.query(&[("exhaustive_search", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.search_cutoff_ms { + req_builder = req_builder.query(&[("search_cutoff_ms", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.use_cache { + req_builder = req_builder.query(&[("use_cache", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.cache_ttl { + req_builder = req_builder.query(&[("cache_ttl", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.min_len_1typo { + req_builder = req_builder.query(&[("min_len_1typo", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.min_len_2typo { + req_builder = req_builder.query(&[("min_len_2typo", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.vector_query { + req_builder = req_builder.query(&[("vector_query", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.remote_embedding_timeout_ms { + req_builder = req_builder.query(&[("remote_embedding_timeout_ms", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.remote_embedding_num_tries { + req_builder = req_builder.query(&[("remote_embedding_num_tries", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.facet_strategy { + req_builder = req_builder.query(&[("facet_strategy", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.stopwords { + req_builder = req_builder.query(&[("stopwords", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.facet_return_parent { + req_builder = req_builder.query(&[("facet_return_parent", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.voice_query { + req_builder = req_builder.query(&[("voice_query", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.conversation { + req_builder = req_builder.query(&[("conversation", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.conversation_model_id { + req_builder = req_builder.query(&[("conversation_model_id", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.conversation_id { + req_builder = req_builder.query(&[("conversation_id", ¶m_value.to_string())]); + } + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchResult`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchResult`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Update an individual document from a collection by using its ID. The update can be partial. -pub async fn update_document( - configuration: &configuration::Configuration, - collection_name: &str, - document_id: &str, - body: serde_json::Value, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/documents/{documentId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - documentId = crate::apis::urlencode(document_id) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::PATCH, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; - local_var_req_builder = local_var_req_builder.json(&body); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; +pub async fn update_document(configuration: &configuration::Configuration, params: UpdateDocumentParams) -> Result> { - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + let uri_str = format!("{}/collections/{collectionName}/documents/{documentId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), documentId=crate::apis::urlencode(params.document_id)); + let mut req_builder = configuration.client.request(reqwest::Method::PATCH, &uri_str); - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, + if let Some(ref param_value) = params.dirty_values { + req_builder = req_builder.query(&[("dirty_values", ¶m_value.to_string())]); + } + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - Err(Error::ResponseError(local_var_error)) + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.body); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `serde_json::Value`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// The filter_by query parameter is used to filter to specify a condition against which the documents are matched. The request body contains the fields that should be updated for any documents that match the filter condition. This endpoint is only available if the Typesense server is version `0.25.0.rc12` or later. -pub async fn update_documents( - configuration: &configuration::Configuration, - collection_name: &str, - body: serde_json::Value, - update_documents_parameters: Option< - crate::models::UpdateDocumentsUpdateDocumentsParametersParameter, - >, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/documents", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::PATCH, local_var_uri_str.as_str()); - - if let Some(ref update_documents_parameters_ref) = update_documents_parameters { - local_var_req_builder = local_var_req_builder.query(&update_documents_parameters_ref); - } - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; - local_var_req_builder = local_var_req_builder.json(&body); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; +pub async fn update_documents(configuration: &configuration::Configuration, params: UpdateDocumentsParams) -> Result> { - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + let uri_str = format!("{}/collections/{collectionName}/documents", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); + let mut req_builder = configuration.client.request(reqwest::Method::PATCH, &uri_str); - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, + if let Some(ref param_value) = params.filter_by { + req_builder = req_builder.query(&[("filter_by", ¶m_value.to_string())]); + } + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - Err(Error::ResponseError(local_var_error)) + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.body); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::UpdateDocuments200Response`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::UpdateDocuments200Response`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Create or update an override to promote certain documents over others. Using overrides, you can include or exclude specific documents for a given query. -pub async fn upsert_search_override( - configuration: &configuration::Configuration, - collection_name: &str, - override_id: &str, - search_override_schema: crate::models::SearchOverrideSchema, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/overrides/{overrideId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - overrideId = crate::apis::urlencode(override_id) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::PUT, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; - local_var_req_builder = local_var_req_builder.json(&search_override_schema); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; +pub async fn upsert_search_override(configuration: &configuration::Configuration, params: UpsertSearchOverrideParams) -> Result> { - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + let uri_str = format!("{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), overrideId=crate::apis::urlencode(params.override_id)); + let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } -} - -/// Create or update a synonym to define search terms that should be considered equivalent. -pub async fn upsert_search_synonym( - configuration: &configuration::Configuration, - collection_name: &str, - synonym_id: &str, - search_synonym_schema: crate::models::SearchSynonymSchema, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/synonyms/{synonymId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - synonymId = crate::apis::urlencode(synonym_id) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::PUT, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - local_var_req_builder = local_var_req_builder.json(&search_synonym_schema); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + req_builder = req_builder.json(¶ms.search_override_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverride`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } + diff --git a/typesense_codegen/src/apis/health_api.rs b/typesense_codegen/src/apis/health_api.rs index 3930680..50f8085 100644 --- a/typesense_codegen/src/apis/health_api.rs +++ b/typesense_codegen/src/apis/health_api.rs @@ -3,13 +3,17 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ -use super::{Error, configuration}; -use crate::apis::ResponseContent; + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + /// struct for typed errors of method [`health`] #[derive(Debug, Clone, Serialize, Deserialize)] @@ -18,47 +22,47 @@ pub enum HealthError { UnknownValue(serde_json::Value), } -/// Checks if Typesense server is ready to accept requests. -pub async fn health( - configuration: &configuration::Configuration, -) -> Result> { - let local_var_configuration = configuration; - let local_var_client = &local_var_configuration.client; +/// Checks if Typesense server is ready to accept requests. +pub async fn health(configuration: &configuration::Configuration) -> Result> { - let local_var_uri_str = format!("{}/health", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + let uri_str = format!("{}/health", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::HealthStatus`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::HealthStatus`")))), + } } else { - let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } + diff --git a/typesense_codegen/src/apis/keys_api.rs b/typesense_codegen/src/apis/keys_api.rs index 084ed6c..e635b0e 100644 --- a/typesense_codegen/src/apis/keys_api.rs +++ b/typesense_codegen/src/apis/keys_api.rs @@ -3,20 +3,45 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ -use super::{Error, configuration}; -use crate::apis::ResponseContent; + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + +/// struct for passing parameters to the method [`create_key`] +#[derive(Clone, Debug)] +pub struct CreateKeyParams { + /// The object that describes API key scope + pub api_key_schema: Option +} + +/// struct for passing parameters to the method [`delete_key`] +#[derive(Clone, Debug)] +pub struct DeleteKeyParams { + /// The ID of the key to delete + pub key_id: i64 +} + +/// struct for passing parameters to the method [`get_key`] +#[derive(Clone, Debug)] +pub struct GetKeyParams { + /// The ID of the key to retrieve + pub key_id: i64 +} + /// struct for typed errors of method [`create_key`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum CreateKeyError { - Status400(crate::models::ApiResponse), - Status409(crate::models::ApiResponse), + Status400(models::ApiResponse), + Status409(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -24,8 +49,8 @@ pub enum CreateKeyError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum DeleteKeyError { - Status400(crate::models::ApiResponse), - Status404(crate::models::ApiResponse), + Status400(models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -33,7 +58,7 @@ pub enum DeleteKeyError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum GetKeyError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -44,194 +69,175 @@ pub enum GetKeysError { UnknownValue(serde_json::Value), } -/// Create an API Key with fine-grain access control. You can restrict access on both a per-collection and per-action level. The generated key is returned only during creation. You want to store this key carefully in a secure place. -pub async fn create_key( - configuration: &configuration::Configuration, - api_key_schema: Option, -) -> Result> { - let local_var_configuration = configuration; - let local_var_client = &local_var_configuration.client; +/// Create an API Key with fine-grain access control. You can restrict access on both a per-collection and per-action level. The generated key is returned only during creation. You want to store this key carefully in a secure place. +pub async fn create_key(configuration: &configuration::Configuration, params: CreateKeyParams) -> Result> { - let local_var_uri_str = format!("{}/keys", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); + let uri_str = format!("{}/keys", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - local_var_req_builder = local_var_req_builder.json(&api_key_schema); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + req_builder = req_builder.json(¶ms.api_key_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ApiKey`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ApiKey`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } -pub async fn delete_key( - configuration: &configuration::Configuration, - key_id: i64, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/keys/{keyId}", - local_var_configuration.base_path, - keyId = key_id - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); +pub async fn delete_key(configuration: &configuration::Configuration, params: DeleteKeyParams) -> Result> { + + let uri_str = format!("{}/keys/{keyId}", configuration.base_path, keyId=params.key_id); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ApiKeyDeleteResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ApiKeyDeleteResponse`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Retrieve (metadata about) a key. Only the key prefix is returned when you retrieve a key. Due to security reasons, only the create endpoint returns the full API key. -pub async fn get_key( - configuration: &configuration::Configuration, - key_id: i64, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/keys/{keyId}", - local_var_configuration.base_path, - keyId = key_id - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); +pub async fn get_key(configuration: &configuration::Configuration, params: GetKeyParams) -> Result> { + + let uri_str = format!("{}/keys/{keyId}", configuration.base_path, keyId=params.key_id); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ApiKey`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ApiKey`")))), + } } else { - let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } -pub async fn get_keys( - configuration: &configuration::Configuration, -) -> Result> { - let local_var_configuration = configuration; +pub async fn get_keys(configuration: &configuration::Configuration) -> Result> { - let local_var_client = &local_var_configuration.client; + let uri_str = format!("{}/keys", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - let local_var_uri_str = format!("{}/keys", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ApiKeysResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ApiKeysResponse`")))), + } } else { - let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } + diff --git a/typesense_codegen/src/apis/mod.rs b/typesense_codegen/src/apis/mod.rs index dd940c9..9e6d17d 100644 --- a/typesense_codegen/src/apis/mod.rs +++ b/typesense_codegen/src/apis/mod.rs @@ -11,6 +11,8 @@ pub struct ResponseContent { #[derive(Debug)] pub enum Error { Reqwest(reqwest::Error), + #[cfg(not(target_arch = "wasm32"))] + ReqwestMiddleware(reqwest_middleware::Error), Serde(serde_json::Error), Io(std::io::Error), ResponseError(ResponseContent), @@ -20,6 +22,8 @@ impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let (module, e) = match self { Error::Reqwest(e) => ("reqwest", e.to_string()), + #[cfg(not(target_arch = "wasm32"))] + Error::ReqwestMiddleware(e) => ("reqwest-middleware", e.to_string()), Error::Serde(e) => ("serde", e.to_string()), Error::Io(e) => ("IO", e.to_string()), Error::ResponseError(e) => ("response", format!("status code {}", e.status)), @@ -32,6 +36,8 @@ impl error::Error for Error { fn source(&self) -> Option<&(dyn error::Error + 'static)> { Some(match self { Error::Reqwest(e) => e, + #[cfg(not(target_arch = "wasm32"))] + Error::ReqwestMiddleware(e) => e, Error::Serde(e) => e, Error::Io(e) => e, Error::ResponseError(_) => return None, @@ -45,6 +51,13 @@ impl From for Error { } } +#[cfg(not(target_arch = "wasm32"))] +impl From for Error { + fn from(e: reqwest_middleware::Error) -> Self { + Error::ReqwestMiddleware(e) + } +} + impl From for Error { fn from(e: serde_json::Error) -> Self { Error::Serde(e) @@ -91,14 +104,41 @@ pub fn parse_deep_object(prefix: &str, value: &serde_json::Value) -> Vec<(String unimplemented!("Only objects are supported with style=deepObject") } +/// Internal use only +/// A content type supported by this client. +#[allow(dead_code)] +enum ContentType { + Json, + Text, + Unsupported(String), +} + +impl From<&str> for ContentType { + fn from(content_type: &str) -> Self { + if content_type.starts_with("application") && content_type.contains("json") { + return Self::Json; + } else if content_type.starts_with("text/plain") { + return Self::Text; + } else { + return Self::Unsupported(content_type.to_string()); + } + } +} + pub mod analytics_api; pub mod collections_api; +pub mod conversations_api; +pub mod curation_api; pub mod debug_api; pub mod documents_api; pub mod health_api; pub mod keys_api; +pub mod nl_search_models_api; pub mod operations_api; pub mod override_api; -pub mod promote_api; +pub mod presets_api; +pub mod stemming_api; +pub mod stopwords_api; +pub mod synonyms_api; pub mod configuration; diff --git a/typesense_codegen/src/apis/nl_search_models_api.rs b/typesense_codegen/src/apis/nl_search_models_api.rs new file mode 100644 index 0000000..1e6e93a --- /dev/null +++ b/typesense_codegen/src/apis/nl_search_models_api.rs @@ -0,0 +1,305 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + +/// struct for passing parameters to the method [`create_nl_search_model`] +#[derive(Clone, Debug)] +pub struct CreateNlSearchModelParams { + /// The NL search model to be created + pub nl_search_model_create_schema: models::NlSearchModelCreateSchema +} + +/// struct for passing parameters to the method [`delete_nl_search_model`] +#[derive(Clone, Debug)] +pub struct DeleteNlSearchModelParams { + /// The ID of the NL search model to delete + pub model_id: String +} + +/// struct for passing parameters to the method [`retrieve_nl_search_model`] +#[derive(Clone, Debug)] +pub struct RetrieveNlSearchModelParams { + /// The ID of the NL search model to retrieve + pub model_id: String +} + +/// struct for passing parameters to the method [`update_nl_search_model`] +#[derive(Clone, Debug)] +pub struct UpdateNlSearchModelParams { + /// The ID of the NL search model to update + pub model_id: String, + /// The NL search model fields to update + pub body: models::NlSearchModelCreateSchema +} + + +/// struct for typed errors of method [`create_nl_search_model`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum CreateNlSearchModelError { + Status400(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`delete_nl_search_model`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum DeleteNlSearchModelError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_all_nl_search_models`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveAllNlSearchModelsError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_nl_search_model`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveNlSearchModelError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`update_nl_search_model`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum UpdateNlSearchModelError { + Status400(models::ApiResponse), + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + + +/// Create a new NL search model. +pub async fn create_nl_search_model(configuration: &configuration::Configuration, params: CreateNlSearchModelParams) -> Result> { + + let uri_str = format!("{}/nl_search_models", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.nl_search_model_create_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::NlSearchModelSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Delete a specific NL search model by its ID. +pub async fn delete_nl_search_model(configuration: &configuration::Configuration, params: DeleteNlSearchModelParams) -> Result> { + + let uri_str = format!("{}/nl_search_models/{modelId}", configuration.base_path, modelId=crate::apis::urlencode(params.model_id)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::NlSearchModelDeleteSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelDeleteSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Retrieve all NL search models. +pub async fn retrieve_all_nl_search_models(configuration: &configuration::Configuration) -> Result, Error> { + + let uri_str = format!("{}/nl_search_models", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec<models::NlSearchModelSchema>`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec<models::NlSearchModelSchema>`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Retrieve a specific NL search model by its ID. +pub async fn retrieve_nl_search_model(configuration: &configuration::Configuration, params: RetrieveNlSearchModelParams) -> Result> { + + let uri_str = format!("{}/nl_search_models/{modelId}", configuration.base_path, modelId=crate::apis::urlencode(params.model_id)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::NlSearchModelSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Update an existing NL search model. +pub async fn update_nl_search_model(configuration: &configuration::Configuration, params: UpdateNlSearchModelParams) -> Result> { + + let uri_str = format!("{}/nl_search_models/{modelId}", configuration.base_path, modelId=crate::apis::urlencode(params.model_id)); + let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.body); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::NlSearchModelSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + diff --git a/typesense_codegen/src/apis/operations_api.rs b/typesense_codegen/src/apis/operations_api.rs index 0c2adc3..31750f3 100644 --- a/typesense_codegen/src/apis/operations_api.rs +++ b/typesense_codegen/src/apis/operations_api.rs @@ -3,13 +3,65 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ -use super::{Error, configuration}; -use crate::apis::ResponseContent; + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + +/// struct for passing parameters to the method [`take_snapshot`] +#[derive(Clone, Debug)] +pub struct TakeSnapshotParams { + /// The directory on the server where the snapshot should be saved. + pub snapshot_path: String +} + +/// struct for passing parameters to the method [`toggle_slow_request_log`] +#[derive(Clone, Debug)] +pub struct ToggleSlowRequestLogParams { + pub toggle_slow_request_log_request: Option +} + + +/// struct for typed errors of method [`clear_cache`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ClearCacheError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`compact_db`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum CompactDbError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_schema_changes`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetSchemaChangesError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_api_stats`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveApiStatsError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_metrics`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveMetricsError { + UnknownValue(serde_json::Value), +} /// struct for typed errors of method [`take_snapshot`] #[derive(Debug, Clone, Serialize, Deserialize)] @@ -18,6 +70,13 @@ pub enum TakeSnapshotError { UnknownValue(serde_json::Value), } +/// struct for typed errors of method [`toggle_slow_request_log`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ToggleSlowRequestLogError { + UnknownValue(serde_json::Value), +} + /// struct for typed errors of method [`vote`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -25,96 +84,350 @@ pub enum VoteError { UnknownValue(serde_json::Value), } + +/// Clear the cached responses of search requests that are sent with `use_cache` parameter in the LRU cache. +pub async fn clear_cache(configuration: &configuration::Configuration) -> Result> { + + let uri_str = format!("{}/operations/cache/clear", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Typesense uses RocksDB to store your documents on the disk. If you do frequent writes or updates, you could benefit from running a compaction of the underlying RocksDB database. This could reduce the size of the database and decrease read latency. While the database will not block during this operation, we recommend running it during off-peak hours. +pub async fn compact_db(configuration: &configuration::Configuration) -> Result> { + + let uri_str = format!("{}/operations/db/compact", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Returns the status of any ongoing schema change operations. If no schema changes are in progress, returns an empty response. +pub async fn get_schema_changes(configuration: &configuration::Configuration) -> Result, Error> { + + let uri_str = format!("{}/operations/schema_changes", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec<models::SchemaChangeStatus>`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec<models::SchemaChangeStatus>`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Retrieve the stats about API endpoints. +pub async fn retrieve_api_stats(configuration: &configuration::Configuration) -> Result> { + + let uri_str = format!("{}/stats.json", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ApiStatsResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ApiStatsResponse`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Retrieve the metrics. +pub async fn retrieve_metrics(configuration: &configuration::Configuration) -> Result> { + + let uri_str = format!("{}/metrics.json", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `serde_json::Value`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + /// Creates a point-in-time snapshot of a Typesense node's state and data in the specified directory. You can then backup the snapshot directory that gets created and later restore it as a data directory, as needed. -pub async fn take_snapshot( - configuration: &configuration::Configuration, - snapshot_path: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!("{}/operations/snapshot", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); - - local_var_req_builder = - local_var_req_builder.query(&[("snapshot_path", &snapshot_path.to_string())]); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), +pub async fn take_snapshot(configuration: &configuration::Configuration, params: TakeSnapshotParams) -> Result> { + + let uri_str = format!("{}/operations/snapshot", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + + req_builder = req_builder.query(&[("snapshot_path", ¶ms.snapshot_path.to_string())]); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Enable logging of requests that take over a defined threshold of time. Default is `-1` which disables slow request logging. Slow requests are logged to the primary log file, with the prefix SLOW REQUEST. +pub async fn toggle_slow_request_log(configuration: &configuration::Configuration, params: ToggleSlowRequestLogParams) -> Result> { + + let uri_str = format!("{}/config", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - Err(Error::ResponseError(local_var_error)) + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.toggle_slow_request_log_request); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Triggers a follower node to initiate the raft voting process, which triggers leader re-election. The follower node that you run this operation against will become the new leader, once this command succeeds. -pub async fn vote( - configuration: &configuration::Configuration, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!("{}/operations/vote", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), +pub async fn vote(configuration: &configuration::Configuration) -> Result> { + + let uri_str = format!("{}/operations/vote", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`")))), + } } else { - let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } + diff --git a/typesense_codegen/src/apis/override_api.rs b/typesense_codegen/src/apis/override_api.rs index 1cad7a8..0f8287f 100644 --- a/typesense_codegen/src/apis/override_api.rs +++ b/typesense_codegen/src/apis/override_api.rs @@ -3,13 +3,26 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ -use super::{Error, configuration}; -use crate::apis::ResponseContent; + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + +/// struct for passing parameters to the method [`get_search_override`] +#[derive(Clone, Debug)] +pub struct GetSearchOverrideParams { + /// The name of the collection + pub collection_name: String, + /// The id of the search override + pub override_id: String +} + /// struct for typed errors of method [`get_search_override`] #[derive(Debug, Clone, Serialize, Deserialize)] @@ -18,55 +31,47 @@ pub enum GetSearchOverrideError { UnknownValue(serde_json::Value), } -/// Retrieve the details of a search override, given its id. -pub async fn get_search_override( - configuration: &configuration::Configuration, - collection_name: &str, - override_id: &str, -) -> Result> { - let local_var_configuration = configuration; - let local_var_client = &local_var_configuration.client; +/// Retrieve the details of a search override, given its id. +pub async fn get_search_override(configuration: &configuration::Configuration, params: GetSearchOverrideParams) -> Result> { - let local_var_uri_str = format!( - "{}/collections/{collectionName}/overrides/{overrideId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - overrideId = crate::apis::urlencode(override_id) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + let uri_str = format!("{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), overrideId=crate::apis::urlencode(params.override_id)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverride`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } + diff --git a/typesense_codegen/src/apis/presets_api.rs b/typesense_codegen/src/apis/presets_api.rs new file mode 100644 index 0000000..5789d17 --- /dev/null +++ b/typesense_codegen/src/apis/presets_api.rs @@ -0,0 +1,245 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + +/// struct for passing parameters to the method [`delete_preset`] +#[derive(Clone, Debug)] +pub struct DeletePresetParams { + /// The ID of the preset to delete. + pub preset_id: String +} + +/// struct for passing parameters to the method [`retrieve_preset`] +#[derive(Clone, Debug)] +pub struct RetrievePresetParams { + /// The ID of the preset to retrieve. + pub preset_id: String +} + +/// struct for passing parameters to the method [`upsert_preset`] +#[derive(Clone, Debug)] +pub struct UpsertPresetParams { + /// The name of the preset set to upsert. + pub preset_id: String, + /// The stopwords set to upsert. + pub preset_upsert_schema: models::PresetUpsertSchema +} + + +/// struct for typed errors of method [`delete_preset`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum DeletePresetError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_all_presets`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveAllPresetsError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_preset`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrievePresetError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`upsert_preset`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum UpsertPresetError { + Status400(models::ApiResponse), + UnknownValue(serde_json::Value), +} + + +/// Permanently deletes a preset, given it's name. +pub async fn delete_preset(configuration: &configuration::Configuration, params: DeletePresetParams) -> Result> { + + let uri_str = format!("{}/presets/{presetId}", configuration.base_path, presetId=crate::apis::urlencode(params.preset_id)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::PresetDeleteSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::PresetDeleteSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Retrieve the details of all presets +pub async fn retrieve_all_presets(configuration: &configuration::Configuration) -> Result> { + + let uri_str = format!("{}/presets", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::PresetsRetrieveSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::PresetsRetrieveSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Retrieve the details of a preset, given it's name. +pub async fn retrieve_preset(configuration: &configuration::Configuration, params: RetrievePresetParams) -> Result> { + + let uri_str = format!("{}/presets/{presetId}", configuration.base_path, presetId=crate::apis::urlencode(params.preset_id)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::PresetSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::PresetSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Create or update an existing preset. +pub async fn upsert_preset(configuration: &configuration::Configuration, params: UpsertPresetParams) -> Result> { + + let uri_str = format!("{}/presets/{presetId}", configuration.base_path, presetId=crate::apis::urlencode(params.preset_id)); + let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.preset_upsert_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::PresetSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::PresetSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + diff --git a/typesense_codegen/src/apis/promote_api.rs b/typesense_codegen/src/apis/promote_api.rs deleted file mode 100644 index 55a2c7e..0000000 --- a/typesense_codegen/src/apis/promote_api.rs +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Typesense API - * - * An open source search engine for building delightful search experiences. - * - * The version of the OpenAPI document: 0.25.0 - * - * Generated by: https://openapi-generator.tech - */ - -use super::{Error, configuration}; -use crate::apis::ResponseContent; - -/// struct for typed errors of method [`delete_search_override`] -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub enum DeleteSearchOverrideError { - Status404(crate::models::ApiResponse), - UnknownValue(serde_json::Value), -} - -/// struct for typed errors of method [`get_search_overrides`] -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub enum GetSearchOverridesError { - UnknownValue(serde_json::Value), -} - -/// struct for typed errors of method [`upsert_search_override`] -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub enum UpsertSearchOverrideError { - Status404(crate::models::ApiResponse), - UnknownValue(serde_json::Value), -} - -pub async fn delete_search_override( - configuration: &configuration::Configuration, - collection_name: &str, - override_id: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/overrides/{overrideId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - overrideId = crate::apis::urlencode(override_id) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) - } -} - -pub async fn get_search_overrides( - configuration: &configuration::Configuration, - collection_name: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/overrides", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) - } -} - -/// Create or update an override to promote certain documents over others. Using overrides, you can include or exclude specific documents for a given query. -pub async fn upsert_search_override( - configuration: &configuration::Configuration, - collection_name: &str, - override_id: &str, - search_override_schema: crate::models::SearchOverrideSchema, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/overrides/{overrideId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - overrideId = crate::apis::urlencode(override_id) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::PUT, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; - local_var_req_builder = local_var_req_builder.json(&search_override_schema); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) - } -} diff --git a/typesense_codegen/src/apis/stemming_api.rs b/typesense_codegen/src/apis/stemming_api.rs new file mode 100644 index 0000000..847f35b --- /dev/null +++ b/typesense_codegen/src/apis/stemming_api.rs @@ -0,0 +1,188 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + +/// struct for passing parameters to the method [`get_stemming_dictionary`] +#[derive(Clone, Debug)] +pub struct GetStemmingDictionaryParams { + /// The ID of the dictionary to retrieve + pub dictionary_id: String +} + +/// struct for passing parameters to the method [`import_stemming_dictionary`] +#[derive(Clone, Debug)] +pub struct ImportStemmingDictionaryParams { + /// The ID to assign to the dictionary + pub id: String, + /// The JSONL file containing word mappings + pub body: String +} + + +/// struct for typed errors of method [`get_stemming_dictionary`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetStemmingDictionaryError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`import_stemming_dictionary`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ImportStemmingDictionaryError { + Status400(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`list_stemming_dictionaries`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ListStemmingDictionariesError { + UnknownValue(serde_json::Value), +} + + +/// Fetch details of a specific stemming dictionary. +pub async fn get_stemming_dictionary(configuration: &configuration::Configuration, params: GetStemmingDictionaryParams) -> Result> { + + let uri_str = format!("{}/stemming/dictionaries/{dictionaryId}", configuration.base_path, dictionaryId=crate::apis::urlencode(params.dictionary_id)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::StemmingDictionary`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::StemmingDictionary`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Upload a JSONL file containing word mappings to create or update a stemming dictionary. +pub async fn import_stemming_dictionary(configuration: &configuration::Configuration, params: ImportStemmingDictionaryParams) -> Result> { + + let uri_str = format!("{}/stemming/dictionaries/import", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + + req_builder = req_builder.query(&[("id", ¶ms.id.to_string())]); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.body); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `String`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `String`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Retrieve a list of all available stemming dictionaries. +pub async fn list_stemming_dictionaries(configuration: &configuration::Configuration) -> Result> { + + let uri_str = format!("{}/stemming/dictionaries", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ListStemmingDictionaries200Response`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ListStemmingDictionaries200Response`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + diff --git a/typesense_codegen/src/apis/stopwords_api.rs b/typesense_codegen/src/apis/stopwords_api.rs new file mode 100644 index 0000000..d80744a --- /dev/null +++ b/typesense_codegen/src/apis/stopwords_api.rs @@ -0,0 +1,245 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + +/// struct for passing parameters to the method [`delete_stopwords_set`] +#[derive(Clone, Debug)] +pub struct DeleteStopwordsSetParams { + /// The ID of the stopwords set to delete. + pub set_id: String +} + +/// struct for passing parameters to the method [`retrieve_stopwords_set`] +#[derive(Clone, Debug)] +pub struct RetrieveStopwordsSetParams { + /// The ID of the stopwords set to retrieve. + pub set_id: String +} + +/// struct for passing parameters to the method [`upsert_stopwords_set`] +#[derive(Clone, Debug)] +pub struct UpsertStopwordsSetParams { + /// The ID of the stopwords set to upsert. + pub set_id: String, + /// The stopwords set to upsert. + pub stopwords_set_upsert_schema: models::StopwordsSetUpsertSchema +} + + +/// struct for typed errors of method [`delete_stopwords_set`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum DeleteStopwordsSetError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_stopwords_set`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveStopwordsSetError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_stopwords_sets`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveStopwordsSetsError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`upsert_stopwords_set`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum UpsertStopwordsSetError { + Status400(models::ApiResponse), + UnknownValue(serde_json::Value), +} + + +/// Permanently deletes a stopwords set, given it's name. +pub async fn delete_stopwords_set(configuration: &configuration::Configuration, params: DeleteStopwordsSetParams) -> Result> { + + let uri_str = format!("{}/stopwords/{setId}", configuration.base_path, setId=crate::apis::urlencode(params.set_id)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::DeleteStopwordsSet200Response`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::DeleteStopwordsSet200Response`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Retrieve the details of a stopwords set, given it's name. +pub async fn retrieve_stopwords_set(configuration: &configuration::Configuration, params: RetrieveStopwordsSetParams) -> Result> { + + let uri_str = format!("{}/stopwords/{setId}", configuration.base_path, setId=crate::apis::urlencode(params.set_id)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::StopwordsSetRetrieveSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::StopwordsSetRetrieveSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Retrieve the details of all stopwords sets +pub async fn retrieve_stopwords_sets(configuration: &configuration::Configuration) -> Result> { + + let uri_str = format!("{}/stopwords", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::StopwordsSetsRetrieveAllSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::StopwordsSetsRetrieveAllSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// When an analytics rule is created, we give it a name and describe the type, the source collections and the destination collection. +pub async fn upsert_stopwords_set(configuration: &configuration::Configuration, params: UpsertStopwordsSetParams) -> Result> { + + let uri_str = format!("{}/stopwords/{setId}", configuration.base_path, setId=crate::apis::urlencode(params.set_id)); + let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.stopwords_set_upsert_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::StopwordsSetSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::StopwordsSetSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + diff --git a/typesense_codegen/src/apis/synonyms_api.rs b/typesense_codegen/src/apis/synonyms_api.rs new file mode 100644 index 0000000..f568fc6 --- /dev/null +++ b/typesense_codegen/src/apis/synonyms_api.rs @@ -0,0 +1,245 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + +/// struct for passing parameters to the method [`delete_synonym_set`] +#[derive(Clone, Debug)] +pub struct DeleteSynonymSetParams { + /// The name of the synonym set to delete + pub synonym_set_name: String +} + +/// struct for passing parameters to the method [`retrieve_synonym_set`] +#[derive(Clone, Debug)] +pub struct RetrieveSynonymSetParams { + /// The name of the synonym set to retrieve + pub synonym_set_name: String +} + +/// struct for passing parameters to the method [`upsert_synonym_set`] +#[derive(Clone, Debug)] +pub struct UpsertSynonymSetParams { + /// The name of the synonym set to create/update + pub synonym_set_name: String, + /// The synonym set to be created/updated + pub synonym_set_create_schema: models::SynonymSetCreateSchema +} + + +/// struct for typed errors of method [`delete_synonym_set`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum DeleteSynonymSetError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_synonym_set`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveSynonymSetError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_synonym_sets`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveSynonymSetsError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`upsert_synonym_set`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum UpsertSynonymSetError { + Status400(models::ApiResponse), + UnknownValue(serde_json::Value), +} + + +/// Delete a specific synonym set by its name +pub async fn delete_synonym_set(configuration: &configuration::Configuration, params: DeleteSynonymSetParams) -> Result> { + + let uri_str = format!("{}/synonym_sets/{synonymSetName}", configuration.base_path, synonymSetName=crate::apis::urlencode(params.synonym_set_name)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SynonymSetDeleteSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SynonymSetDeleteSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Retrieve a specific synonym set by its name +pub async fn retrieve_synonym_set(configuration: &configuration::Configuration, params: RetrieveSynonymSetParams) -> Result> { + + let uri_str = format!("{}/synonym_sets/{synonymSetName}", configuration.base_path, synonymSetName=crate::apis::urlencode(params.synonym_set_name)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SynonymSetCreateSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SynonymSetCreateSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Retrieve all synonym sets +pub async fn retrieve_synonym_sets(configuration: &configuration::Configuration) -> Result, Error> { + + let uri_str = format!("{}/synonym_sets", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec<models::SynonymSetSchema>`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec<models::SynonymSetSchema>`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Create or update a synonym set with the given name +pub async fn upsert_synonym_set(configuration: &configuration::Configuration, params: UpsertSynonymSetParams) -> Result> { + + let uri_str = format!("{}/synonym_sets/{synonymSetName}", configuration.base_path, synonymSetName=crate::apis::urlencode(params.synonym_set_name)); + let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.synonym_set_create_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SynonymSetSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SynonymSetSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + diff --git a/typesense_codegen/src/lib.rs b/typesense_codegen/src/lib.rs index 4c8b05d..f9a96b5 100644 --- a/typesense_codegen/src/lib.rs +++ b/typesense_codegen/src/lib.rs @@ -1,5 +1,6 @@ -#[macro_use] -extern crate serde_derive; +#![allow(unused_imports)] +#![allow(clippy::all)] +#![allow(elided_lifetimes_in_paths)] pub mod apis; pub mod models; diff --git a/typesense_codegen/src/models/analytics_event.rs b/typesense_codegen/src/models/analytics_event.rs new file mode 100644 index 0000000..df09edc --- /dev/null +++ b/typesense_codegen/src/models/analytics_event.rs @@ -0,0 +1,35 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct AnalyticsEvent { + /// Name of the analytics rule this event corresponds to + #[serde(rename = "name")] + pub name: String, + /// Type of event (e.g., click, conversion, query, visit) + #[serde(rename = "event_type")] + pub event_type: String, + #[serde(rename = "data")] + pub data: Box, +} + +impl AnalyticsEvent { + pub fn new(name: String, event_type: String, data: models::AnalyticsEventData) -> AnalyticsEvent { + AnalyticsEvent { + name, + event_type, + data: Box::new(data), + } + } +} + diff --git a/typesense_codegen/src/models/analytics_event_create_response.rs b/typesense_codegen/src/models/analytics_event_create_response.rs new file mode 100644 index 0000000..6e5e054 --- /dev/null +++ b/typesense_codegen/src/models/analytics_event_create_response.rs @@ -0,0 +1,27 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct AnalyticsEventCreateResponse { + #[serde(rename = "ok")] + pub ok: bool, +} + +impl AnalyticsEventCreateResponse { + pub fn new(ok: bool) -> AnalyticsEventCreateResponse { + AnalyticsEventCreateResponse { + ok, + } + } +} + diff --git a/typesense_codegen/src/models/analytics_event_data.rs b/typesense_codegen/src/models/analytics_event_data.rs new file mode 100644 index 0000000..d94fa7a --- /dev/null +++ b/typesense_codegen/src/models/analytics_event_data.rs @@ -0,0 +1,41 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +/// AnalyticsEventData : Event payload +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct AnalyticsEventData { + #[serde(rename = "user_id", skip_serializing_if = "Option::is_none")] + pub user_id: Option, + #[serde(rename = "doc_id", skip_serializing_if = "Option::is_none")] + pub doc_id: Option, + #[serde(rename = "doc_ids", skip_serializing_if = "Option::is_none")] + pub doc_ids: Option>, + #[serde(rename = "q", skip_serializing_if = "Option::is_none")] + pub q: Option, + #[serde(rename = "analytics_tag", skip_serializing_if = "Option::is_none")] + pub analytics_tag: Option, +} + +impl AnalyticsEventData { + /// Event payload + pub fn new() -> AnalyticsEventData { + AnalyticsEventData { + user_id: None, + doc_id: None, + doc_ids: None, + q: None, + analytics_tag: None, + } + } +} + diff --git a/typesense_codegen/src/models/analytics_events_response.rs b/typesense_codegen/src/models/analytics_events_response.rs new file mode 100644 index 0000000..43271dc --- /dev/null +++ b/typesense_codegen/src/models/analytics_events_response.rs @@ -0,0 +1,27 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct AnalyticsEventsResponse { + #[serde(rename = "events")] + pub events: Vec, +} + +impl AnalyticsEventsResponse { + pub fn new(events: Vec) -> AnalyticsEventsResponse { + AnalyticsEventsResponse { + events, + } + } +} + diff --git a/typesense_codegen/src/models/analytics_events_response_events_inner.rs b/typesense_codegen/src/models/analytics_events_response_events_inner.rs new file mode 100644 index 0000000..3f5b2d1 --- /dev/null +++ b/typesense_codegen/src/models/analytics_events_response_events_inner.rs @@ -0,0 +1,48 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct AnalyticsEventsResponseEventsInner { + #[serde(rename = "name", skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(rename = "event_type", skip_serializing_if = "Option::is_none")] + pub event_type: Option, + #[serde(rename = "collection", skip_serializing_if = "Option::is_none")] + pub collection: Option, + #[serde(rename = "timestamp", skip_serializing_if = "Option::is_none")] + pub timestamp: Option, + #[serde(rename = "user_id", skip_serializing_if = "Option::is_none")] + pub user_id: Option, + #[serde(rename = "doc_id", skip_serializing_if = "Option::is_none")] + pub doc_id: Option, + #[serde(rename = "doc_ids", skip_serializing_if = "Option::is_none")] + pub doc_ids: Option>, + #[serde(rename = "query", skip_serializing_if = "Option::is_none")] + pub query: Option, +} + +impl AnalyticsEventsResponseEventsInner { + pub fn new() -> AnalyticsEventsResponseEventsInner { + AnalyticsEventsResponseEventsInner { + name: None, + event_type: None, + collection: None, + timestamp: None, + user_id: None, + doc_id: None, + doc_ids: None, + query: None, + } + } +} + diff --git a/typesense_codegen/src/models/analytics_rule.rs b/typesense_codegen/src/models/analytics_rule.rs new file mode 100644 index 0000000..6044d9b --- /dev/null +++ b/typesense_codegen/src/models/analytics_rule.rs @@ -0,0 +1,60 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct AnalyticsRule { + #[serde(rename = "name")] + pub name: String, + #[serde(rename = "type")] + pub r#type: Type, + #[serde(rename = "collection")] + pub collection: String, + #[serde(rename = "event_type")] + pub event_type: String, + #[serde(rename = "rule_tag", skip_serializing_if = "Option::is_none")] + pub rule_tag: Option, + #[serde(rename = "params", skip_serializing_if = "Option::is_none")] + pub params: Option>, +} + +impl AnalyticsRule { + pub fn new(name: String, r#type: Type, collection: String, event_type: String) -> AnalyticsRule { + AnalyticsRule { + name, + r#type, + collection, + event_type, + rule_tag: None, + params: None, + } + } +} +/// +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum Type { + #[serde(rename = "popular_queries")] + PopularQueries, + #[serde(rename = "nohits_queries")] + NohitsQueries, + #[serde(rename = "counter")] + Counter, + #[serde(rename = "log")] + Log, +} + +impl Default for Type { + fn default() -> Type { + Self::PopularQueries + } +} + diff --git a/typesense_codegen/src/models/analytics_rule_create.rs b/typesense_codegen/src/models/analytics_rule_create.rs new file mode 100644 index 0000000..4685277 --- /dev/null +++ b/typesense_codegen/src/models/analytics_rule_create.rs @@ -0,0 +1,60 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct AnalyticsRuleCreate { + #[serde(rename = "name")] + pub name: String, + #[serde(rename = "type")] + pub r#type: Type, + #[serde(rename = "collection")] + pub collection: String, + #[serde(rename = "event_type")] + pub event_type: String, + #[serde(rename = "rule_tag", skip_serializing_if = "Option::is_none")] + pub rule_tag: Option, + #[serde(rename = "params", skip_serializing_if = "Option::is_none")] + pub params: Option>, +} + +impl AnalyticsRuleCreate { + pub fn new(name: String, r#type: Type, collection: String, event_type: String) -> AnalyticsRuleCreate { + AnalyticsRuleCreate { + name, + r#type, + collection, + event_type, + rule_tag: None, + params: None, + } + } +} +/// +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum Type { + #[serde(rename = "popular_queries")] + PopularQueries, + #[serde(rename = "nohits_queries")] + NohitsQueries, + #[serde(rename = "counter")] + Counter, + #[serde(rename = "log")] + Log, +} + +impl Default for Type { + fn default() -> Type { + Self::PopularQueries + } +} + diff --git a/typesense_codegen/src/models/analytics_rule_create_params.rs b/typesense_codegen/src/models/analytics_rule_create_params.rs new file mode 100644 index 0000000..e62debd --- /dev/null +++ b/typesense_codegen/src/models/analytics_rule_create_params.rs @@ -0,0 +1,45 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct AnalyticsRuleCreateParams { + #[serde(rename = "destination_collection", skip_serializing_if = "Option::is_none")] + pub destination_collection: Option, + #[serde(rename = "limit", skip_serializing_if = "Option::is_none")] + pub limit: Option, + #[serde(rename = "capture_search_requests", skip_serializing_if = "Option::is_none")] + pub capture_search_requests: Option, + #[serde(rename = "meta_fields", skip_serializing_if = "Option::is_none")] + pub meta_fields: Option>, + #[serde(rename = "expand_query", skip_serializing_if = "Option::is_none")] + pub expand_query: Option, + #[serde(rename = "counter_field", skip_serializing_if = "Option::is_none")] + pub counter_field: Option, + #[serde(rename = "weight", skip_serializing_if = "Option::is_none")] + pub weight: Option, +} + +impl AnalyticsRuleCreateParams { + pub fn new() -> AnalyticsRuleCreateParams { + AnalyticsRuleCreateParams { + destination_collection: None, + limit: None, + capture_search_requests: None, + meta_fields: None, + expand_query: None, + counter_field: None, + weight: None, + } + } +} + diff --git a/typesense_codegen/src/models/analytics_rule_parameters.rs b/typesense_codegen/src/models/analytics_rule_parameters.rs deleted file mode 100644 index 32b4de4..0000000 --- a/typesense_codegen/src/models/analytics_rule_parameters.rs +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Typesense API - * - * An open source search engine for building delightful search experiences. - * - * The version of the OpenAPI document: 0.25.0 - * - * Generated by: https://openapi-generator.tech - */ - -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct AnalyticsRuleParameters { - #[serde(rename = "source")] - pub source: Box, - #[serde(rename = "destination")] - pub destination: Box, - #[serde(rename = "limit")] - pub limit: i32, -} - -impl AnalyticsRuleParameters { - pub fn new( - source: crate::models::AnalyticsRuleParametersSource, - destination: crate::models::AnalyticsRuleParametersDestination, - limit: i32, - ) -> AnalyticsRuleParameters { - AnalyticsRuleParameters { - source: Box::new(source), - destination: Box::new(destination), - limit, - } - } -} diff --git a/typesense_codegen/src/models/analytics_rule_parameters_destination.rs b/typesense_codegen/src/models/analytics_rule_parameters_destination.rs deleted file mode 100644 index b713af8..0000000 --- a/typesense_codegen/src/models/analytics_rule_parameters_destination.rs +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Typesense API - * - * An open source search engine for building delightful search experiences. - * - * The version of the OpenAPI document: 0.25.0 - * - * Generated by: https://openapi-generator.tech - */ - -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct AnalyticsRuleParametersDestination { - #[serde(rename = "collection", skip_serializing_if = "Option::is_none")] - pub collection: Option, -} - -impl AnalyticsRuleParametersDestination { - pub fn new() -> AnalyticsRuleParametersDestination { - AnalyticsRuleParametersDestination { collection: None } - } -} diff --git a/typesense_codegen/src/models/analytics_rule_parameters_source.rs b/typesense_codegen/src/models/analytics_rule_parameters_source.rs deleted file mode 100644 index ae055fa..0000000 --- a/typesense_codegen/src/models/analytics_rule_parameters_source.rs +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Typesense API - * - * An open source search engine for building delightful search experiences. - * - * The version of the OpenAPI document: 0.25.0 - * - * Generated by: https://openapi-generator.tech - */ - -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct AnalyticsRuleParametersSource { - #[serde(rename = "collections", skip_serializing_if = "Option::is_none")] - pub collections: Option>, -} - -impl AnalyticsRuleParametersSource { - pub fn new() -> AnalyticsRuleParametersSource { - AnalyticsRuleParametersSource { collections: None } - } -} diff --git a/typesense_codegen/src/models/analytics_rule_schema.rs b/typesense_codegen/src/models/analytics_rule_schema.rs deleted file mode 100644 index 4d9c266..0000000 --- a/typesense_codegen/src/models/analytics_rule_schema.rs +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Typesense API - * - * An open source search engine for building delightful search experiences. - * - * The version of the OpenAPI document: 0.25.0 - * - * Generated by: https://openapi-generator.tech - */ - -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct AnalyticsRuleSchema { - #[serde(rename = "name")] - pub name: String, - #[serde(rename = "type")] - pub r#type: String, - #[serde(rename = "params")] - pub params: Box, -} - -impl AnalyticsRuleSchema { - pub fn new( - name: String, - r#type: String, - params: crate::models::AnalyticsRuleParameters, - ) -> AnalyticsRuleSchema { - AnalyticsRuleSchema { - name, - r#type, - params: Box::new(params), - } - } -} diff --git a/typesense_codegen/src/models/analytics_rule_update.rs b/typesense_codegen/src/models/analytics_rule_update.rs new file mode 100644 index 0000000..78d0fad --- /dev/null +++ b/typesense_codegen/src/models/analytics_rule_update.rs @@ -0,0 +1,35 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +/// AnalyticsRuleUpdate : Fields allowed to update on an analytics rule +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct AnalyticsRuleUpdate { + #[serde(rename = "name", skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(rename = "rule_tag", skip_serializing_if = "Option::is_none")] + pub rule_tag: Option, + #[serde(rename = "params", skip_serializing_if = "Option::is_none")] + pub params: Option>, +} + +impl AnalyticsRuleUpdate { + /// Fields allowed to update on an analytics rule + pub fn new() -> AnalyticsRuleUpdate { + AnalyticsRuleUpdate { + name: None, + rule_tag: None, + params: None, + } + } +} + diff --git a/typesense_codegen/src/models/analytics_rules_retrieve_schema.rs b/typesense_codegen/src/models/analytics_rules_retrieve_schema.rs deleted file mode 100644 index ed32555..0000000 --- a/typesense_codegen/src/models/analytics_rules_retrieve_schema.rs +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Typesense API - * - * An open source search engine for building delightful search experiences. - * - * The version of the OpenAPI document: 0.25.0 - * - * Generated by: https://openapi-generator.tech - */ - -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct AnalyticsRulesRetrieveSchema { - #[serde(rename = "rules", skip_serializing_if = "Option::is_none")] - pub rules: Option>, -} - -impl AnalyticsRulesRetrieveSchema { - pub fn new() -> AnalyticsRulesRetrieveSchema { - AnalyticsRulesRetrieveSchema { rules: None } - } -} diff --git a/typesense_codegen/src/models/analytics_status.rs b/typesense_codegen/src/models/analytics_status.rs new file mode 100644 index 0000000..8cc6d1a --- /dev/null +++ b/typesense_codegen/src/models/analytics_status.rs @@ -0,0 +1,45 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct AnalyticsStatus { + #[serde(rename = "popular_prefix_queries", skip_serializing_if = "Option::is_none")] + pub popular_prefix_queries: Option, + #[serde(rename = "nohits_prefix_queries", skip_serializing_if = "Option::is_none")] + pub nohits_prefix_queries: Option, + #[serde(rename = "log_prefix_queries", skip_serializing_if = "Option::is_none")] + pub log_prefix_queries: Option, + #[serde(rename = "query_log_events", skip_serializing_if = "Option::is_none")] + pub query_log_events: Option, + #[serde(rename = "query_counter_events", skip_serializing_if = "Option::is_none")] + pub query_counter_events: Option, + #[serde(rename = "doc_log_events", skip_serializing_if = "Option::is_none")] + pub doc_log_events: Option, + #[serde(rename = "doc_counter_events", skip_serializing_if = "Option::is_none")] + pub doc_counter_events: Option, +} + +impl AnalyticsStatus { + pub fn new() -> AnalyticsStatus { + AnalyticsStatus { + popular_prefix_queries: None, + nohits_prefix_queries: None, + log_prefix_queries: None, + query_log_events: None, + query_counter_events: None, + doc_log_events: None, + doc_counter_events: None, + } + } +} + diff --git a/typesense_codegen/src/models/api_key.rs b/typesense_codegen/src/models/api_key.rs index 7de6d81..24fc861 100644 --- a/typesense_codegen/src/models/api_key.rs +++ b/typesense_codegen/src/models/api_key.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct ApiKey { #[serde(rename = "value", skip_serializing_if = "Option::is_none")] @@ -39,3 +42,4 @@ impl ApiKey { } } } + diff --git a/typesense_codegen/src/models/api_key_delete_response.rs b/typesense_codegen/src/models/api_key_delete_response.rs new file mode 100644 index 0000000..e59d0b5 --- /dev/null +++ b/typesense_codegen/src/models/api_key_delete_response.rs @@ -0,0 +1,28 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct ApiKeyDeleteResponse { + /// The id of the API key that was deleted + #[serde(rename = "id")] + pub id: i64, +} + +impl ApiKeyDeleteResponse { + pub fn new(id: i64) -> ApiKeyDeleteResponse { + ApiKeyDeleteResponse { + id, + } + } +} + diff --git a/typesense_codegen/src/models/api_key_schema.rs b/typesense_codegen/src/models/api_key_schema.rs index 2f6cb2b..a25dc81 100644 --- a/typesense_codegen/src/models/api_key_schema.rs +++ b/typesense_codegen/src/models/api_key_schema.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct ApiKeySchema { #[serde(rename = "value", skip_serializing_if = "Option::is_none")] @@ -23,11 +26,7 @@ pub struct ApiKeySchema { } impl ApiKeySchema { - pub fn new( - description: String, - actions: Vec, - collections: Vec, - ) -> ApiKeySchema { + pub fn new(description: String, actions: Vec, collections: Vec) -> ApiKeySchema { ApiKeySchema { value: None, description, @@ -37,3 +36,4 @@ impl ApiKeySchema { } } } + diff --git a/typesense_codegen/src/models/api_keys_response.rs b/typesense_codegen/src/models/api_keys_response.rs index f523a98..f416c2c 100644 --- a/typesense_codegen/src/models/api_keys_response.rs +++ b/typesense_codegen/src/models/api_keys_response.rs @@ -3,19 +3,25 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct ApiKeysResponse { #[serde(rename = "keys")] - pub keys: Vec, + pub keys: Vec, } impl ApiKeysResponse { - pub fn new(keys: Vec) -> ApiKeysResponse { - ApiKeysResponse { keys } + pub fn new(keys: Vec) -> ApiKeysResponse { + ApiKeysResponse { + keys, + } } } + diff --git a/typesense_codegen/src/models/api_response.rs b/typesense_codegen/src/models/api_response.rs index 691ea49..3fc9d03 100644 --- a/typesense_codegen/src/models/api_response.rs +++ b/typesense_codegen/src/models/api_response.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct ApiResponse { #[serde(rename = "message")] @@ -16,6 +19,9 @@ pub struct ApiResponse { impl ApiResponse { pub fn new(message: String) -> ApiResponse { - ApiResponse { message } + ApiResponse { + message, + } } } + diff --git a/typesense_codegen/src/models/api_stats_response.rs b/typesense_codegen/src/models/api_stats_response.rs new file mode 100644 index 0000000..9766f7f --- /dev/null +++ b/typesense_codegen/src/models/api_stats_response.rs @@ -0,0 +1,63 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct ApiStatsResponse { + #[serde(rename = "delete_latency_ms", skip_serializing_if = "Option::is_none")] + pub delete_latency_ms: Option, + #[serde(rename = "delete_requests_per_second", skip_serializing_if = "Option::is_none")] + pub delete_requests_per_second: Option, + #[serde(rename = "import_latency_ms", skip_serializing_if = "Option::is_none")] + pub import_latency_ms: Option, + #[serde(rename = "import_requests_per_second", skip_serializing_if = "Option::is_none")] + pub import_requests_per_second: Option, + #[serde(rename = "latency_ms", skip_serializing_if = "Option::is_none")] + pub latency_ms: Option, + #[serde(rename = "overloaded_requests_per_second", skip_serializing_if = "Option::is_none")] + pub overloaded_requests_per_second: Option, + #[serde(rename = "pending_write_batches", skip_serializing_if = "Option::is_none")] + pub pending_write_batches: Option, + #[serde(rename = "requests_per_second", skip_serializing_if = "Option::is_none")] + pub requests_per_second: Option, + #[serde(rename = "search_latency_ms", skip_serializing_if = "Option::is_none")] + pub search_latency_ms: Option, + #[serde(rename = "search_requests_per_second", skip_serializing_if = "Option::is_none")] + pub search_requests_per_second: Option, + #[serde(rename = "total_requests_per_second", skip_serializing_if = "Option::is_none")] + pub total_requests_per_second: Option, + #[serde(rename = "write_latency_ms", skip_serializing_if = "Option::is_none")] + pub write_latency_ms: Option, + #[serde(rename = "write_requests_per_second", skip_serializing_if = "Option::is_none")] + pub write_requests_per_second: Option, +} + +impl ApiStatsResponse { + pub fn new() -> ApiStatsResponse { + ApiStatsResponse { + delete_latency_ms: None, + delete_requests_per_second: None, + import_latency_ms: None, + import_requests_per_second: None, + latency_ms: None, + overloaded_requests_per_second: None, + pending_write_batches: None, + requests_per_second: None, + search_latency_ms: None, + search_requests_per_second: None, + total_requests_per_second: None, + write_latency_ms: None, + write_requests_per_second: None, + } + } +} + diff --git a/typesense_codegen/src/models/collection_alias.rs b/typesense_codegen/src/models/collection_alias.rs index b5ab76e..2b3afe8 100644 --- a/typesense_codegen/src/models/collection_alias.rs +++ b/typesense_codegen/src/models/collection_alias.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct CollectionAlias { /// Name of the collection alias @@ -26,3 +29,4 @@ impl CollectionAlias { } } } + diff --git a/typesense_codegen/src/models/collection_alias_schema.rs b/typesense_codegen/src/models/collection_alias_schema.rs index 279e88f..bcc4029 100644 --- a/typesense_codegen/src/models/collection_alias_schema.rs +++ b/typesense_codegen/src/models/collection_alias_schema.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct CollectionAliasSchema { /// Name of the collection you wish to map the alias to @@ -17,6 +20,9 @@ pub struct CollectionAliasSchema { impl CollectionAliasSchema { pub fn new(collection_name: String) -> CollectionAliasSchema { - CollectionAliasSchema { collection_name } + CollectionAliasSchema { + collection_name, + } } } + diff --git a/typesense_codegen/src/models/collection_aliases_response.rs b/typesense_codegen/src/models/collection_aliases_response.rs index 2bc9560..8b3fd5c 100644 --- a/typesense_codegen/src/models/collection_aliases_response.rs +++ b/typesense_codegen/src/models/collection_aliases_response.rs @@ -3,19 +3,25 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct CollectionAliasesResponse { #[serde(rename = "aliases")] - pub aliases: Vec, + pub aliases: Vec, } impl CollectionAliasesResponse { - pub fn new(aliases: Vec) -> CollectionAliasesResponse { - CollectionAliasesResponse { aliases } + pub fn new(aliases: Vec) -> CollectionAliasesResponse { + CollectionAliasesResponse { + aliases, + } } } + diff --git a/typesense_codegen/src/models/collection_response.rs b/typesense_codegen/src/models/collection_response.rs index 8676b81..dc31000 100644 --- a/typesense_codegen/src/models/collection_response.rs +++ b/typesense_codegen/src/models/collection_response.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct CollectionResponse { /// Name of the collection @@ -15,25 +18,27 @@ pub struct CollectionResponse { pub name: String, /// A list of fields for querying, filtering and faceting #[serde(rename = "fields")] - pub fields: Vec, + pub fields: Vec, /// The name of an int32 / float field that determines the order in which the search results are ranked when a sort_by clause is not provided during searching. This field must indicate some kind of popularity. - #[serde( - rename = "default_sorting_field", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "default_sorting_field", skip_serializing_if = "Option::is_none")] pub default_sorting_field: Option, - /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. + /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. #[serde(rename = "token_separators", skip_serializing_if = "Option::is_none")] pub token_separators: Option>, + /// List of synonym set names to associate with this collection + #[serde(rename = "synonym_sets", skip_serializing_if = "Option::is_none")] + pub synonym_sets: Option>, /// Enables experimental support at a collection level for nested object or object array fields. This field is only available if the Typesense server is version `0.24.0.rcn34` or later. - #[serde( - rename = "enable_nested_fields", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "enable_nested_fields", skip_serializing_if = "Option::is_none")] pub enable_nested_fields: Option, - /// List of symbols or special characters to be indexed. + /// List of symbols or special characters to be indexed. #[serde(rename = "symbols_to_index", skip_serializing_if = "Option::is_none")] pub symbols_to_index: Option>, + #[serde(rename = "voice_query_model", skip_serializing_if = "Option::is_none")] + pub voice_query_model: Option>, + /// Optional details about the collection, e.g., when it was created, who created it etc. + #[serde(rename = "metadata", skip_serializing_if = "Option::is_none")] + pub metadata: Option, /// Number of documents in the collection #[serde(rename = "num_documents")] pub num_documents: i64, @@ -43,21 +48,20 @@ pub struct CollectionResponse { } impl CollectionResponse { - pub fn new( - name: String, - fields: Vec, - num_documents: i64, - created_at: i64, - ) -> CollectionResponse { + pub fn new(name: String, fields: Vec, num_documents: i64, created_at: i64) -> CollectionResponse { CollectionResponse { name, fields, default_sorting_field: None, token_separators: None, + synonym_sets: None, enable_nested_fields: None, symbols_to_index: None, + voice_query_model: None, + metadata: None, num_documents, created_at, } } } + diff --git a/typesense_codegen/src/models/collection_schema.rs b/typesense_codegen/src/models/collection_schema.rs index 5a373f6..eef9df6 100644 --- a/typesense_codegen/src/models/collection_schema.rs +++ b/typesense_codegen/src/models/collection_schema.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct CollectionSchema { /// Name of the collection @@ -15,36 +18,42 @@ pub struct CollectionSchema { pub name: String, /// A list of fields for querying, filtering and faceting #[serde(rename = "fields")] - pub fields: Vec, + pub fields: Vec, /// The name of an int32 / float field that determines the order in which the search results are ranked when a sort_by clause is not provided during searching. This field must indicate some kind of popularity. - #[serde( - rename = "default_sorting_field", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "default_sorting_field", skip_serializing_if = "Option::is_none")] pub default_sorting_field: Option, - /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. + /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. #[serde(rename = "token_separators", skip_serializing_if = "Option::is_none")] pub token_separators: Option>, + /// List of synonym set names to associate with this collection + #[serde(rename = "synonym_sets", skip_serializing_if = "Option::is_none")] + pub synonym_sets: Option>, /// Enables experimental support at a collection level for nested object or object array fields. This field is only available if the Typesense server is version `0.24.0.rcn34` or later. - #[serde( - rename = "enable_nested_fields", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "enable_nested_fields", skip_serializing_if = "Option::is_none")] pub enable_nested_fields: Option, - /// List of symbols or special characters to be indexed. + /// List of symbols or special characters to be indexed. #[serde(rename = "symbols_to_index", skip_serializing_if = "Option::is_none")] pub symbols_to_index: Option>, + #[serde(rename = "voice_query_model", skip_serializing_if = "Option::is_none")] + pub voice_query_model: Option>, + /// Optional details about the collection, e.g., when it was created, who created it etc. + #[serde(rename = "metadata", skip_serializing_if = "Option::is_none")] + pub metadata: Option, } impl CollectionSchema { - pub fn new(name: String, fields: Vec) -> CollectionSchema { + pub fn new(name: String, fields: Vec) -> CollectionSchema { CollectionSchema { name, fields, default_sorting_field: None, token_separators: None, + synonym_sets: None, enable_nested_fields: None, symbols_to_index: None, + voice_query_model: None, + metadata: None, } } } + diff --git a/typesense_codegen/src/models/collection_update_schema.rs b/typesense_codegen/src/models/collection_update_schema.rs index f4a4078..494d3b9 100644 --- a/typesense_codegen/src/models/collection_update_schema.rs +++ b/typesense_codegen/src/models/collection_update_schema.rs @@ -3,20 +3,34 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct CollectionUpdateSchema { /// A list of fields for querying, filtering and faceting #[serde(rename = "fields")] - pub fields: Vec, + pub fields: Vec, + /// List of synonym set names to associate with this collection + #[serde(rename = "synonym_sets", skip_serializing_if = "Option::is_none")] + pub synonym_sets: Option>, + /// Optional details about the collection, e.g., when it was created, who created it etc. + #[serde(rename = "metadata", skip_serializing_if = "Option::is_none")] + pub metadata: Option, } impl CollectionUpdateSchema { - pub fn new(fields: Vec) -> CollectionUpdateSchema { - CollectionUpdateSchema { fields } + pub fn new(fields: Vec) -> CollectionUpdateSchema { + CollectionUpdateSchema { + fields, + synonym_sets: None, + metadata: None, + } } } + diff --git a/typesense_codegen/src/models/conversation_model_create_schema.rs b/typesense_codegen/src/models/conversation_model_create_schema.rs new file mode 100644 index 0000000..2a9eb42 --- /dev/null +++ b/typesense_codegen/src/models/conversation_model_create_schema.rs @@ -0,0 +1,60 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct ConversationModelCreateSchema { + /// An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. + #[serde(rename = "id", skip_serializing_if = "Option::is_none")] + pub id: Option, + /// Name of the LLM model offered by OpenAI, Cloudflare or vLLM + #[serde(rename = "model_name")] + pub model_name: String, + /// The LLM service's API Key + #[serde(rename = "api_key", skip_serializing_if = "Option::is_none")] + pub api_key: Option, + /// Typesense collection that stores the historical conversations + #[serde(rename = "history_collection")] + pub history_collection: String, + /// LLM service's account ID (only applicable for Cloudflare) + #[serde(rename = "account_id", skip_serializing_if = "Option::is_none")] + pub account_id: Option, + /// The system prompt that contains special instructions to the LLM + #[serde(rename = "system_prompt", skip_serializing_if = "Option::is_none")] + pub system_prompt: Option, + /// Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) + #[serde(rename = "ttl", skip_serializing_if = "Option::is_none")] + pub ttl: Option, + /// The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. + #[serde(rename = "max_bytes")] + pub max_bytes: i32, + /// URL of vLLM service + #[serde(rename = "vllm_url", skip_serializing_if = "Option::is_none")] + pub vllm_url: Option, +} + +impl ConversationModelCreateSchema { + pub fn new(model_name: String, history_collection: String, max_bytes: i32) -> ConversationModelCreateSchema { + ConversationModelCreateSchema { + id: None, + model_name, + api_key: None, + history_collection, + account_id: None, + system_prompt: None, + ttl: None, + max_bytes, + vllm_url: None, + } + } +} + diff --git a/typesense_codegen/src/models/conversation_model_schema.rs b/typesense_codegen/src/models/conversation_model_schema.rs new file mode 100644 index 0000000..d5a4a0d --- /dev/null +++ b/typesense_codegen/src/models/conversation_model_schema.rs @@ -0,0 +1,60 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct ConversationModelSchema { + /// An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. + #[serde(rename = "id")] + pub id: String, + /// Name of the LLM model offered by OpenAI, Cloudflare or vLLM + #[serde(rename = "model_name")] + pub model_name: String, + /// The LLM service's API Key + #[serde(rename = "api_key", skip_serializing_if = "Option::is_none")] + pub api_key: Option, + /// Typesense collection that stores the historical conversations + #[serde(rename = "history_collection")] + pub history_collection: String, + /// LLM service's account ID (only applicable for Cloudflare) + #[serde(rename = "account_id", skip_serializing_if = "Option::is_none")] + pub account_id: Option, + /// The system prompt that contains special instructions to the LLM + #[serde(rename = "system_prompt", skip_serializing_if = "Option::is_none")] + pub system_prompt: Option, + /// Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) + #[serde(rename = "ttl", skip_serializing_if = "Option::is_none")] + pub ttl: Option, + /// The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. + #[serde(rename = "max_bytes")] + pub max_bytes: i32, + /// URL of vLLM service + #[serde(rename = "vllm_url", skip_serializing_if = "Option::is_none")] + pub vllm_url: Option, +} + +impl ConversationModelSchema { + pub fn new(id: String, model_name: String, history_collection: String, max_bytes: i32) -> ConversationModelSchema { + ConversationModelSchema { + id, + model_name, + api_key: None, + history_collection, + account_id: None, + system_prompt: None, + ttl: None, + max_bytes, + vllm_url: None, + } + } +} + diff --git a/typesense_codegen/src/models/conversation_model_update_schema.rs b/typesense_codegen/src/models/conversation_model_update_schema.rs new file mode 100644 index 0000000..3dd5e8b --- /dev/null +++ b/typesense_codegen/src/models/conversation_model_update_schema.rs @@ -0,0 +1,60 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct ConversationModelUpdateSchema { + /// An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. + #[serde(rename = "id", skip_serializing_if = "Option::is_none")] + pub id: Option, + /// Name of the LLM model offered by OpenAI, Cloudflare or vLLM + #[serde(rename = "model_name", skip_serializing_if = "Option::is_none")] + pub model_name: Option, + /// The LLM service's API Key + #[serde(rename = "api_key", skip_serializing_if = "Option::is_none")] + pub api_key: Option, + /// Typesense collection that stores the historical conversations + #[serde(rename = "history_collection", skip_serializing_if = "Option::is_none")] + pub history_collection: Option, + /// LLM service's account ID (only applicable for Cloudflare) + #[serde(rename = "account_id", skip_serializing_if = "Option::is_none")] + pub account_id: Option, + /// The system prompt that contains special instructions to the LLM + #[serde(rename = "system_prompt", skip_serializing_if = "Option::is_none")] + pub system_prompt: Option, + /// Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) + #[serde(rename = "ttl", skip_serializing_if = "Option::is_none")] + pub ttl: Option, + /// The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. + #[serde(rename = "max_bytes", skip_serializing_if = "Option::is_none")] + pub max_bytes: Option, + /// URL of vLLM service + #[serde(rename = "vllm_url", skip_serializing_if = "Option::is_none")] + pub vllm_url: Option, +} + +impl ConversationModelUpdateSchema { + pub fn new() -> ConversationModelUpdateSchema { + ConversationModelUpdateSchema { + id: None, + model_name: None, + api_key: None, + history_collection: None, + account_id: None, + system_prompt: None, + ttl: None, + max_bytes: None, + vllm_url: None, + } + } +} + diff --git a/typesense_codegen/src/models/create_analytics_rule_200_response.rs b/typesense_codegen/src/models/create_analytics_rule_200_response.rs new file mode 100644 index 0000000..6d45dca --- /dev/null +++ b/typesense_codegen/src/models/create_analytics_rule_200_response.rs @@ -0,0 +1,44 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum CreateAnalyticsRule200Response { + AnalyticsRule(Box), + Array(Vec), +} + +impl Default for CreateAnalyticsRule200Response { + fn default() -> Self { + Self::AnalyticsRule(Default::default()) + } +} +/// +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum Type { + #[serde(rename = "popular_queries")] + PopularQueries, + #[serde(rename = "nohits_queries")] + NohitsQueries, + #[serde(rename = "counter")] + Counter, + #[serde(rename = "log")] + Log, +} + +impl Default for Type { + fn default() -> Type { + Self::PopularQueries + } +} + diff --git a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs new file mode 100644 index 0000000..03661e2 --- /dev/null +++ b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs @@ -0,0 +1,63 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct CreateAnalyticsRule200ResponseOneOfInner { + #[serde(rename = "name")] + pub name: String, + #[serde(rename = "type")] + pub r#type: Type, + #[serde(rename = "collection")] + pub collection: String, + #[serde(rename = "event_type")] + pub event_type: String, + #[serde(rename = "rule_tag", skip_serializing_if = "Option::is_none")] + pub rule_tag: Option, + #[serde(rename = "params", skip_serializing_if = "Option::is_none")] + pub params: Option>, + #[serde(rename = "error", skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +impl CreateAnalyticsRule200ResponseOneOfInner { + pub fn new(name: String, r#type: Type, collection: String, event_type: String) -> CreateAnalyticsRule200ResponseOneOfInner { + CreateAnalyticsRule200ResponseOneOfInner { + name, + r#type, + collection, + event_type, + rule_tag: None, + params: None, + error: None, + } + } +} +/// +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum Type { + #[serde(rename = "popular_queries")] + PopularQueries, + #[serde(rename = "nohits_queries")] + NohitsQueries, + #[serde(rename = "counter")] + Counter, + #[serde(rename = "log")] + Log, +} + +impl Default for Type { + fn default() -> Type { + Self::PopularQueries + } +} + diff --git a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs new file mode 100644 index 0000000..8e3d7a0 --- /dev/null +++ b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs @@ -0,0 +1,27 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct CreateAnalyticsRule200ResponseOneOfInnerAnyOf { + #[serde(rename = "error", skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +impl CreateAnalyticsRule200ResponseOneOfInnerAnyOf { + pub fn new() -> CreateAnalyticsRule200ResponseOneOfInnerAnyOf { + CreateAnalyticsRule200ResponseOneOfInnerAnyOf { + error: None, + } + } +} + diff --git a/typesense_codegen/src/models/create_analytics_rule_request.rs b/typesense_codegen/src/models/create_analytics_rule_request.rs new file mode 100644 index 0000000..597dec9 --- /dev/null +++ b/typesense_codegen/src/models/create_analytics_rule_request.rs @@ -0,0 +1,44 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum CreateAnalyticsRuleRequest { + AnalyticsRuleCreate(Box), + Array(Vec), +} + +impl Default for CreateAnalyticsRuleRequest { + fn default() -> Self { + Self::AnalyticsRuleCreate(Default::default()) + } +} +/// +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum Type { + #[serde(rename = "popular_queries")] + PopularQueries, + #[serde(rename = "nohits_queries")] + NohitsQueries, + #[serde(rename = "counter")] + Counter, + #[serde(rename = "log")] + Log, +} + +impl Default for Type { + fn default() -> Type { + Self::PopularQueries + } +} + diff --git a/typesense_codegen/src/models/debug_200_response.rs b/typesense_codegen/src/models/debug_200_response.rs index 365fc42..c9ba357 100644 --- a/typesense_codegen/src/models/debug_200_response.rs +++ b/typesense_codegen/src/models/debug_200_response.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct Debug200Response { #[serde(rename = "version", skip_serializing_if = "Option::is_none")] @@ -16,6 +19,9 @@ pub struct Debug200Response { impl Debug200Response { pub fn new() -> Debug200Response { - Debug200Response { version: None } + Debug200Response { + version: None, + } } } + diff --git a/typesense_codegen/src/models/delete_documents_200_response.rs b/typesense_codegen/src/models/delete_documents_200_response.rs index a509291..d1a8399 100644 --- a/typesense_codegen/src/models/delete_documents_200_response.rs +++ b/typesense_codegen/src/models/delete_documents_200_response.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct DeleteDocuments200Response { #[serde(rename = "num_deleted")] @@ -16,6 +19,9 @@ pub struct DeleteDocuments200Response { impl DeleteDocuments200Response { pub fn new(num_deleted: i32) -> DeleteDocuments200Response { - DeleteDocuments200Response { num_deleted } + DeleteDocuments200Response { + num_deleted, + } } } + diff --git a/typesense_codegen/src/models/delete_documents_delete_documents_parameters_parameter.rs b/typesense_codegen/src/models/delete_documents_delete_documents_parameters_parameter.rs deleted file mode 100644 index 722bdc4..0000000 --- a/typesense_codegen/src/models/delete_documents_delete_documents_parameters_parameter.rs +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Typesense API - * - * An open source search engine for building delightful search experiences. - * - * The version of the OpenAPI document: 0.25.0 - * - * Generated by: https://openapi-generator.tech - */ - -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct DeleteDocumentsDeleteDocumentsParametersParameter { - #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] - pub filter_by: Option, - /// Batch size parameter controls the number of documents that should be deleted at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. - #[serde(rename = "batch_size", skip_serializing_if = "Option::is_none")] - pub batch_size: Option, -} - -impl DeleteDocumentsDeleteDocumentsParametersParameter { - pub fn new() -> DeleteDocumentsDeleteDocumentsParametersParameter { - DeleteDocumentsDeleteDocumentsParametersParameter { - filter_by: None, - batch_size: None, - } - } -} diff --git a/typesense_codegen/src/models/delete_documents_parameters.rs b/typesense_codegen/src/models/delete_documents_parameters.rs new file mode 100644 index 0000000..e18797a --- /dev/null +++ b/typesense_codegen/src/models/delete_documents_parameters.rs @@ -0,0 +1,38 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct DeleteDocumentsParameters { + #[serde(rename = "filter_by")] + pub filter_by: String, + /// Batch size parameter controls the number of documents that should be deleted at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. + #[serde(rename = "batch_size", skip_serializing_if = "Option::is_none")] + pub batch_size: Option, + #[serde(rename = "ignore_not_found", skip_serializing_if = "Option::is_none")] + pub ignore_not_found: Option, + /// When true, removes all documents from the collection while preserving the collection and its schema. + #[serde(rename = "truncate", skip_serializing_if = "Option::is_none")] + pub truncate: Option, +} + +impl DeleteDocumentsParameters { + pub fn new(filter_by: String) -> DeleteDocumentsParameters { + DeleteDocumentsParameters { + filter_by, + batch_size: None, + ignore_not_found: None, + truncate: None, + } + } +} + diff --git a/typesense_codegen/src/models/delete_stopwords_set_200_response.rs b/typesense_codegen/src/models/delete_stopwords_set_200_response.rs new file mode 100644 index 0000000..25ab944 --- /dev/null +++ b/typesense_codegen/src/models/delete_stopwords_set_200_response.rs @@ -0,0 +1,27 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct DeleteStopwordsSet200Response { + #[serde(rename = "id")] + pub id: String, +} + +impl DeleteStopwordsSet200Response { + pub fn new(id: String) -> DeleteStopwordsSet200Response { + DeleteStopwordsSet200Response { + id, + } + } +} + diff --git a/typesense_codegen/src/models/dirty_values.rs b/typesense_codegen/src/models/dirty_values.rs new file mode 100644 index 0000000..5c3a422 --- /dev/null +++ b/typesense_codegen/src/models/dirty_values.rs @@ -0,0 +1,44 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +/// +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum DirtyValues { + #[serde(rename = "coerce_or_reject")] + CoerceOrReject, + #[serde(rename = "coerce_or_drop")] + CoerceOrDrop, + #[serde(rename = "drop")] + Drop, + #[serde(rename = "reject")] + Reject, + +} + +impl std::fmt::Display for DirtyValues { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + Self::CoerceOrReject => write!(f, "coerce_or_reject"), + Self::CoerceOrDrop => write!(f, "coerce_or_drop"), + Self::Drop => write!(f, "drop"), + Self::Reject => write!(f, "reject"), + } + } +} + +impl Default for DirtyValues { + fn default() -> DirtyValues { + Self::CoerceOrReject + } +} + diff --git a/typesense_codegen/src/models/drop_tokens_mode.rs b/typesense_codegen/src/models/drop_tokens_mode.rs new file mode 100644 index 0000000..9769869 --- /dev/null +++ b/typesense_codegen/src/models/drop_tokens_mode.rs @@ -0,0 +1,42 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +/// DropTokensMode : Dictates the direction in which the words in the query must be dropped when the original words in the query do not appear in any document. Values: right_to_left (default), left_to_right, both_sides:3 A note on both_sides:3 - for queries up to 3 tokens (words) in length, this mode will drop tokens from both sides and exhaustively rank all matching results. If query length is greater than 3 words, Typesense will just fallback to default behavior of right_to_left +/// Dictates the direction in which the words in the query must be dropped when the original words in the query do not appear in any document. Values: right_to_left (default), left_to_right, both_sides:3 A note on both_sides:3 - for queries up to 3 tokens (words) in length, this mode will drop tokens from both sides and exhaustively rank all matching results. If query length is greater than 3 words, Typesense will just fallback to default behavior of right_to_left +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum DropTokensMode { + #[serde(rename = "right_to_left")] + RightToLeft, + #[serde(rename = "left_to_right")] + LeftToRight, + #[serde(rename = "both_sides:3")] + BothSidesColon3, + +} + +impl std::fmt::Display for DropTokensMode { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + Self::RightToLeft => write!(f, "right_to_left"), + Self::LeftToRight => write!(f, "left_to_right"), + Self::BothSidesColon3 => write!(f, "both_sides:3"), + } + } +} + +impl Default for DropTokensMode { + fn default() -> DropTokensMode { + Self::RightToLeft + } +} + diff --git a/typesense_codegen/src/models/error_response.rs b/typesense_codegen/src/models/error_response.rs deleted file mode 100644 index ec2ef82..0000000 --- a/typesense_codegen/src/models/error_response.rs +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Typesense API - * - * An open source search engine for building delightful search experiences. - * - * The version of the OpenAPI document: 0.25.0 - * - * Generated by: https://openapi-generator.tech - */ - -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct ErrorResponse { - #[serde(rename = "message", skip_serializing_if = "Option::is_none")] - pub message: Option, -} - -impl ErrorResponse { - pub fn new() -> ErrorResponse { - ErrorResponse { message: None } - } -} diff --git a/typesense_codegen/src/models/export_documents_export_documents_parameters_parameter.rs b/typesense_codegen/src/models/export_documents_parameters.rs similarity index 52% rename from typesense_codegen/src/models/export_documents_export_documents_parameters_parameter.rs rename to typesense_codegen/src/models/export_documents_parameters.rs index c798028..d7fcc7b 100644 --- a/typesense_codegen/src/models/export_documents_export_documents_parameters_parameter.rs +++ b/typesense_codegen/src/models/export_documents_parameters.rs @@ -3,33 +3,34 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct ExportDocumentsExportDocumentsParametersParameter { +pub struct ExportDocumentsParameters { /// Filter conditions for refining your search results. Separate multiple conditions with &&. #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] pub filter_by: Option, /// List of fields from the document to include in the search result - #[serde(rename = "include_fields")] - pub include_fields: String, + #[serde(rename = "include_fields", skip_serializing_if = "Option::is_none")] + pub include_fields: Option, /// List of fields from the document to exclude in the search result - #[serde(rename = "exclude_fields")] - pub exclude_fields: String, + #[serde(rename = "exclude_fields", skip_serializing_if = "Option::is_none")] + pub exclude_fields: Option, } -impl ExportDocumentsExportDocumentsParametersParameter { - pub fn new( - include_fields: String, - exclude_fields: String, - ) -> ExportDocumentsExportDocumentsParametersParameter { - ExportDocumentsExportDocumentsParametersParameter { +impl ExportDocumentsParameters { + pub fn new() -> ExportDocumentsParameters { + ExportDocumentsParameters { filter_by: None, - include_fields, - exclude_fields, + include_fields: None, + exclude_fields: None, } } } + diff --git a/typesense_codegen/src/models/facet_counts.rs b/typesense_codegen/src/models/facet_counts.rs index 3e0a930..920a49e 100644 --- a/typesense_codegen/src/models/facet_counts.rs +++ b/typesense_codegen/src/models/facet_counts.rs @@ -3,19 +3,22 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct FacetCounts { #[serde(rename = "counts", skip_serializing_if = "Option::is_none")] - pub counts: Option>, + pub counts: Option>, #[serde(rename = "field_name", skip_serializing_if = "Option::is_none")] pub field_name: Option, #[serde(rename = "stats", skip_serializing_if = "Option::is_none")] - pub stats: Option>, + pub stats: Option>, } impl FacetCounts { @@ -27,3 +30,4 @@ impl FacetCounts { } } } + diff --git a/typesense_codegen/src/models/facet_counts_counts_inner.rs b/typesense_codegen/src/models/facet_counts_counts_inner.rs index a4dca2e..7af2af8 100644 --- a/typesense_codegen/src/models/facet_counts_counts_inner.rs +++ b/typesense_codegen/src/models/facet_counts_counts_inner.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct FacetCountsCountsInner { #[serde(rename = "count", skip_serializing_if = "Option::is_none")] @@ -16,6 +19,8 @@ pub struct FacetCountsCountsInner { pub highlighted: Option, #[serde(rename = "value", skip_serializing_if = "Option::is_none")] pub value: Option, + #[serde(rename = "parent", skip_serializing_if = "Option::is_none")] + pub parent: Option, } impl FacetCountsCountsInner { @@ -24,6 +29,8 @@ impl FacetCountsCountsInner { count: None, highlighted: None, value: None, + parent: None, } } } + diff --git a/typesense_codegen/src/models/facet_counts_stats.rs b/typesense_codegen/src/models/facet_counts_stats.rs index 142d2ce..8e1109e 100644 --- a/typesense_codegen/src/models/facet_counts_stats.rs +++ b/typesense_codegen/src/models/facet_counts_stats.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct FacetCountsStats { #[serde(rename = "max", skip_serializing_if = "Option::is_none")] @@ -33,3 +36,4 @@ impl FacetCountsStats { } } } + diff --git a/typesense_codegen/src/models/field.rs b/typesense_codegen/src/models/field.rs index 454ae90..6722b99 100644 --- a/typesense_codegen/src/models/field.rs +++ b/typesense_codegen/src/models/field.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct Field { #[serde(rename = "name")] @@ -26,12 +29,36 @@ pub struct Field { pub sort: Option, #[serde(rename = "infix", skip_serializing_if = "Option::is_none")] pub infix: Option, + /// Name of a field in another collection that should be linked to this collection so that it can be joined during query. + #[serde(rename = "reference", skip_serializing_if = "Option::is_none")] + pub reference: Option, #[serde(rename = "num_dim", skip_serializing_if = "Option::is_none")] pub num_dim: Option, #[serde(rename = "drop", skip_serializing_if = "Option::is_none")] pub drop: Option, + /// When set to false, the field value will not be stored on disk. Default: true. + #[serde(rename = "store", skip_serializing_if = "Option::is_none")] + pub store: Option, + /// The distance metric to be used for vector search. Default: `cosine`. You can also use `ip` for inner product. + #[serde(rename = "vec_dist", skip_serializing_if = "Option::is_none")] + pub vec_dist: Option, + /// Enables an index optimized for range filtering on numerical fields (e.g. rating:>3.5). Default: false. + #[serde(rename = "range_index", skip_serializing_if = "Option::is_none")] + pub range_index: Option, + /// Values are stemmed before indexing in-memory. Default: false. + #[serde(rename = "stem", skip_serializing_if = "Option::is_none")] + pub stem: Option, + /// Name of the stemming dictionary to use for this field + #[serde(rename = "stem_dictionary", skip_serializing_if = "Option::is_none")] + pub stem_dictionary: Option, + /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. + #[serde(rename = "token_separators", skip_serializing_if = "Option::is_none")] + pub token_separators: Option>, + /// List of symbols or special characters to be indexed. + #[serde(rename = "symbols_to_index", skip_serializing_if = "Option::is_none")] + pub symbols_to_index: Option>, #[serde(rename = "embed", skip_serializing_if = "Option::is_none")] - pub embed: Option>, + pub embed: Option>, } impl Field { @@ -45,9 +72,18 @@ impl Field { locale: None, sort: None, infix: None, + reference: None, num_dim: None, drop: None, + store: None, + vec_dist: None, + range_index: None, + stem: None, + stem_dictionary: None, + token_separators: None, + symbols_to_index: None, embed: None, } } } + diff --git a/typesense_codegen/src/models/field_embed.rs b/typesense_codegen/src/models/field_embed.rs index fcb68e4..80fa93c 100644 --- a/typesense_codegen/src/models/field_embed.rs +++ b/typesense_codegen/src/models/field_embed.rs @@ -3,27 +3,28 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct FieldEmbed { #[serde(rename = "from")] pub from: Vec, #[serde(rename = "model_config")] - pub model_config: Box, + pub model_config: Box, } impl FieldEmbed { - pub fn new( - from: Vec, - model_config: crate::models::FieldEmbedModelConfig, - ) -> FieldEmbed { + pub fn new(from: Vec, model_config: models::FieldEmbedModelConfig) -> FieldEmbed { FieldEmbed { from, model_config: Box::new(model_config), } } } + diff --git a/typesense_codegen/src/models/field_embed_model_config.rs b/typesense_codegen/src/models/field_embed_model_config.rs index a7af536..00620cc 100644 --- a/typesense_codegen/src/models/field_embed_model_config.rs +++ b/typesense_codegen/src/models/field_embed_model_config.rs @@ -3,25 +3,36 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct FieldEmbedModelConfig { #[serde(rename = "model_name")] pub model_name: String, #[serde(rename = "api_key", skip_serializing_if = "Option::is_none")] pub api_key: Option, + #[serde(rename = "url", skip_serializing_if = "Option::is_none")] + pub url: Option, #[serde(rename = "access_token", skip_serializing_if = "Option::is_none")] pub access_token: Option, + #[serde(rename = "refresh_token", skip_serializing_if = "Option::is_none")] + pub refresh_token: Option, #[serde(rename = "client_id", skip_serializing_if = "Option::is_none")] pub client_id: Option, #[serde(rename = "client_secret", skip_serializing_if = "Option::is_none")] pub client_secret: Option, #[serde(rename = "project_id", skip_serializing_if = "Option::is_none")] pub project_id: Option, + #[serde(rename = "indexing_prefix", skip_serializing_if = "Option::is_none")] + pub indexing_prefix: Option, + #[serde(rename = "query_prefix", skip_serializing_if = "Option::is_none")] + pub query_prefix: Option, } impl FieldEmbedModelConfig { @@ -29,10 +40,15 @@ impl FieldEmbedModelConfig { FieldEmbedModelConfig { model_name, api_key: None, + url: None, access_token: None, + refresh_token: None, client_id: None, client_secret: None, project_id: None, + indexing_prefix: None, + query_prefix: None, } } } + diff --git a/typesense_codegen/src/models/get_collections_parameters.rs b/typesense_codegen/src/models/get_collections_parameters.rs new file mode 100644 index 0000000..c6ac5a3 --- /dev/null +++ b/typesense_codegen/src/models/get_collections_parameters.rs @@ -0,0 +1,36 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct GetCollectionsParameters { + /// Comma-separated list of fields from the collection to exclude from the response + #[serde(rename = "exclude_fields", skip_serializing_if = "Option::is_none")] + pub exclude_fields: Option, + /// Number of collections to fetch. Default: returns all collections. + #[serde(rename = "limit", skip_serializing_if = "Option::is_none")] + pub limit: Option, + /// Identifies the starting point to return collections when paginating. + #[serde(rename = "offset", skip_serializing_if = "Option::is_none")] + pub offset: Option, +} + +impl GetCollectionsParameters { + pub fn new() -> GetCollectionsParameters { + GetCollectionsParameters { + exclude_fields: None, + limit: None, + offset: None, + } + } +} + diff --git a/typesense_codegen/src/models/health_status.rs b/typesense_codegen/src/models/health_status.rs index b33a2ba..1a69ccb 100644 --- a/typesense_codegen/src/models/health_status.rs +++ b/typesense_codegen/src/models/health_status.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct HealthStatus { #[serde(rename = "ok")] @@ -16,6 +19,9 @@ pub struct HealthStatus { impl HealthStatus { pub fn new(ok: bool) -> HealthStatus { - HealthStatus { ok } + HealthStatus { + ok, + } } } + diff --git a/typesense_codegen/src/models/import_documents_import_documents_parameters_parameter.rs b/typesense_codegen/src/models/import_documents_import_documents_parameters_parameter.rs deleted file mode 100644 index 9dd0edb..0000000 --- a/typesense_codegen/src/models/import_documents_import_documents_parameters_parameter.rs +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Typesense API - * - * An open source search engine for building delightful search experiences. - * - * The version of the OpenAPI document: 0.25.0 - * - * Generated by: https://openapi-generator.tech - */ - -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct ImportDocumentsImportDocumentsParametersParameter { - #[serde(rename = "action", skip_serializing_if = "Option::is_none")] - pub action: Option, - #[serde(rename = "batch_size", skip_serializing_if = "Option::is_none")] - pub batch_size: Option, - #[serde(rename = "dirty_values", skip_serializing_if = "Option::is_none")] - pub dirty_values: Option, - #[serde( - rename = "remote_embedding_batch_size", - skip_serializing_if = "Option::is_none" - )] - pub remote_embedding_batch_size: Option, -} - -impl ImportDocumentsImportDocumentsParametersParameter { - pub fn new() -> ImportDocumentsImportDocumentsParametersParameter { - ImportDocumentsImportDocumentsParametersParameter { - action: None, - batch_size: None, - dirty_values: None, - remote_embedding_batch_size: None, - } - } -} - -#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] -pub enum DirtyValues { - #[serde(rename = "coerce_or_reject")] - CoerceOrReject, - #[serde(rename = "coerce_or_drop")] - CoerceOrDrop, - #[serde(rename = "drop")] - Drop, - #[serde(rename = "reject")] - Reject, -} - -impl Default for DirtyValues { - fn default() -> DirtyValues { - Self::CoerceOrReject - } -} diff --git a/typesense_codegen/src/models/import_documents_parameters.rs b/typesense_codegen/src/models/import_documents_parameters.rs new file mode 100644 index 0000000..01e502e --- /dev/null +++ b/typesense_codegen/src/models/import_documents_parameters.rs @@ -0,0 +1,43 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct ImportDocumentsParameters { + #[serde(rename = "batch_size", skip_serializing_if = "Option::is_none")] + pub batch_size: Option, + /// Returning the id of the imported documents. If you want the import response to return the ingested document's id in the response, you can use the return_id parameter. + #[serde(rename = "return_id", skip_serializing_if = "Option::is_none")] + pub return_id: Option, + #[serde(rename = "remote_embedding_batch_size", skip_serializing_if = "Option::is_none")] + pub remote_embedding_batch_size: Option, + #[serde(rename = "return_doc", skip_serializing_if = "Option::is_none")] + pub return_doc: Option, + #[serde(rename = "action", skip_serializing_if = "Option::is_none")] + pub action: Option, + #[serde(rename = "dirty_values", skip_serializing_if = "Option::is_none")] + pub dirty_values: Option, +} + +impl ImportDocumentsParameters { + pub fn new() -> ImportDocumentsParameters { + ImportDocumentsParameters { + batch_size: None, + return_id: None, + remote_embedding_batch_size: None, + return_doc: None, + action: None, + dirty_values: None, + } + } +} + diff --git a/typesense_codegen/src/models/index_action.rs b/typesense_codegen/src/models/index_action.rs new file mode 100644 index 0000000..7bce745 --- /dev/null +++ b/typesense_codegen/src/models/index_action.rs @@ -0,0 +1,44 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +/// +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum IndexAction { + #[serde(rename = "create")] + Create, + #[serde(rename = "update")] + Update, + #[serde(rename = "upsert")] + Upsert, + #[serde(rename = "emplace")] + Emplace, + +} + +impl std::fmt::Display for IndexAction { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + Self::Create => write!(f, "create"), + Self::Update => write!(f, "update"), + Self::Upsert => write!(f, "upsert"), + Self::Emplace => write!(f, "emplace"), + } + } +} + +impl Default for IndexAction { + fn default() -> IndexAction { + Self::Create + } +} + diff --git a/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs b/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs new file mode 100644 index 0000000..e519db7 --- /dev/null +++ b/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs @@ -0,0 +1,27 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct ListStemmingDictionaries200Response { + #[serde(rename = "dictionaries", skip_serializing_if = "Option::is_none")] + pub dictionaries: Option>, +} + +impl ListStemmingDictionaries200Response { + pub fn new() -> ListStemmingDictionaries200Response { + ListStemmingDictionaries200Response { + dictionaries: None, + } + } +} + diff --git a/typesense_codegen/src/models/mod.rs b/typesense_codegen/src/models/mod.rs index f8fb452..40ce6f2 100644 --- a/typesense_codegen/src/models/mod.rs +++ b/typesense_codegen/src/models/mod.rs @@ -1,21 +1,35 @@ -pub mod analytics_rule_parameters; -pub use self::analytics_rule_parameters::AnalyticsRuleParameters; -pub mod analytics_rule_parameters_destination; -pub use self::analytics_rule_parameters_destination::AnalyticsRuleParametersDestination; -pub mod analytics_rule_parameters_source; -pub use self::analytics_rule_parameters_source::AnalyticsRuleParametersSource; -pub mod analytics_rule_schema; -pub use self::analytics_rule_schema::AnalyticsRuleSchema; -pub mod analytics_rules_retrieve_schema; -pub use self::analytics_rules_retrieve_schema::AnalyticsRulesRetrieveSchema; +pub mod analytics_event; +pub use self::analytics_event::AnalyticsEvent; +pub mod analytics_event_create_response; +pub use self::analytics_event_create_response::AnalyticsEventCreateResponse; +pub mod analytics_event_data; +pub use self::analytics_event_data::AnalyticsEventData; +pub mod analytics_events_response; +pub use self::analytics_events_response::AnalyticsEventsResponse; +pub mod analytics_events_response_events_inner; +pub use self::analytics_events_response_events_inner::AnalyticsEventsResponseEventsInner; +pub mod analytics_rule; +pub use self::analytics_rule::AnalyticsRule; +pub mod analytics_rule_create; +pub use self::analytics_rule_create::AnalyticsRuleCreate; +pub mod analytics_rule_create_params; +pub use self::analytics_rule_create_params::AnalyticsRuleCreateParams; +pub mod analytics_rule_update; +pub use self::analytics_rule_update::AnalyticsRuleUpdate; +pub mod analytics_status; +pub use self::analytics_status::AnalyticsStatus; pub mod api_key; pub use self::api_key::ApiKey; +pub mod api_key_delete_response; +pub use self::api_key_delete_response::ApiKeyDeleteResponse; pub mod api_key_schema; pub use self::api_key_schema::ApiKeySchema; pub mod api_keys_response; pub use self::api_keys_response::ApiKeysResponse; pub mod api_response; pub use self::api_response::ApiResponse; +pub mod api_stats_response; +pub use self::api_stats_response::ApiStatsResponse; pub mod collection_alias; pub use self::collection_alias::CollectionAlias; pub mod collection_alias_schema; @@ -28,16 +42,34 @@ pub mod collection_schema; pub use self::collection_schema::CollectionSchema; pub mod collection_update_schema; pub use self::collection_update_schema::CollectionUpdateSchema; +pub mod conversation_model_create_schema; +pub use self::conversation_model_create_schema::ConversationModelCreateSchema; +pub mod conversation_model_schema; +pub use self::conversation_model_schema::ConversationModelSchema; +pub mod conversation_model_update_schema; +pub use self::conversation_model_update_schema::ConversationModelUpdateSchema; +pub mod create_analytics_rule_200_response; +pub use self::create_analytics_rule_200_response::CreateAnalyticsRule200Response; +pub mod create_analytics_rule_200_response_one_of_inner; +pub use self::create_analytics_rule_200_response_one_of_inner::CreateAnalyticsRule200ResponseOneOfInner; +pub mod create_analytics_rule_200_response_one_of_inner_any_of; +pub use self::create_analytics_rule_200_response_one_of_inner_any_of::CreateAnalyticsRule200ResponseOneOfInnerAnyOf; +pub mod create_analytics_rule_request; +pub use self::create_analytics_rule_request::CreateAnalyticsRuleRequest; pub mod debug_200_response; pub use self::debug_200_response::Debug200Response; pub mod delete_documents_200_response; pub use self::delete_documents_200_response::DeleteDocuments200Response; -pub mod delete_documents_delete_documents_parameters_parameter; -pub use self::delete_documents_delete_documents_parameters_parameter::DeleteDocumentsDeleteDocumentsParametersParameter; -pub mod error_response; -pub use self::error_response::ErrorResponse; -pub mod export_documents_export_documents_parameters_parameter; -pub use self::export_documents_export_documents_parameters_parameter::ExportDocumentsExportDocumentsParametersParameter; +pub mod delete_documents_parameters; +pub use self::delete_documents_parameters::DeleteDocumentsParameters; +pub mod delete_stopwords_set_200_response; +pub use self::delete_stopwords_set_200_response::DeleteStopwordsSet200Response; +pub mod dirty_values; +pub use self::dirty_values::DirtyValues; +pub mod drop_tokens_mode; +pub use self::drop_tokens_mode::DropTokensMode; +pub mod export_documents_parameters; +pub use self::export_documents_parameters::ExportDocumentsParameters; pub mod facet_counts; pub use self::facet_counts::FacetCounts; pub mod facet_counts_counts_inner; @@ -50,26 +82,54 @@ pub mod field_embed; pub use self::field_embed::FieldEmbed; pub mod field_embed_model_config; pub use self::field_embed_model_config::FieldEmbedModelConfig; +pub mod get_collections_parameters; +pub use self::get_collections_parameters::GetCollectionsParameters; pub mod health_status; pub use self::health_status::HealthStatus; -pub mod import_documents_import_documents_parameters_parameter; -pub use self::import_documents_import_documents_parameters_parameter::ImportDocumentsImportDocumentsParametersParameter; +pub mod import_documents_parameters; +pub use self::import_documents_parameters::ImportDocumentsParameters; +pub mod index_action; +pub use self::index_action::IndexAction; +pub mod list_stemming_dictionaries_200_response; +pub use self::list_stemming_dictionaries_200_response::ListStemmingDictionaries200Response; pub mod multi_search_collection_parameters; pub use self::multi_search_collection_parameters::MultiSearchCollectionParameters; pub mod multi_search_parameters; pub use self::multi_search_parameters::MultiSearchParameters; pub mod multi_search_result; pub use self::multi_search_result::MultiSearchResult; +pub mod multi_search_result_item; +pub use self::multi_search_result_item::MultiSearchResultItem; pub mod multi_search_searches_parameter; pub use self::multi_search_searches_parameter::MultiSearchSearchesParameter; -pub mod scoped_key_parameters; -pub use self::scoped_key_parameters::ScopedKeyParameters; +pub mod nl_search_model_base; +pub use self::nl_search_model_base::NlSearchModelBase; +pub mod nl_search_model_create_schema; +pub use self::nl_search_model_create_schema::NlSearchModelCreateSchema; +pub mod nl_search_model_delete_schema; +pub use self::nl_search_model_delete_schema::NlSearchModelDeleteSchema; +pub mod nl_search_model_schema; +pub use self::nl_search_model_schema::NlSearchModelSchema; +pub mod preset_delete_schema; +pub use self::preset_delete_schema::PresetDeleteSchema; +pub mod preset_schema; +pub use self::preset_schema::PresetSchema; +pub mod preset_upsert_schema; +pub use self::preset_upsert_schema::PresetUpsertSchema; +pub mod preset_upsert_schema_value; +pub use self::preset_upsert_schema_value::PresetUpsertSchemaValue; +pub mod presets_retrieve_schema; +pub use self::presets_retrieve_schema::PresetsRetrieveSchema; +pub mod schema_change_status; +pub use self::schema_change_status::SchemaChangeStatus; pub mod search_grouped_hit; pub use self::search_grouped_hit::SearchGroupedHit; pub mod search_highlight; pub use self::search_highlight::SearchHighlight; pub mod search_override; pub use self::search_override::SearchOverride; +pub mod search_override_delete_response; +pub use self::search_override_delete_response::SearchOverrideDeleteResponse; pub mod search_override_exclude; pub use self::search_override_exclude::SearchOverrideExclude; pub mod search_override_include; @@ -82,23 +142,57 @@ pub mod search_overrides_response; pub use self::search_overrides_response::SearchOverridesResponse; pub mod search_parameters; pub use self::search_parameters::SearchParameters; +pub mod search_request_params; +pub use self::search_request_params::SearchRequestParams; +pub mod search_request_params_voice_query; +pub use self::search_request_params_voice_query::SearchRequestParamsVoiceQuery; pub mod search_result; pub use self::search_result::SearchResult; +pub mod search_result_conversation; +pub use self::search_result_conversation::SearchResultConversation; pub mod search_result_hit; pub use self::search_result_hit::SearchResultHit; -pub mod search_result_request_params; -pub use self::search_result_request_params::SearchResultRequestParams; +pub mod search_result_hit_hybrid_search_info; +pub use self::search_result_hit_hybrid_search_info::SearchResultHitHybridSearchInfo; +pub mod search_result_hit_text_match_info; +pub use self::search_result_hit_text_match_info::SearchResultHitTextMatchInfo; pub mod search_synonym; pub use self::search_synonym::SearchSynonym; +pub mod search_synonym_delete_response; +pub use self::search_synonym_delete_response::SearchSynonymDeleteResponse; pub mod search_synonym_schema; pub use self::search_synonym_schema::SearchSynonymSchema; pub mod search_synonyms_response; pub use self::search_synonyms_response::SearchSynonymsResponse; -pub mod snapshot_parameters; -pub use self::snapshot_parameters::SnapshotParameters; +pub mod stemming_dictionary; +pub use self::stemming_dictionary::StemmingDictionary; +pub mod stemming_dictionary_words_inner; +pub use self::stemming_dictionary_words_inner::StemmingDictionaryWordsInner; +pub mod stopwords_set_retrieve_schema; +pub use self::stopwords_set_retrieve_schema::StopwordsSetRetrieveSchema; +pub mod stopwords_set_schema; +pub use self::stopwords_set_schema::StopwordsSetSchema; +pub mod stopwords_set_upsert_schema; +pub use self::stopwords_set_upsert_schema::StopwordsSetUpsertSchema; +pub mod stopwords_sets_retrieve_all_schema; +pub use self::stopwords_sets_retrieve_all_schema::StopwordsSetsRetrieveAllSchema; pub mod success_status; pub use self::success_status::SuccessStatus; +pub mod synonym_item_schema; +pub use self::synonym_item_schema::SynonymItemSchema; +pub mod synonym_set_create_schema; +pub use self::synonym_set_create_schema::SynonymSetCreateSchema; +pub mod synonym_set_delete_schema; +pub use self::synonym_set_delete_schema::SynonymSetDeleteSchema; +pub mod synonym_set_schema; +pub use self::synonym_set_schema::SynonymSetSchema; +pub mod synonym_sets_retrieve_schema; +pub use self::synonym_sets_retrieve_schema::SynonymSetsRetrieveSchema; +pub mod toggle_slow_request_log_request; +pub use self::toggle_slow_request_log_request::ToggleSlowRequestLogRequest; pub mod update_documents_200_response; pub use self::update_documents_200_response::UpdateDocuments200Response; -pub mod update_documents_update_documents_parameters_parameter; -pub use self::update_documents_update_documents_parameters_parameter::UpdateDocumentsUpdateDocumentsParametersParameter; +pub mod update_documents_parameters; +pub use self::update_documents_parameters::UpdateDocumentsParameters; +pub mod voice_query_model_collection_config; +pub use self::voice_query_model_collection_config::VoiceQueryModelCollectionConfig; diff --git a/typesense_codegen/src/models/multi_search_collection_parameters.rs b/typesense_codegen/src/models/multi_search_collection_parameters.rs index 97a99fd..c3b7fe2 100644 --- a/typesense_codegen/src/models/multi_search_collection_parameters.rs +++ b/typesense_codegen/src/models/multi_search_collection_parameters.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct MultiSearchCollectionParameters { /// The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. @@ -49,7 +52,7 @@ pub struct MultiSearchCollectionParameters { /// Facet values that are returned can now be filtered via this parameter. The matching facet text is also highlighted. For example, when faceting by `category`, you can set `facet_query=category:shoe` to return only facet values that contain the prefix \"shoe\". #[serde(rename = "facet_query", skip_serializing_if = "Option::is_none")] pub facet_query: Option, - /// The number of typographical errors (1 or 2) that would be tolerated. Default: 2 + /// The number of typographical errors (1 or 2) that would be tolerated. Default: 2 #[serde(rename = "num_typos", skip_serializing_if = "Option::is_none")] pub num_typos: Option, /// Results from this specific page number would be fetched. @@ -58,7 +61,7 @@ pub struct MultiSearchCollectionParameters { /// Number of results to fetch per page. Default: 10 #[serde(rename = "per_page", skip_serializing_if = "Option::is_none")] pub per_page: Option, - /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. + /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. #[serde(rename = "limit", skip_serializing_if = "Option::is_none")] pub limit: Option, /// Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. @@ -67,9 +70,12 @@ pub struct MultiSearchCollectionParameters { /// You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. #[serde(rename = "group_by", skip_serializing_if = "Option::is_none")] pub group_by: Option, - /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 + /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 #[serde(rename = "group_limit", skip_serializing_if = "Option::is_none")] pub group_limit: Option, + /// Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true + #[serde(rename = "group_missing_values", skip_serializing_if = "Option::is_none")] + pub group_missing_values: Option, /// List of fields from the document to include in the search result #[serde(rename = "include_fields", skip_serializing_if = "Option::is_none")] pub include_fields: Option, @@ -77,108 +83,140 @@ pub struct MultiSearchCollectionParameters { #[serde(rename = "exclude_fields", skip_serializing_if = "Option::is_none")] pub exclude_fields: Option, /// List of fields which should be highlighted fully without snippeting - #[serde( - rename = "highlight_full_fields", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "highlight_full_fields", skip_serializing_if = "Option::is_none")] pub highlight_full_fields: Option, - /// The number of tokens that should surround the highlighted text on each side. Default: 4 - #[serde( - rename = "highlight_affix_num_tokens", - skip_serializing_if = "Option::is_none" - )] + /// The number of tokens that should surround the highlighted text on each side. Default: 4 + #[serde(rename = "highlight_affix_num_tokens", skip_serializing_if = "Option::is_none")] pub highlight_affix_num_tokens: Option, - /// The start tag used for the highlighted snippets. Default: `` - #[serde( - rename = "highlight_start_tag", - skip_serializing_if = "Option::is_none" - )] + /// The start tag used for the highlighted snippets. Default: `` + #[serde(rename = "highlight_start_tag", skip_serializing_if = "Option::is_none")] pub highlight_start_tag: Option, - /// The end tag used for the highlighted snippets. Default: `` + /// The end tag used for the highlighted snippets. Default: `` #[serde(rename = "highlight_end_tag", skip_serializing_if = "Option::is_none")] pub highlight_end_tag: Option, - /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 + /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 #[serde(rename = "snippet_threshold", skip_serializing_if = "Option::is_none")] pub snippet_threshold: Option, - /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 - #[serde( - rename = "drop_tokens_threshold", - skip_serializing_if = "Option::is_none" - )] + /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 + #[serde(rename = "drop_tokens_threshold", skip_serializing_if = "Option::is_none")] pub drop_tokens_threshold: Option, - /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 - #[serde( - rename = "typo_tokens_threshold", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "drop_tokens_mode", skip_serializing_if = "Option::is_none")] + pub drop_tokens_mode: Option, + /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 + #[serde(rename = "typo_tokens_threshold", skip_serializing_if = "Option::is_none")] pub typo_tokens_threshold: Option, - /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + #[serde(rename = "enable_typos_for_alpha_numerical_tokens", skip_serializing_if = "Option::is_none")] + pub enable_typos_for_alpha_numerical_tokens: Option, + /// Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + #[serde(rename = "filter_curated_hits", skip_serializing_if = "Option::is_none")] + pub filter_curated_hits: Option, + /// If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + #[serde(rename = "enable_synonyms", skip_serializing_if = "Option::is_none")] + pub enable_synonyms: Option, + /// Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). + #[serde(rename = "enable_analytics", skip_serializing_if = "Option::is_none")] + pub enable_analytics: Option, + /// Allow synonym resolution on word prefixes in the query. Default: false + #[serde(rename = "synonym_prefix", skip_serializing_if = "Option::is_none")] + pub synonym_prefix: Option, + /// Allow synonym resolution on typo-corrected words in the query. Default: 0 + #[serde(rename = "synonym_num_typos", skip_serializing_if = "Option::is_none")] + pub synonym_num_typos: Option, + /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "pinned_hits", skip_serializing_if = "Option::is_none")] pub pinned_hits: Option, - /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "hidden_hits", skip_serializing_if = "Option::is_none")] pub hidden_hits: Option, - /// A list of custom fields that must be highlighted even if you don't query for them + /// Comma separated list of tags to trigger the curations rules that match the tags. + #[serde(rename = "override_tags", skip_serializing_if = "Option::is_none")] + pub override_tags: Option, + /// A list of custom fields that must be highlighted even if you don't query for them #[serde(rename = "highlight_fields", skip_serializing_if = "Option::is_none")] pub highlight_fields: Option, - /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same - #[serde( - rename = "pre_segmented_query", - skip_serializing_if = "Option::is_none" - )] + /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same + #[serde(rename = "pre_segmented_query", skip_serializing_if = "Option::is_none")] pub pre_segmented_query: Option, - /// Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. + /// Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. #[serde(rename = "preset", skip_serializing_if = "Option::is_none")] pub preset: Option, - /// If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false + /// If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false #[serde(rename = "enable_overrides", skip_serializing_if = "Option::is_none")] pub enable_overrides: Option, - /// Set this parameter to true to ensure that an exact match is ranked above the others - #[serde( - rename = "prioritize_exact_match", - skip_serializing_if = "Option::is_none" - )] + /// Set this parameter to true to ensure that an exact match is ranked above the others + #[serde(rename = "prioritize_exact_match", skip_serializing_if = "Option::is_none")] pub prioritize_exact_match: Option, - /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). + /// Make Typesense prioritize documents where the query words appear earlier in the text. + #[serde(rename = "prioritize_token_position", skip_serializing_if = "Option::is_none")] + pub prioritize_token_position: Option, + /// Make Typesense prioritize documents where the query words appear in more number of fields. + #[serde(rename = "prioritize_num_matching_fields", skip_serializing_if = "Option::is_none")] + pub prioritize_num_matching_fields: Option, + /// Make Typesense disable typos for numerical tokens. + #[serde(rename = "enable_typos_for_numerical_tokens", skip_serializing_if = "Option::is_none")] + pub enable_typos_for_numerical_tokens: Option, + /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). #[serde(rename = "exhaustive_search", skip_serializing_if = "Option::is_none")] pub exhaustive_search: Option, - /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. + /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. #[serde(rename = "search_cutoff_ms", skip_serializing_if = "Option::is_none")] pub search_cutoff_ms: Option, - /// Enable server side caching of search query results. By default, caching is disabled. + /// Enable server side caching of search query results. By default, caching is disabled. #[serde(rename = "use_cache", skip_serializing_if = "Option::is_none")] pub use_cache: Option, - /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. + /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. #[serde(rename = "cache_ttl", skip_serializing_if = "Option::is_none")] pub cache_ttl: Option, - /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_1typo", skip_serializing_if = "Option::is_none")] pub min_len_1typo: Option, - /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_2typo", skip_serializing_if = "Option::is_none")] pub min_len_2typo: Option, - /// Vector query expression for fetching documents \"closest\" to a given query/document vector. + /// Vector query expression for fetching documents \"closest\" to a given query/document vector. #[serde(rename = "vector_query", skip_serializing_if = "Option::is_none")] pub vector_query: Option, - /// Timeout (in milliseconds) for fetching remote embeddings. - #[serde( - rename = "remote_embedding_timeout_ms", - skip_serializing_if = "Option::is_none" - )] + /// Timeout (in milliseconds) for fetching remote embeddings. + #[serde(rename = "remote_embedding_timeout_ms", skip_serializing_if = "Option::is_none")] pub remote_embedding_timeout_ms: Option, - /// Number of times to retry fetching remote embeddings. - #[serde( - rename = "remote_embedding_num_tries", - skip_serializing_if = "Option::is_none" - )] + /// Number of times to retry fetching remote embeddings. + #[serde(rename = "remote_embedding_num_tries", skip_serializing_if = "Option::is_none")] pub remote_embedding_num_tries: Option, - /// The collection to search in. - #[serde(rename = "collection")] - pub collection: String, + /// Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). + #[serde(rename = "facet_strategy", skip_serializing_if = "Option::is_none")] + pub facet_strategy: Option, + /// Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. + #[serde(rename = "stopwords", skip_serializing_if = "Option::is_none")] + pub stopwords: Option, + /// Comma separated string of nested facet fields whose parent object should be returned in facet response. + #[serde(rename = "facet_return_parent", skip_serializing_if = "Option::is_none")] + pub facet_return_parent: Option, + /// The base64 encoded audio file in 16 khz 16-bit WAV format. + #[serde(rename = "voice_query", skip_serializing_if = "Option::is_none")] + pub voice_query: Option, + /// Enable conversational search. + #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] + pub conversation: Option, + /// The Id of Conversation Model to be used. + #[serde(rename = "conversation_model_id", skip_serializing_if = "Option::is_none")] + pub conversation_model_id: Option, + /// The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + #[serde(rename = "conversation_id", skip_serializing_if = "Option::is_none")] + pub conversation_id: Option, + /// The collection to search in. + #[serde(rename = "collection", skip_serializing_if = "Option::is_none")] + pub collection: Option, + /// A separate search API key for each search within a multi_search request + #[serde(rename = "x-typesense-api-key", skip_serializing_if = "Option::is_none")] + pub x_typesense_api_key: Option, + /// When true, computes both text match and vector distance scores for all matches in hybrid search. Documents found only through keyword search will get a vector distance score, and documents found only through vector search will get a text match score. + #[serde(rename = "rerank_hybrid_matches", skip_serializing_if = "Option::is_none")] + pub rerank_hybrid_matches: Option, } impl MultiSearchCollectionParameters { - pub fn new(collection: String) -> MultiSearchCollectionParameters { + pub fn new() -> MultiSearchCollectionParameters { MultiSearchCollectionParameters { q: None, query_by: None, @@ -200,6 +238,7 @@ impl MultiSearchCollectionParameters { offset: None, group_by: None, group_limit: None, + group_missing_values: None, include_fields: None, exclude_fields: None, highlight_full_fields: None, @@ -208,14 +247,25 @@ impl MultiSearchCollectionParameters { highlight_end_tag: None, snippet_threshold: None, drop_tokens_threshold: None, + drop_tokens_mode: None, typo_tokens_threshold: None, + enable_typos_for_alpha_numerical_tokens: None, + filter_curated_hits: None, + enable_synonyms: None, + enable_analytics: None, + synonym_prefix: None, + synonym_num_typos: None, pinned_hits: None, hidden_hits: None, + override_tags: None, highlight_fields: None, pre_segmented_query: None, preset: None, enable_overrides: None, prioritize_exact_match: None, + prioritize_token_position: None, + prioritize_num_matching_fields: None, + enable_typos_for_numerical_tokens: None, exhaustive_search: None, search_cutoff_ms: None, use_cache: None, @@ -225,7 +275,17 @@ impl MultiSearchCollectionParameters { vector_query: None, remote_embedding_timeout_ms: None, remote_embedding_num_tries: None, - collection, + facet_strategy: None, + stopwords: None, + facet_return_parent: None, + voice_query: None, + conversation: None, + conversation_model_id: None, + conversation_id: None, + collection: None, + x_typesense_api_key: None, + rerank_hybrid_matches: None, } } } + diff --git a/typesense_codegen/src/models/multi_search_parameters.rs b/typesense_codegen/src/models/multi_search_parameters.rs index 409cc90..2a94e44 100644 --- a/typesense_codegen/src/models/multi_search_parameters.rs +++ b/typesense_codegen/src/models/multi_search_parameters.rs @@ -3,13 +3,15 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ -/// MultiSearchParameters : Parameters for the multi search API. +use crate::models; +use serde::{Deserialize, Serialize}; +/// MultiSearchParameters : Parameters for the multi search API. #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct MultiSearchParameters { /// The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. @@ -51,7 +53,7 @@ pub struct MultiSearchParameters { /// Facet values that are returned can now be filtered via this parameter. The matching facet text is also highlighted. For example, when faceting by `category`, you can set `facet_query=category:shoe` to return only facet values that contain the prefix \"shoe\". #[serde(rename = "facet_query", skip_serializing_if = "Option::is_none")] pub facet_query: Option, - /// The number of typographical errors (1 or 2) that would be tolerated. Default: 2 + /// The number of typographical errors (1 or 2) that would be tolerated. Default: 2 #[serde(rename = "num_typos", skip_serializing_if = "Option::is_none")] pub num_typos: Option, /// Results from this specific page number would be fetched. @@ -60,7 +62,7 @@ pub struct MultiSearchParameters { /// Number of results to fetch per page. Default: 10 #[serde(rename = "per_page", skip_serializing_if = "Option::is_none")] pub per_page: Option, - /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. + /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. #[serde(rename = "limit", skip_serializing_if = "Option::is_none")] pub limit: Option, /// Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. @@ -69,9 +71,12 @@ pub struct MultiSearchParameters { /// You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. #[serde(rename = "group_by", skip_serializing_if = "Option::is_none")] pub group_by: Option, - /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 + /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 #[serde(rename = "group_limit", skip_serializing_if = "Option::is_none")] pub group_limit: Option, + /// Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true + #[serde(rename = "group_missing_values", skip_serializing_if = "Option::is_none")] + pub group_missing_values: Option, /// List of fields from the document to include in the search result #[serde(rename = "include_fields", skip_serializing_if = "Option::is_none")] pub include_fields: Option, @@ -79,105 +84,131 @@ pub struct MultiSearchParameters { #[serde(rename = "exclude_fields", skip_serializing_if = "Option::is_none")] pub exclude_fields: Option, /// List of fields which should be highlighted fully without snippeting - #[serde( - rename = "highlight_full_fields", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "highlight_full_fields", skip_serializing_if = "Option::is_none")] pub highlight_full_fields: Option, - /// The number of tokens that should surround the highlighted text on each side. Default: 4 - #[serde( - rename = "highlight_affix_num_tokens", - skip_serializing_if = "Option::is_none" - )] + /// The number of tokens that should surround the highlighted text on each side. Default: 4 + #[serde(rename = "highlight_affix_num_tokens", skip_serializing_if = "Option::is_none")] pub highlight_affix_num_tokens: Option, - /// The start tag used for the highlighted snippets. Default: `` - #[serde( - rename = "highlight_start_tag", - skip_serializing_if = "Option::is_none" - )] + /// The start tag used for the highlighted snippets. Default: `` + #[serde(rename = "highlight_start_tag", skip_serializing_if = "Option::is_none")] pub highlight_start_tag: Option, - /// The end tag used for the highlighted snippets. Default: `` + /// The end tag used for the highlighted snippets. Default: `` #[serde(rename = "highlight_end_tag", skip_serializing_if = "Option::is_none")] pub highlight_end_tag: Option, - /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 + /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 #[serde(rename = "snippet_threshold", skip_serializing_if = "Option::is_none")] pub snippet_threshold: Option, - /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 - #[serde( - rename = "drop_tokens_threshold", - skip_serializing_if = "Option::is_none" - )] + /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 + #[serde(rename = "drop_tokens_threshold", skip_serializing_if = "Option::is_none")] pub drop_tokens_threshold: Option, - /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 - #[serde( - rename = "typo_tokens_threshold", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "drop_tokens_mode", skip_serializing_if = "Option::is_none")] + pub drop_tokens_mode: Option, + /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 + #[serde(rename = "typo_tokens_threshold", skip_serializing_if = "Option::is_none")] pub typo_tokens_threshold: Option, - /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + #[serde(rename = "enable_typos_for_alpha_numerical_tokens", skip_serializing_if = "Option::is_none")] + pub enable_typos_for_alpha_numerical_tokens: Option, + /// Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + #[serde(rename = "filter_curated_hits", skip_serializing_if = "Option::is_none")] + pub filter_curated_hits: Option, + /// If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + #[serde(rename = "enable_synonyms", skip_serializing_if = "Option::is_none")] + pub enable_synonyms: Option, + /// Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). + #[serde(rename = "enable_analytics", skip_serializing_if = "Option::is_none")] + pub enable_analytics: Option, + /// Allow synonym resolution on word prefixes in the query. Default: false + #[serde(rename = "synonym_prefix", skip_serializing_if = "Option::is_none")] + pub synonym_prefix: Option, + /// Allow synonym resolution on typo-corrected words in the query. Default: 0 + #[serde(rename = "synonym_num_typos", skip_serializing_if = "Option::is_none")] + pub synonym_num_typos: Option, + /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "pinned_hits", skip_serializing_if = "Option::is_none")] pub pinned_hits: Option, - /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "hidden_hits", skip_serializing_if = "Option::is_none")] pub hidden_hits: Option, - /// A list of custom fields that must be highlighted even if you don't query for them + /// Comma separated list of tags to trigger the curations rules that match the tags. + #[serde(rename = "override_tags", skip_serializing_if = "Option::is_none")] + pub override_tags: Option, + /// A list of custom fields that must be highlighted even if you don't query for them #[serde(rename = "highlight_fields", skip_serializing_if = "Option::is_none")] pub highlight_fields: Option, - /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same - #[serde( - rename = "pre_segmented_query", - skip_serializing_if = "Option::is_none" - )] + /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same + #[serde(rename = "pre_segmented_query", skip_serializing_if = "Option::is_none")] pub pre_segmented_query: Option, - /// Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. + /// Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. #[serde(rename = "preset", skip_serializing_if = "Option::is_none")] pub preset: Option, - /// If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false + /// If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false #[serde(rename = "enable_overrides", skip_serializing_if = "Option::is_none")] pub enable_overrides: Option, - /// Set this parameter to true to ensure that an exact match is ranked above the others - #[serde( - rename = "prioritize_exact_match", - skip_serializing_if = "Option::is_none" - )] + /// Set this parameter to true to ensure that an exact match is ranked above the others + #[serde(rename = "prioritize_exact_match", skip_serializing_if = "Option::is_none")] pub prioritize_exact_match: Option, - /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). + /// Make Typesense prioritize documents where the query words appear earlier in the text. + #[serde(rename = "prioritize_token_position", skip_serializing_if = "Option::is_none")] + pub prioritize_token_position: Option, + /// Make Typesense prioritize documents where the query words appear in more number of fields. + #[serde(rename = "prioritize_num_matching_fields", skip_serializing_if = "Option::is_none")] + pub prioritize_num_matching_fields: Option, + /// Make Typesense disable typos for numerical tokens. + #[serde(rename = "enable_typos_for_numerical_tokens", skip_serializing_if = "Option::is_none")] + pub enable_typos_for_numerical_tokens: Option, + /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). #[serde(rename = "exhaustive_search", skip_serializing_if = "Option::is_none")] pub exhaustive_search: Option, - /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. + /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. #[serde(rename = "search_cutoff_ms", skip_serializing_if = "Option::is_none")] pub search_cutoff_ms: Option, - /// Enable server side caching of search query results. By default, caching is disabled. + /// Enable server side caching of search query results. By default, caching is disabled. #[serde(rename = "use_cache", skip_serializing_if = "Option::is_none")] pub use_cache: Option, - /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. + /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. #[serde(rename = "cache_ttl", skip_serializing_if = "Option::is_none")] pub cache_ttl: Option, - /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_1typo", skip_serializing_if = "Option::is_none")] pub min_len_1typo: Option, - /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_2typo", skip_serializing_if = "Option::is_none")] pub min_len_2typo: Option, - /// Vector query expression for fetching documents \"closest\" to a given query/document vector. + /// Vector query expression for fetching documents \"closest\" to a given query/document vector. #[serde(rename = "vector_query", skip_serializing_if = "Option::is_none")] pub vector_query: Option, - /// Timeout (in milliseconds) for fetching remote embeddings. - #[serde( - rename = "remote_embedding_timeout_ms", - skip_serializing_if = "Option::is_none" - )] + /// Timeout (in milliseconds) for fetching remote embeddings. + #[serde(rename = "remote_embedding_timeout_ms", skip_serializing_if = "Option::is_none")] pub remote_embedding_timeout_ms: Option, - /// Number of times to retry fetching remote embeddings. - #[serde( - rename = "remote_embedding_num_tries", - skip_serializing_if = "Option::is_none" - )] + /// Number of times to retry fetching remote embeddings. + #[serde(rename = "remote_embedding_num_tries", skip_serializing_if = "Option::is_none")] pub remote_embedding_num_tries: Option, + /// Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). + #[serde(rename = "facet_strategy", skip_serializing_if = "Option::is_none")] + pub facet_strategy: Option, + /// Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. + #[serde(rename = "stopwords", skip_serializing_if = "Option::is_none")] + pub stopwords: Option, + /// Comma separated string of nested facet fields whose parent object should be returned in facet response. + #[serde(rename = "facet_return_parent", skip_serializing_if = "Option::is_none")] + pub facet_return_parent: Option, + /// The base64 encoded audio file in 16 khz 16-bit WAV format. + #[serde(rename = "voice_query", skip_serializing_if = "Option::is_none")] + pub voice_query: Option, + /// Enable conversational search. + #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] + pub conversation: Option, + /// The Id of Conversation Model to be used. + #[serde(rename = "conversation_model_id", skip_serializing_if = "Option::is_none")] + pub conversation_model_id: Option, + /// The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + #[serde(rename = "conversation_id", skip_serializing_if = "Option::is_none")] + pub conversation_id: Option, } impl MultiSearchParameters { - /// Parameters for the multi search API. + /// Parameters for the multi search API. pub fn new() -> MultiSearchParameters { MultiSearchParameters { q: None, @@ -200,6 +231,7 @@ impl MultiSearchParameters { offset: None, group_by: None, group_limit: None, + group_missing_values: None, include_fields: None, exclude_fields: None, highlight_full_fields: None, @@ -208,14 +240,25 @@ impl MultiSearchParameters { highlight_end_tag: None, snippet_threshold: None, drop_tokens_threshold: None, + drop_tokens_mode: None, typo_tokens_threshold: None, + enable_typos_for_alpha_numerical_tokens: None, + filter_curated_hits: None, + enable_synonyms: None, + enable_analytics: None, + synonym_prefix: None, + synonym_num_typos: None, pinned_hits: None, hidden_hits: None, + override_tags: None, highlight_fields: None, pre_segmented_query: None, preset: None, enable_overrides: None, prioritize_exact_match: None, + prioritize_token_position: None, + prioritize_num_matching_fields: None, + enable_typos_for_numerical_tokens: None, exhaustive_search: None, search_cutoff_ms: None, use_cache: None, @@ -225,6 +268,14 @@ impl MultiSearchParameters { vector_query: None, remote_embedding_timeout_ms: None, remote_embedding_num_tries: None, + facet_strategy: None, + stopwords: None, + facet_return_parent: None, + voice_query: None, + conversation: None, + conversation_model_id: None, + conversation_id: None, } } } + diff --git a/typesense_codegen/src/models/multi_search_result.rs b/typesense_codegen/src/models/multi_search_result.rs index 1bab924..c0675e4 100644 --- a/typesense_codegen/src/models/multi_search_result.rs +++ b/typesense_codegen/src/models/multi_search_result.rs @@ -3,19 +3,28 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct MultiSearchResult { +pub struct MultiSearchResult { #[serde(rename = "results")] - pub results: Vec>, + pub results: Vec, + #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] + pub conversation: Option>, } -impl MultiSearchResult { - pub fn new(results: Vec>) -> Self { - Self { results } +impl MultiSearchResult { + pub fn new(results: Vec) -> MultiSearchResult { + MultiSearchResult { + results, + conversation: None, + } } } + diff --git a/typesense_codegen/src/models/multi_search_result_item.rs b/typesense_codegen/src/models/multi_search_result_item.rs new file mode 100644 index 0000000..8cdc357 --- /dev/null +++ b/typesense_codegen/src/models/multi_search_result_item.rs @@ -0,0 +1,75 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct MultiSearchResultItem { + #[serde(rename = "facet_counts", skip_serializing_if = "Option::is_none")] + pub facet_counts: Option>, + /// The number of documents found + #[serde(rename = "found", skip_serializing_if = "Option::is_none")] + pub found: Option, + #[serde(rename = "found_docs", skip_serializing_if = "Option::is_none")] + pub found_docs: Option, + /// The number of milliseconds the search took + #[serde(rename = "search_time_ms", skip_serializing_if = "Option::is_none")] + pub search_time_ms: Option, + /// The total number of documents in the collection + #[serde(rename = "out_of", skip_serializing_if = "Option::is_none")] + pub out_of: Option, + /// Whether the search was cut off + #[serde(rename = "search_cutoff", skip_serializing_if = "Option::is_none")] + pub search_cutoff: Option, + /// The search result page number + #[serde(rename = "page", skip_serializing_if = "Option::is_none")] + pub page: Option, + #[serde(rename = "grouped_hits", skip_serializing_if = "Option::is_none")] + pub grouped_hits: Option>, + /// The documents that matched the search query + #[serde(rename = "hits", skip_serializing_if = "Option::is_none")] + pub hits: Option>, + #[serde(rename = "request_params", skip_serializing_if = "Option::is_none")] + pub request_params: Option>, + #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] + pub conversation: Option>, + /// Returned only for union query response. + #[serde(rename = "union_request_params", skip_serializing_if = "Option::is_none")] + pub union_request_params: Option>, + /// HTTP error code + #[serde(rename = "code", skip_serializing_if = "Option::is_none")] + pub code: Option, + /// Error description + #[serde(rename = "error", skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +impl MultiSearchResultItem { + pub fn new() -> MultiSearchResultItem { + MultiSearchResultItem { + facet_counts: None, + found: None, + found_docs: None, + search_time_ms: None, + out_of: None, + search_cutoff: None, + page: None, + grouped_hits: None, + hits: None, + request_params: None, + conversation: None, + union_request_params: None, + code: None, + error: None, + } + } +} + diff --git a/typesense_codegen/src/models/multi_search_searches_parameter.rs b/typesense_codegen/src/models/multi_search_searches_parameter.rs index 1e11b6e..b4f53b1 100644 --- a/typesense_codegen/src/models/multi_search_searches_parameter.rs +++ b/typesense_codegen/src/models/multi_search_searches_parameter.rs @@ -3,21 +3,29 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct MultiSearchSearchesParameter { + /// When true, merges the search results from each search query into a single ordered set of hits. + #[serde(rename = "union", skip_serializing_if = "Option::is_none")] + pub union: Option, #[serde(rename = "searches")] - pub searches: Vec, + pub searches: Vec, } impl MultiSearchSearchesParameter { - pub fn new( - searches: Vec, - ) -> MultiSearchSearchesParameter { - MultiSearchSearchesParameter { searches } + pub fn new(searches: Vec) -> MultiSearchSearchesParameter { + MultiSearchSearchesParameter { + union: None, + searches, + } } } + diff --git a/typesense_codegen/src/models/nl_search_model_base.rs b/typesense_codegen/src/models/nl_search_model_base.rs new file mode 100644 index 0000000..8474b36 --- /dev/null +++ b/typesense_codegen/src/models/nl_search_model_base.rs @@ -0,0 +1,96 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct NlSearchModelBase { + /// Name of the NL model to use + #[serde(rename = "model_name", skip_serializing_if = "Option::is_none")] + pub model_name: Option, + /// API key for the NL model service + #[serde(rename = "api_key", skip_serializing_if = "Option::is_none")] + pub api_key: Option, + /// Custom API URL for the NL model service + #[serde(rename = "api_url", skip_serializing_if = "Option::is_none")] + pub api_url: Option, + /// Maximum number of bytes to process + #[serde(rename = "max_bytes", skip_serializing_if = "Option::is_none")] + pub max_bytes: Option, + /// Temperature parameter for the NL model + #[serde(rename = "temperature", skip_serializing_if = "Option::is_none")] + pub temperature: Option, + /// System prompt for the NL model + #[serde(rename = "system_prompt", skip_serializing_if = "Option::is_none")] + pub system_prompt: Option, + /// Top-p parameter for the NL model (Google-specific) + #[serde(rename = "top_p", skip_serializing_if = "Option::is_none")] + pub top_p: Option, + /// Top-k parameter for the NL model (Google-specific) + #[serde(rename = "top_k", skip_serializing_if = "Option::is_none")] + pub top_k: Option, + /// Stop sequences for the NL model (Google-specific) + #[serde(rename = "stop_sequences", skip_serializing_if = "Option::is_none")] + pub stop_sequences: Option>, + /// API version for the NL model service + #[serde(rename = "api_version", skip_serializing_if = "Option::is_none")] + pub api_version: Option, + /// Project ID for GCP Vertex AI + #[serde(rename = "project_id", skip_serializing_if = "Option::is_none")] + pub project_id: Option, + /// Access token for GCP Vertex AI + #[serde(rename = "access_token", skip_serializing_if = "Option::is_none")] + pub access_token: Option, + /// Refresh token for GCP Vertex AI + #[serde(rename = "refresh_token", skip_serializing_if = "Option::is_none")] + pub refresh_token: Option, + /// Client ID for GCP Vertex AI + #[serde(rename = "client_id", skip_serializing_if = "Option::is_none")] + pub client_id: Option, + /// Client secret for GCP Vertex AI + #[serde(rename = "client_secret", skip_serializing_if = "Option::is_none")] + pub client_secret: Option, + /// Region for GCP Vertex AI + #[serde(rename = "region", skip_serializing_if = "Option::is_none")] + pub region: Option, + /// Maximum output tokens for GCP Vertex AI + #[serde(rename = "max_output_tokens", skip_serializing_if = "Option::is_none")] + pub max_output_tokens: Option, + /// Account ID for Cloudflare-specific models + #[serde(rename = "account_id", skip_serializing_if = "Option::is_none")] + pub account_id: Option, +} + +impl NlSearchModelBase { + pub fn new() -> NlSearchModelBase { + NlSearchModelBase { + model_name: None, + api_key: None, + api_url: None, + max_bytes: None, + temperature: None, + system_prompt: None, + top_p: None, + top_k: None, + stop_sequences: None, + api_version: None, + project_id: None, + access_token: None, + refresh_token: None, + client_id: None, + client_secret: None, + region: None, + max_output_tokens: None, + account_id: None, + } + } +} + diff --git a/typesense_codegen/src/models/nl_search_model_create_schema.rs b/typesense_codegen/src/models/nl_search_model_create_schema.rs new file mode 100644 index 0000000..b4fd036 --- /dev/null +++ b/typesense_codegen/src/models/nl_search_model_create_schema.rs @@ -0,0 +1,100 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct NlSearchModelCreateSchema { + /// Name of the NL model to use + #[serde(rename = "model_name", skip_serializing_if = "Option::is_none")] + pub model_name: Option, + /// API key for the NL model service + #[serde(rename = "api_key", skip_serializing_if = "Option::is_none")] + pub api_key: Option, + /// Custom API URL for the NL model service + #[serde(rename = "api_url", skip_serializing_if = "Option::is_none")] + pub api_url: Option, + /// Maximum number of bytes to process + #[serde(rename = "max_bytes", skip_serializing_if = "Option::is_none")] + pub max_bytes: Option, + /// Temperature parameter for the NL model + #[serde(rename = "temperature", skip_serializing_if = "Option::is_none")] + pub temperature: Option, + /// System prompt for the NL model + #[serde(rename = "system_prompt", skip_serializing_if = "Option::is_none")] + pub system_prompt: Option, + /// Top-p parameter for the NL model (Google-specific) + #[serde(rename = "top_p", skip_serializing_if = "Option::is_none")] + pub top_p: Option, + /// Top-k parameter for the NL model (Google-specific) + #[serde(rename = "top_k", skip_serializing_if = "Option::is_none")] + pub top_k: Option, + /// Stop sequences for the NL model (Google-specific) + #[serde(rename = "stop_sequences", skip_serializing_if = "Option::is_none")] + pub stop_sequences: Option>, + /// API version for the NL model service + #[serde(rename = "api_version", skip_serializing_if = "Option::is_none")] + pub api_version: Option, + /// Project ID for GCP Vertex AI + #[serde(rename = "project_id", skip_serializing_if = "Option::is_none")] + pub project_id: Option, + /// Access token for GCP Vertex AI + #[serde(rename = "access_token", skip_serializing_if = "Option::is_none")] + pub access_token: Option, + /// Refresh token for GCP Vertex AI + #[serde(rename = "refresh_token", skip_serializing_if = "Option::is_none")] + pub refresh_token: Option, + /// Client ID for GCP Vertex AI + #[serde(rename = "client_id", skip_serializing_if = "Option::is_none")] + pub client_id: Option, + /// Client secret for GCP Vertex AI + #[serde(rename = "client_secret", skip_serializing_if = "Option::is_none")] + pub client_secret: Option, + /// Region for GCP Vertex AI + #[serde(rename = "region", skip_serializing_if = "Option::is_none")] + pub region: Option, + /// Maximum output tokens for GCP Vertex AI + #[serde(rename = "max_output_tokens", skip_serializing_if = "Option::is_none")] + pub max_output_tokens: Option, + /// Account ID for Cloudflare-specific models + #[serde(rename = "account_id", skip_serializing_if = "Option::is_none")] + pub account_id: Option, + /// Optional ID for the NL search model + #[serde(rename = "id", skip_serializing_if = "Option::is_none")] + pub id: Option, +} + +impl NlSearchModelCreateSchema { + pub fn new() -> NlSearchModelCreateSchema { + NlSearchModelCreateSchema { + model_name: None, + api_key: None, + api_url: None, + max_bytes: None, + temperature: None, + system_prompt: None, + top_p: None, + top_k: None, + stop_sequences: None, + api_version: None, + project_id: None, + access_token: None, + refresh_token: None, + client_id: None, + client_secret: None, + region: None, + max_output_tokens: None, + account_id: None, + id: None, + } + } +} + diff --git a/typesense_codegen/src/models/nl_search_model_delete_schema.rs b/typesense_codegen/src/models/nl_search_model_delete_schema.rs new file mode 100644 index 0000000..734e090 --- /dev/null +++ b/typesense_codegen/src/models/nl_search_model_delete_schema.rs @@ -0,0 +1,28 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct NlSearchModelDeleteSchema { + /// ID of the deleted NL search model + #[serde(rename = "id")] + pub id: String, +} + +impl NlSearchModelDeleteSchema { + pub fn new(id: String) -> NlSearchModelDeleteSchema { + NlSearchModelDeleteSchema { + id, + } + } +} + diff --git a/typesense_codegen/src/models/nl_search_model_schema.rs b/typesense_codegen/src/models/nl_search_model_schema.rs new file mode 100644 index 0000000..7658d9a --- /dev/null +++ b/typesense_codegen/src/models/nl_search_model_schema.rs @@ -0,0 +1,100 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct NlSearchModelSchema { + /// Name of the NL model to use + #[serde(rename = "model_name", skip_serializing_if = "Option::is_none")] + pub model_name: Option, + /// API key for the NL model service + #[serde(rename = "api_key", skip_serializing_if = "Option::is_none")] + pub api_key: Option, + /// Custom API URL for the NL model service + #[serde(rename = "api_url", skip_serializing_if = "Option::is_none")] + pub api_url: Option, + /// Maximum number of bytes to process + #[serde(rename = "max_bytes", skip_serializing_if = "Option::is_none")] + pub max_bytes: Option, + /// Temperature parameter for the NL model + #[serde(rename = "temperature", skip_serializing_if = "Option::is_none")] + pub temperature: Option, + /// System prompt for the NL model + #[serde(rename = "system_prompt", skip_serializing_if = "Option::is_none")] + pub system_prompt: Option, + /// Top-p parameter for the NL model (Google-specific) + #[serde(rename = "top_p", skip_serializing_if = "Option::is_none")] + pub top_p: Option, + /// Top-k parameter for the NL model (Google-specific) + #[serde(rename = "top_k", skip_serializing_if = "Option::is_none")] + pub top_k: Option, + /// Stop sequences for the NL model (Google-specific) + #[serde(rename = "stop_sequences", skip_serializing_if = "Option::is_none")] + pub stop_sequences: Option>, + /// API version for the NL model service + #[serde(rename = "api_version", skip_serializing_if = "Option::is_none")] + pub api_version: Option, + /// Project ID for GCP Vertex AI + #[serde(rename = "project_id", skip_serializing_if = "Option::is_none")] + pub project_id: Option, + /// Access token for GCP Vertex AI + #[serde(rename = "access_token", skip_serializing_if = "Option::is_none")] + pub access_token: Option, + /// Refresh token for GCP Vertex AI + #[serde(rename = "refresh_token", skip_serializing_if = "Option::is_none")] + pub refresh_token: Option, + /// Client ID for GCP Vertex AI + #[serde(rename = "client_id", skip_serializing_if = "Option::is_none")] + pub client_id: Option, + /// Client secret for GCP Vertex AI + #[serde(rename = "client_secret", skip_serializing_if = "Option::is_none")] + pub client_secret: Option, + /// Region for GCP Vertex AI + #[serde(rename = "region", skip_serializing_if = "Option::is_none")] + pub region: Option, + /// Maximum output tokens for GCP Vertex AI + #[serde(rename = "max_output_tokens", skip_serializing_if = "Option::is_none")] + pub max_output_tokens: Option, + /// Account ID for Cloudflare-specific models + #[serde(rename = "account_id", skip_serializing_if = "Option::is_none")] + pub account_id: Option, + /// ID of the NL search model + #[serde(rename = "id")] + pub id: String, +} + +impl NlSearchModelSchema { + pub fn new(id: String) -> NlSearchModelSchema { + NlSearchModelSchema { + model_name: None, + api_key: None, + api_url: None, + max_bytes: None, + temperature: None, + system_prompt: None, + top_p: None, + top_k: None, + stop_sequences: None, + api_version: None, + project_id: None, + access_token: None, + refresh_token: None, + client_id: None, + client_secret: None, + region: None, + max_output_tokens: None, + account_id: None, + id, + } + } +} + diff --git a/typesense_codegen/src/models/preset_delete_schema.rs b/typesense_codegen/src/models/preset_delete_schema.rs new file mode 100644 index 0000000..2e09591 --- /dev/null +++ b/typesense_codegen/src/models/preset_delete_schema.rs @@ -0,0 +1,27 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct PresetDeleteSchema { + #[serde(rename = "name")] + pub name: String, +} + +impl PresetDeleteSchema { + pub fn new(name: String) -> PresetDeleteSchema { + PresetDeleteSchema { + name, + } + } +} + diff --git a/typesense_codegen/src/models/preset_schema.rs b/typesense_codegen/src/models/preset_schema.rs new file mode 100644 index 0000000..c2ad363 --- /dev/null +++ b/typesense_codegen/src/models/preset_schema.rs @@ -0,0 +1,30 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct PresetSchema { + #[serde(rename = "value")] + pub value: Box, + #[serde(rename = "name")] + pub name: String, +} + +impl PresetSchema { + pub fn new(value: models::PresetUpsertSchemaValue, name: String) -> PresetSchema { + PresetSchema { + value: Box::new(value), + name, + } + } +} + diff --git a/typesense_codegen/src/models/preset_upsert_schema.rs b/typesense_codegen/src/models/preset_upsert_schema.rs new file mode 100644 index 0000000..f92c4f0 --- /dev/null +++ b/typesense_codegen/src/models/preset_upsert_schema.rs @@ -0,0 +1,27 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct PresetUpsertSchema { + #[serde(rename = "value")] + pub value: Box, +} + +impl PresetUpsertSchema { + pub fn new(value: models::PresetUpsertSchemaValue) -> PresetUpsertSchema { + PresetUpsertSchema { + value: Box::new(value), + } + } +} + diff --git a/typesense_codegen/src/models/preset_upsert_schema_value.rs b/typesense_codegen/src/models/preset_upsert_schema_value.rs new file mode 100644 index 0000000..f6a502f --- /dev/null +++ b/typesense_codegen/src/models/preset_upsert_schema_value.rs @@ -0,0 +1,26 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum PresetUpsertSchemaValue { + SearchParameters(Box), + MultiSearchSearchesParameter(Box), +} + +impl Default for PresetUpsertSchemaValue { + fn default() -> Self { + Self::SearchParameters(Default::default()) + } +} + diff --git a/typesense_codegen/src/models/presets_retrieve_schema.rs b/typesense_codegen/src/models/presets_retrieve_schema.rs new file mode 100644 index 0000000..752ea33 --- /dev/null +++ b/typesense_codegen/src/models/presets_retrieve_schema.rs @@ -0,0 +1,27 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct PresetsRetrieveSchema { + #[serde(rename = "presets")] + pub presets: Vec, +} + +impl PresetsRetrieveSchema { + pub fn new(presets: Vec) -> PresetsRetrieveSchema { + PresetsRetrieveSchema { + presets, + } + } +} + diff --git a/typesense_codegen/src/models/schema_change_status.rs b/typesense_codegen/src/models/schema_change_status.rs new file mode 100644 index 0000000..6021075 --- /dev/null +++ b/typesense_codegen/src/models/schema_change_status.rs @@ -0,0 +1,36 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct SchemaChangeStatus { + /// Name of the collection being modified + #[serde(rename = "collection", skip_serializing_if = "Option::is_none")] + pub collection: Option, + /// Number of documents that have been validated + #[serde(rename = "validated_docs", skip_serializing_if = "Option::is_none")] + pub validated_docs: Option, + /// Number of documents that have been altered + #[serde(rename = "altered_docs", skip_serializing_if = "Option::is_none")] + pub altered_docs: Option, +} + +impl SchemaChangeStatus { + pub fn new() -> SchemaChangeStatus { + SchemaChangeStatus { + collection: None, + validated_docs: None, + altered_docs: None, + } + } +} + diff --git a/typesense_codegen/src/models/scoped_key_parameters.rs b/typesense_codegen/src/models/scoped_key_parameters.rs index 4a88ffd..62a11af 100644 --- a/typesense_codegen/src/models/scoped_key_parameters.rs +++ b/typesense_codegen/src/models/scoped_key_parameters.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct ScopedKeyParameters { #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] @@ -24,3 +27,4 @@ impl ScopedKeyParameters { } } } + diff --git a/typesense_codegen/src/models/search_grouped_hit.rs b/typesense_codegen/src/models/search_grouped_hit.rs index b9e19cd..f55ad8d 100644 --- a/typesense_codegen/src/models/search_grouped_hit.rs +++ b/typesense_codegen/src/models/search_grouped_hit.rs @@ -3,31 +3,32 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct SearchGroupedHit { +pub struct SearchGroupedHit { #[serde(rename = "found", skip_serializing_if = "Option::is_none")] pub found: Option, #[serde(rename = "group_key")] pub group_key: Vec, /// The documents that matched the search query #[serde(rename = "hits")] - pub hits: Vec>, + pub hits: Vec, } -impl SearchGroupedHit { - pub fn new( - group_key: Vec, - hits: Vec>, - ) -> Self { - Self { +impl SearchGroupedHit { + pub fn new(group_key: Vec, hits: Vec) -> SearchGroupedHit { + SearchGroupedHit { found: None, group_key, hits, } } } + diff --git a/typesense_codegen/src/models/search_highlight.rs b/typesense_codegen/src/models/search_highlight.rs index f5b7e2a..23b8b47 100644 --- a/typesense_codegen/src/models/search_highlight.rs +++ b/typesense_codegen/src/models/search_highlight.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchHighlight { #[serde(rename = "field", skip_serializing_if = "Option::is_none")] @@ -44,3 +47,4 @@ impl SearchHighlight { } } } + diff --git a/typesense_codegen/src/models/search_override.rs b/typesense_codegen/src/models/search_override.rs index ed41718..b95ad22 100644 --- a/typesense_codegen/src/models/search_override.rs +++ b/typesense_codegen/src/models/search_override.rs @@ -3,43 +3,72 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchOverride { #[serde(rename = "rule")] - pub rule: Box, + pub rule: Box, /// List of document `id`s that should be included in the search results with their corresponding `position`s. #[serde(rename = "includes", skip_serializing_if = "Option::is_none")] - pub includes: Option>, + pub includes: Option>, /// List of document `id`s that should be excluded from the search results. #[serde(rename = "excludes", skip_serializing_if = "Option::is_none")] - pub excludes: Option>, - /// A filter by clause that is applied to any search query that matches the override rule. + pub excludes: Option>, + /// A filter by clause that is applied to any search query that matches the override rule. #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] pub filter_by: Option, - /// Indicates whether search query tokens that exist in the override's rule should be removed from the search query. - #[serde( - rename = "remove_matched_tokens", - skip_serializing_if = "Option::is_none" - )] + /// Indicates whether search query tokens that exist in the override's rule should be removed from the search query. + #[serde(rename = "remove_matched_tokens", skip_serializing_if = "Option::is_none")] pub remove_matched_tokens: Option, + /// Return a custom JSON object in the Search API response, when this rule is triggered. This can can be used to display a pre-defined message (eg: a promotion banner) on the front-end when a particular rule is triggered. + #[serde(rename = "metadata", skip_serializing_if = "Option::is_none")] + pub metadata: Option, + /// A sort by clause that is applied to any search query that matches the override rule. + #[serde(rename = "sort_by", skip_serializing_if = "Option::is_none")] + pub sort_by: Option, + /// Replaces the current search query with this value, when the search query matches the override rule. + #[serde(rename = "replace_query", skip_serializing_if = "Option::is_none")] + pub replace_query: Option, + /// When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. + #[serde(rename = "filter_curated_hits", skip_serializing_if = "Option::is_none")] + pub filter_curated_hits: Option, + /// A Unix timestamp that indicates the date/time from which the override will be active. You can use this to create override rules that start applying from a future point in time. + #[serde(rename = "effective_from_ts", skip_serializing_if = "Option::is_none")] + pub effective_from_ts: Option, + /// A Unix timestamp that indicates the date/time until which the override will be active. You can use this to create override rules that stop applying after a period of time. + #[serde(rename = "effective_to_ts", skip_serializing_if = "Option::is_none")] + pub effective_to_ts: Option, + /// When set to true, override processing will stop at the first matching rule. When set to false override processing will continue and multiple override actions will be triggered in sequence. Overrides are processed in the lexical sort order of their id field. Default: true. + #[serde(rename = "stop_processing", skip_serializing_if = "Option::is_none")] + pub stop_processing: Option, #[serde(rename = "id")] pub id: String, } impl SearchOverride { - pub fn new(rule: crate::models::SearchOverrideRule, id: String) -> SearchOverride { + pub fn new(rule: models::SearchOverrideRule, id: String) -> SearchOverride { SearchOverride { rule: Box::new(rule), includes: None, excludes: None, filter_by: None, remove_matched_tokens: None, + metadata: None, + sort_by: None, + replace_query: None, + filter_curated_hits: None, + effective_from_ts: None, + effective_to_ts: None, + stop_processing: None, id, } } } + diff --git a/typesense_codegen/src/models/search_override_delete_response.rs b/typesense_codegen/src/models/search_override_delete_response.rs new file mode 100644 index 0000000..1842bd5 --- /dev/null +++ b/typesense_codegen/src/models/search_override_delete_response.rs @@ -0,0 +1,28 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct SearchOverrideDeleteResponse { + /// The id of the override that was deleted + #[serde(rename = "id")] + pub id: String, +} + +impl SearchOverrideDeleteResponse { + pub fn new(id: String) -> SearchOverrideDeleteResponse { + SearchOverrideDeleteResponse { + id, + } + } +} + diff --git a/typesense_codegen/src/models/search_override_exclude.rs b/typesense_codegen/src/models/search_override_exclude.rs index 1cea902..177ea55 100644 --- a/typesense_codegen/src/models/search_override_exclude.rs +++ b/typesense_codegen/src/models/search_override_exclude.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchOverrideExclude { /// document id that should be excluded from the search results. @@ -17,6 +20,9 @@ pub struct SearchOverrideExclude { impl SearchOverrideExclude { pub fn new(id: String) -> SearchOverrideExclude { - SearchOverrideExclude { id } + SearchOverrideExclude { + id, + } } } + diff --git a/typesense_codegen/src/models/search_override_include.rs b/typesense_codegen/src/models/search_override_include.rs index 3cdbff2..5f275bb 100644 --- a/typesense_codegen/src/models/search_override_include.rs +++ b/typesense_codegen/src/models/search_override_include.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchOverrideInclude { /// document id that should be included @@ -20,6 +23,10 @@ pub struct SearchOverrideInclude { impl SearchOverrideInclude { pub fn new(id: String, position: i32) -> SearchOverrideInclude { - SearchOverrideInclude { id, position } + SearchOverrideInclude { + id, + position, + } } } + diff --git a/typesense_codegen/src/models/search_override_rule.rs b/typesense_codegen/src/models/search_override_rule.rs index f5a339b..923171d 100644 --- a/typesense_codegen/src/models/search_override_rule.rs +++ b/typesense_codegen/src/models/search_override_rule.rs @@ -3,28 +3,41 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchOverrideRule { + /// List of tag values to associate with this override rule. + #[serde(rename = "tags", skip_serializing_if = "Option::is_none")] + pub tags: Option>, /// Indicates what search queries should be overridden - #[serde(rename = "query")] - pub query: String, - /// Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. - #[serde(rename = "match")] - pub r#match: Match, + #[serde(rename = "query", skip_serializing_if = "Option::is_none")] + pub query: Option, + /// Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. + #[serde(rename = "match", skip_serializing_if = "Option::is_none")] + pub r#match: Option, + /// Indicates that the override should apply when the filter_by parameter in a search query exactly matches the string specified here (including backticks, spaces, brackets, etc). + #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] + pub filter_by: Option, } impl SearchOverrideRule { - pub fn new(query: String, r#match: Match) -> SearchOverrideRule { - SearchOverrideRule { query, r#match } + pub fn new() -> SearchOverrideRule { + SearchOverrideRule { + tags: None, + query: None, + r#match: None, + filter_by: None, + } } } - -/// Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. +/// Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum Match { #[serde(rename = "exact")] @@ -38,3 +51,4 @@ impl Default for Match { Self::Exact } } + diff --git a/typesense_codegen/src/models/search_override_schema.rs b/typesense_codegen/src/models/search_override_schema.rs index 7b3eedb..5997bcd 100644 --- a/typesense_codegen/src/models/search_override_schema.rs +++ b/typesense_codegen/src/models/search_override_schema.rs @@ -3,40 +3,69 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchOverrideSchema { #[serde(rename = "rule")] - pub rule: Box, + pub rule: Box, /// List of document `id`s that should be included in the search results with their corresponding `position`s. #[serde(rename = "includes", skip_serializing_if = "Option::is_none")] - pub includes: Option>, + pub includes: Option>, /// List of document `id`s that should be excluded from the search results. #[serde(rename = "excludes", skip_serializing_if = "Option::is_none")] - pub excludes: Option>, - /// A filter by clause that is applied to any search query that matches the override rule. + pub excludes: Option>, + /// A filter by clause that is applied to any search query that matches the override rule. #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] pub filter_by: Option, - /// Indicates whether search query tokens that exist in the override's rule should be removed from the search query. - #[serde( - rename = "remove_matched_tokens", - skip_serializing_if = "Option::is_none" - )] + /// Indicates whether search query tokens that exist in the override's rule should be removed from the search query. + #[serde(rename = "remove_matched_tokens", skip_serializing_if = "Option::is_none")] pub remove_matched_tokens: Option, + /// Return a custom JSON object in the Search API response, when this rule is triggered. This can can be used to display a pre-defined message (eg: a promotion banner) on the front-end when a particular rule is triggered. + #[serde(rename = "metadata", skip_serializing_if = "Option::is_none")] + pub metadata: Option, + /// A sort by clause that is applied to any search query that matches the override rule. + #[serde(rename = "sort_by", skip_serializing_if = "Option::is_none")] + pub sort_by: Option, + /// Replaces the current search query with this value, when the search query matches the override rule. + #[serde(rename = "replace_query", skip_serializing_if = "Option::is_none")] + pub replace_query: Option, + /// When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. + #[serde(rename = "filter_curated_hits", skip_serializing_if = "Option::is_none")] + pub filter_curated_hits: Option, + /// A Unix timestamp that indicates the date/time from which the override will be active. You can use this to create override rules that start applying from a future point in time. + #[serde(rename = "effective_from_ts", skip_serializing_if = "Option::is_none")] + pub effective_from_ts: Option, + /// A Unix timestamp that indicates the date/time until which the override will be active. You can use this to create override rules that stop applying after a period of time. + #[serde(rename = "effective_to_ts", skip_serializing_if = "Option::is_none")] + pub effective_to_ts: Option, + /// When set to true, override processing will stop at the first matching rule. When set to false override processing will continue and multiple override actions will be triggered in sequence. Overrides are processed in the lexical sort order of their id field. Default: true. + #[serde(rename = "stop_processing", skip_serializing_if = "Option::is_none")] + pub stop_processing: Option, } impl SearchOverrideSchema { - pub fn new(rule: crate::models::SearchOverrideRule) -> SearchOverrideSchema { + pub fn new(rule: models::SearchOverrideRule) -> SearchOverrideSchema { SearchOverrideSchema { rule: Box::new(rule), includes: None, excludes: None, filter_by: None, remove_matched_tokens: None, + metadata: None, + sort_by: None, + replace_query: None, + filter_curated_hits: None, + effective_from_ts: None, + effective_to_ts: None, + stop_processing: None, } } } + diff --git a/typesense_codegen/src/models/search_overrides_response.rs b/typesense_codegen/src/models/search_overrides_response.rs index 1c4e49b..c71e776 100644 --- a/typesense_codegen/src/models/search_overrides_response.rs +++ b/typesense_codegen/src/models/search_overrides_response.rs @@ -3,19 +3,25 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchOverridesResponse { #[serde(rename = "overrides")] - pub overrides: Vec, + pub overrides: Vec, } impl SearchOverridesResponse { - pub fn new(overrides: Vec) -> SearchOverridesResponse { - SearchOverridesResponse { overrides } + pub fn new(overrides: Vec) -> SearchOverridesResponse { + SearchOverridesResponse { + overrides, + } } } + diff --git a/typesense_codegen/src/models/search_parameters.rs b/typesense_codegen/src/models/search_parameters.rs index 3c1fb07..28ff332 100644 --- a/typesense_codegen/src/models/search_parameters.rs +++ b/typesense_codegen/src/models/search_parameters.rs @@ -3,19 +3,28 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchParameters { /// The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. - #[serde(rename = "q")] - pub q: String, + #[serde(rename = "q", skip_serializing_if = "Option::is_none")] + pub q: Option, /// A list of `string` fields that should be queried against. Multiple fields are separated with a comma. - #[serde(rename = "query_by")] - pub query_by: String, + #[serde(rename = "query_by", skip_serializing_if = "Option::is_none")] + pub query_by: Option, + /// Whether to use natural language processing to parse the query. + #[serde(rename = "nl_query", skip_serializing_if = "Option::is_none")] + pub nl_query: Option, + /// The ID of the natural language model to use. + #[serde(rename = "nl_model_id", skip_serializing_if = "Option::is_none")] + pub nl_model_id: Option, /// The relative weight to give each `query_by` field when ranking results. This can be used to boost fields in priority, when looking for matches. Multiple fields are separated with a comma. #[serde(rename = "query_by_weights", skip_serializing_if = "Option::is_none")] pub query_by_weights: Option, @@ -34,9 +43,12 @@ pub struct SearchParameters { /// There are also 2 parameters that allow you to control the extent of infix searching max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before or after the query that can be present in the token. For example query \"K2100\" has 2 extra symbols in \"6PK2100\". By default, any number of prefixes/suffixes can be present for a match. #[serde(rename = "max_extra_suffix", skip_serializing_if = "Option::is_none")] pub max_extra_suffix: Option, - /// Filter conditions for refining youropen api validator search results. Separate multiple conditions with &&. + /// Filter conditions for refining your open api validator search results. Separate multiple conditions with &&. #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] pub filter_by: Option, + /// Controls the number of similar words that Typesense considers during fuzzy search on filter_by values. Useful for controlling prefix matches like company_name:Acm*. + #[serde(rename = "max_filter_by_candidates", skip_serializing_if = "Option::is_none")] + pub max_filter_by_candidates: Option, /// A list of numerical fields and their corresponding sort orders that will be used for ordering your results. Up to 3 sort fields can be specified. The text similarity score is exposed as a special `_text_match` field that you can use in the list of sorting fields. If no `sort_by` parameter is specified, results are sorted by `_text_match:desc,default_sorting_field:desc` #[serde(rename = "sort_by", skip_serializing_if = "Option::is_none")] pub sort_by: Option, @@ -49,7 +61,7 @@ pub struct SearchParameters { /// Facet values that are returned can now be filtered via this parameter. The matching facet text is also highlighted. For example, when faceting by `category`, you can set `facet_query=category:shoe` to return only facet values that contain the prefix \"shoe\". #[serde(rename = "facet_query", skip_serializing_if = "Option::is_none")] pub facet_query: Option, - /// The number of typographical errors (1 or 2) that would be tolerated. Default: 2 + /// The number of typographical errors (1 or 2) that would be tolerated. Default: 2 #[serde(rename = "num_typos", skip_serializing_if = "Option::is_none")] pub num_typos: Option, /// Results from this specific page number would be fetched. @@ -58,7 +70,7 @@ pub struct SearchParameters { /// Number of results to fetch per page. Default: 10 #[serde(rename = "per_page", skip_serializing_if = "Option::is_none")] pub per_page: Option, - /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. + /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. #[serde(rename = "limit", skip_serializing_if = "Option::is_none")] pub limit: Option, /// Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. @@ -67,9 +79,12 @@ pub struct SearchParameters { /// You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. #[serde(rename = "group_by", skip_serializing_if = "Option::is_none")] pub group_by: Option, - /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 + /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 #[serde(rename = "group_limit", skip_serializing_if = "Option::is_none")] pub group_limit: Option, + /// Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true + #[serde(rename = "group_missing_values", skip_serializing_if = "Option::is_none")] + pub group_missing_values: Option, /// List of fields from the document to include in the search result #[serde(rename = "include_fields", skip_serializing_if = "Option::is_none")] pub include_fields: Option, @@ -77,126 +92,148 @@ pub struct SearchParameters { #[serde(rename = "exclude_fields", skip_serializing_if = "Option::is_none")] pub exclude_fields: Option, /// List of fields which should be highlighted fully without snippeting - #[serde( - rename = "highlight_full_fields", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "highlight_full_fields", skip_serializing_if = "Option::is_none")] pub highlight_full_fields: Option, - /// The number of tokens that should surround the highlighted text on each side. Default: 4 - #[serde( - rename = "highlight_affix_num_tokens", - skip_serializing_if = "Option::is_none" - )] + /// The number of tokens that should surround the highlighted text on each side. Default: 4 + #[serde(rename = "highlight_affix_num_tokens", skip_serializing_if = "Option::is_none")] pub highlight_affix_num_tokens: Option, - /// The start tag used for the highlighted snippets. Default: `` - #[serde( - rename = "highlight_start_tag", - skip_serializing_if = "Option::is_none" - )] + /// The start tag used for the highlighted snippets. Default: `` + #[serde(rename = "highlight_start_tag", skip_serializing_if = "Option::is_none")] pub highlight_start_tag: Option, - /// The end tag used for the highlighted snippets. Default: `` + /// The end tag used for the highlighted snippets. Default: `` #[serde(rename = "highlight_end_tag", skip_serializing_if = "Option::is_none")] pub highlight_end_tag: Option, - /// Flag for enabling/disabling the deprecated, old highlight structure in the response. Default: true - #[serde( - rename = "enable_highlight_v1", - skip_serializing_if = "Option::is_none" - )] + /// Flag for enabling/disabling the deprecated, old highlight structure in the response. Default: true + #[serde(rename = "enable_highlight_v1", skip_serializing_if = "Option::is_none")] pub enable_highlight_v1: Option, - /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 + /// Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). + #[serde(rename = "enable_analytics", skip_serializing_if = "Option::is_none")] + pub enable_analytics: Option, + /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 #[serde(rename = "snippet_threshold", skip_serializing_if = "Option::is_none")] pub snippet_threshold: Option, - /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 - #[serde( - rename = "drop_tokens_threshold", - skip_serializing_if = "Option::is_none" - )] + /// List of synonym set names to associate with this search query + #[serde(rename = "synonym_sets", skip_serializing_if = "Option::is_none")] + pub synonym_sets: Option, + /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 + #[serde(rename = "drop_tokens_threshold", skip_serializing_if = "Option::is_none")] pub drop_tokens_threshold: Option, - /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 - #[serde( - rename = "typo_tokens_threshold", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "drop_tokens_mode", skip_serializing_if = "Option::is_none")] + pub drop_tokens_mode: Option, + /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 + #[serde(rename = "typo_tokens_threshold", skip_serializing_if = "Option::is_none")] pub typo_tokens_threshold: Option, - /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + #[serde(rename = "enable_typos_for_alpha_numerical_tokens", skip_serializing_if = "Option::is_none")] + pub enable_typos_for_alpha_numerical_tokens: Option, + /// Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + #[serde(rename = "filter_curated_hits", skip_serializing_if = "Option::is_none")] + pub filter_curated_hits: Option, + /// If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + #[serde(rename = "enable_synonyms", skip_serializing_if = "Option::is_none")] + pub enable_synonyms: Option, + /// Allow synonym resolution on word prefixes in the query. Default: false + #[serde(rename = "synonym_prefix", skip_serializing_if = "Option::is_none")] + pub synonym_prefix: Option, + /// Allow synonym resolution on typo-corrected words in the query. Default: 0 + #[serde(rename = "synonym_num_typos", skip_serializing_if = "Option::is_none")] + pub synonym_num_typos: Option, + /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "pinned_hits", skip_serializing_if = "Option::is_none")] pub pinned_hits: Option, - /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "hidden_hits", skip_serializing_if = "Option::is_none")] pub hidden_hits: Option, - /// A list of custom fields that must be highlighted even if you don't query for them + /// Comma separated list of tags to trigger the curations rules that match the tags. + #[serde(rename = "override_tags", skip_serializing_if = "Option::is_none")] + pub override_tags: Option, + /// A list of custom fields that must be highlighted even if you don't query for them #[serde(rename = "highlight_fields", skip_serializing_if = "Option::is_none")] pub highlight_fields: Option, - /// Treat space as typo: search for q=basket ball if q=basketball is not found or vice-versa. Splitting/joining of tokens will only be attempted if the original query produces no results. To always trigger this behavior, set value to `always``. To disable, set value to `off`. Default is `fallback`. + /// Treat space as typo: search for q=basket ball if q=basketball is not found or vice-versa. Splitting/joining of tokens will only be attempted if the original query produces no results. To always trigger this behavior, set value to `always``. To disable, set value to `off`. Default is `fallback`. #[serde(rename = "split_join_tokens", skip_serializing_if = "Option::is_none")] pub split_join_tokens: Option, - /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same - #[serde( - rename = "pre_segmented_query", - skip_serializing_if = "Option::is_none" - )] + /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same + #[serde(rename = "pre_segmented_query", skip_serializing_if = "Option::is_none")] pub pre_segmented_query: Option, - /// Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. + /// Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. #[serde(rename = "preset", skip_serializing_if = "Option::is_none")] pub preset: Option, - /// If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false + /// If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false #[serde(rename = "enable_overrides", skip_serializing_if = "Option::is_none")] pub enable_overrides: Option, - /// Set this parameter to true to ensure that an exact match is ranked above the others - #[serde( - rename = "prioritize_exact_match", - skip_serializing_if = "Option::is_none" - )] + /// Set this parameter to true to ensure that an exact match is ranked above the others + #[serde(rename = "prioritize_exact_match", skip_serializing_if = "Option::is_none")] pub prioritize_exact_match: Option, - /// Control the number of words that Typesense considers for typo and prefix searching. + /// Control the number of words that Typesense considers for typo and prefix searching. #[serde(rename = "max_candidates", skip_serializing_if = "Option::is_none")] pub max_candidates: Option, - /// Make Typesense prioritize documents where the query words appear earlier in the text. - #[serde( - rename = "prioritize_token_position", - skip_serializing_if = "Option::is_none" - )] + /// Make Typesense prioritize documents where the query words appear earlier in the text. + #[serde(rename = "prioritize_token_position", skip_serializing_if = "Option::is_none")] pub prioritize_token_position: Option, - /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). + /// Make Typesense prioritize documents where the query words appear in more number of fields. + #[serde(rename = "prioritize_num_matching_fields", skip_serializing_if = "Option::is_none")] + pub prioritize_num_matching_fields: Option, + /// Make Typesense disable typos for numerical tokens. + #[serde(rename = "enable_typos_for_numerical_tokens", skip_serializing_if = "Option::is_none")] + pub enable_typos_for_numerical_tokens: Option, + /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). #[serde(rename = "exhaustive_search", skip_serializing_if = "Option::is_none")] pub exhaustive_search: Option, - /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. + /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. #[serde(rename = "search_cutoff_ms", skip_serializing_if = "Option::is_none")] pub search_cutoff_ms: Option, - /// Enable server side caching of search query results. By default, caching is disabled. + /// Enable server side caching of search query results. By default, caching is disabled. #[serde(rename = "use_cache", skip_serializing_if = "Option::is_none")] pub use_cache: Option, - /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. + /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. #[serde(rename = "cache_ttl", skip_serializing_if = "Option::is_none")] pub cache_ttl: Option, - /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_1typo", skip_serializing_if = "Option::is_none")] pub min_len_1typo: Option, - /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_2typo", skip_serializing_if = "Option::is_none")] pub min_len_2typo: Option, - /// Vector query expression for fetching documents \"closest\" to a given query/document vector. + /// Vector query expression for fetching documents \"closest\" to a given query/document vector. #[serde(rename = "vector_query", skip_serializing_if = "Option::is_none")] pub vector_query: Option, - /// Timeout (in milliseconds) for fetching remote embeddings. - #[serde( - rename = "remote_embedding_timeout_ms", - skip_serializing_if = "Option::is_none" - )] + /// Timeout (in milliseconds) for fetching remote embeddings. + #[serde(rename = "remote_embedding_timeout_ms", skip_serializing_if = "Option::is_none")] pub remote_embedding_timeout_ms: Option, - /// Number of times to retry fetching remote embeddings. - #[serde( - rename = "remote_embedding_num_tries", - skip_serializing_if = "Option::is_none" - )] + /// Number of times to retry fetching remote embeddings. + #[serde(rename = "remote_embedding_num_tries", skip_serializing_if = "Option::is_none")] pub remote_embedding_num_tries: Option, + /// Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). + #[serde(rename = "facet_strategy", skip_serializing_if = "Option::is_none")] + pub facet_strategy: Option, + /// Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. + #[serde(rename = "stopwords", skip_serializing_if = "Option::is_none")] + pub stopwords: Option, + /// Comma separated string of nested facet fields whose parent object should be returned in facet response. + #[serde(rename = "facet_return_parent", skip_serializing_if = "Option::is_none")] + pub facet_return_parent: Option, + /// The base64 encoded audio file in 16 khz 16-bit WAV format. + #[serde(rename = "voice_query", skip_serializing_if = "Option::is_none")] + pub voice_query: Option, + /// Enable conversational search. + #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] + pub conversation: Option, + /// The Id of Conversation Model to be used. + #[serde(rename = "conversation_model_id", skip_serializing_if = "Option::is_none")] + pub conversation_model_id: Option, + /// The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + #[serde(rename = "conversation_id", skip_serializing_if = "Option::is_none")] + pub conversation_id: Option, } impl SearchParameters { - pub fn new(q: String, query_by: String) -> SearchParameters { + pub fn new() -> SearchParameters { SearchParameters { - q, - query_by, + q: None, + query_by: None, + nl_query: None, + nl_model_id: None, query_by_weights: None, text_match_type: None, prefix: None, @@ -204,6 +241,7 @@ impl SearchParameters { max_extra_prefix: None, max_extra_suffix: None, filter_by: None, + max_filter_by_candidates: None, sort_by: None, facet_by: None, max_facet_values: None, @@ -215,6 +253,7 @@ impl SearchParameters { offset: None, group_by: None, group_limit: None, + group_missing_values: None, include_fields: None, exclude_fields: None, highlight_full_fields: None, @@ -222,11 +261,20 @@ impl SearchParameters { highlight_start_tag: None, highlight_end_tag: None, enable_highlight_v1: None, + enable_analytics: None, snippet_threshold: None, + synonym_sets: None, drop_tokens_threshold: None, + drop_tokens_mode: None, typo_tokens_threshold: None, + enable_typos_for_alpha_numerical_tokens: None, + filter_curated_hits: None, + enable_synonyms: None, + synonym_prefix: None, + synonym_num_typos: None, pinned_hits: None, hidden_hits: None, + override_tags: None, highlight_fields: None, split_join_tokens: None, pre_segmented_query: None, @@ -235,6 +283,8 @@ impl SearchParameters { prioritize_exact_match: None, max_candidates: None, prioritize_token_position: None, + prioritize_num_matching_fields: None, + enable_typos_for_numerical_tokens: None, exhaustive_search: None, search_cutoff_ms: None, use_cache: None, @@ -244,6 +294,14 @@ impl SearchParameters { vector_query: None, remote_embedding_timeout_ms: None, remote_embedding_num_tries: None, + facet_strategy: None, + stopwords: None, + facet_return_parent: None, + voice_query: None, + conversation: None, + conversation_model_id: None, + conversation_id: None, } } } + diff --git a/typesense_codegen/src/models/search_result_request_params.rs b/typesense_codegen/src/models/search_request_params.rs similarity index 57% rename from typesense_codegen/src/models/search_result_request_params.rs rename to typesense_codegen/src/models/search_request_params.rs index 94e323b..bcdca8d 100644 --- a/typesense_codegen/src/models/search_result_request_params.rs +++ b/typesense_codegen/src/models/search_request_params.rs @@ -3,27 +3,34 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct SearchResultRequestParams { +pub struct SearchRequestParams { #[serde(rename = "collection_name")] pub collection_name: String, #[serde(rename = "q")] pub q: String, #[serde(rename = "per_page")] pub per_page: i32, + #[serde(rename = "voice_query", skip_serializing_if = "Option::is_none")] + pub voice_query: Option>, } -impl SearchResultRequestParams { - pub fn new(collection_name: String, q: String, per_page: i32) -> SearchResultRequestParams { - SearchResultRequestParams { +impl SearchRequestParams { + pub fn new(collection_name: String, q: String, per_page: i32) -> SearchRequestParams { + SearchRequestParams { collection_name, q, per_page, + voice_query: None, } } } + diff --git a/typesense_codegen/src/models/search_request_params_voice_query.rs b/typesense_codegen/src/models/search_request_params_voice_query.rs new file mode 100644 index 0000000..4c5efdd --- /dev/null +++ b/typesense_codegen/src/models/search_request_params_voice_query.rs @@ -0,0 +1,27 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct SearchRequestParamsVoiceQuery { + #[serde(rename = "transcribed_query", skip_serializing_if = "Option::is_none")] + pub transcribed_query: Option, +} + +impl SearchRequestParamsVoiceQuery { + pub fn new() -> SearchRequestParamsVoiceQuery { + SearchRequestParamsVoiceQuery { + transcribed_query: None, + } + } +} + diff --git a/typesense_codegen/src/models/search_result.rs b/typesense_codegen/src/models/search_result.rs index 11527ab..68179bb 100644 --- a/typesense_codegen/src/models/search_result.rs +++ b/typesense_codegen/src/models/search_result.rs @@ -3,18 +3,23 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct SearchResult { +pub struct SearchResult { #[serde(rename = "facet_counts", skip_serializing_if = "Option::is_none")] - pub facet_counts: Option>, + pub facet_counts: Option>, /// The number of documents found #[serde(rename = "found", skip_serializing_if = "Option::is_none")] pub found: Option, + #[serde(rename = "found_docs", skip_serializing_if = "Option::is_none")] + pub found_docs: Option, /// The number of milliseconds the search took #[serde(rename = "search_time_ms", skip_serializing_if = "Option::is_none")] pub search_time_ms: Option, @@ -28,19 +33,25 @@ pub struct SearchResult { #[serde(rename = "page", skip_serializing_if = "Option::is_none")] pub page: Option, #[serde(rename = "grouped_hits", skip_serializing_if = "Option::is_none")] - pub grouped_hits: Option>>, + pub grouped_hits: Option>, /// The documents that matched the search query #[serde(rename = "hits", skip_serializing_if = "Option::is_none")] - pub hits: Option>>, + pub hits: Option>, #[serde(rename = "request_params", skip_serializing_if = "Option::is_none")] - pub request_params: Option>, + pub request_params: Option>, + #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] + pub conversation: Option>, + /// Returned only for union query response. + #[serde(rename = "union_request_params", skip_serializing_if = "Option::is_none")] + pub union_request_params: Option>, } -impl SearchResult { - pub fn new() -> Self { - Self { +impl SearchResult { + pub fn new() -> SearchResult { + SearchResult { facet_counts: None, found: None, + found_docs: None, search_time_ms: None, out_of: None, search_cutoff: None, @@ -48,6 +59,9 @@ impl SearchResult { grouped_hits: None, hits: None, request_params: None, + conversation: None, + union_request_params: None, } } } + diff --git a/typesense_codegen/src/models/search_result_conversation.rs b/typesense_codegen/src/models/search_result_conversation.rs new file mode 100644 index 0000000..959f287 --- /dev/null +++ b/typesense_codegen/src/models/search_result_conversation.rs @@ -0,0 +1,36 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct SearchResultConversation { + #[serde(rename = "answer")] + pub answer: String, + #[serde(rename = "conversation_history")] + pub conversation_history: Vec, + #[serde(rename = "conversation_id")] + pub conversation_id: String, + #[serde(rename = "query")] + pub query: String, +} + +impl SearchResultConversation { + pub fn new(answer: String, conversation_history: Vec, conversation_id: String, query: String) -> SearchResultConversation { + SearchResultConversation { + answer, + conversation_history, + conversation_id, + query, + } + } +} + diff --git a/typesense_codegen/src/models/search_result_hit.rs b/typesense_codegen/src/models/search_result_hit.rs index d637e65..7736414 100644 --- a/typesense_codegen/src/models/search_result_hit.rs +++ b/typesense_codegen/src/models/search_result_hit.rs @@ -3,44 +3,55 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct SearchResultHit { +pub struct SearchResultHit { /// (Deprecated) Contains highlighted portions of the search fields #[serde(rename = "highlights", skip_serializing_if = "Option::is_none")] - pub highlights: Option>, + pub highlights: Option>, /// Highlighted version of the matching document #[serde(rename = "highlight", skip_serializing_if = "Option::is_none")] - pub highlight: Option<::std::collections::HashMap>, + pub highlight: Option>, /// Can be any key-value pair #[serde(rename = "document", skip_serializing_if = "Option::is_none")] - pub document: Option, + pub document: Option>, #[serde(rename = "text_match", skip_serializing_if = "Option::is_none")] pub text_match: Option, + #[serde(rename = "text_match_info", skip_serializing_if = "Option::is_none")] + pub text_match_info: Option>, /// Can be any key-value pair - #[serde( - rename = "geo_distance_meters", - skip_serializing_if = "Option::is_none" - )] - pub geo_distance_meters: Option<::std::collections::HashMap>, + #[serde(rename = "geo_distance_meters", skip_serializing_if = "Option::is_none")] + pub geo_distance_meters: Option>, /// Distance between the query vector and matching document's vector value #[serde(rename = "vector_distance", skip_serializing_if = "Option::is_none")] pub vector_distance: Option, + #[serde(rename = "hybrid_search_info", skip_serializing_if = "Option::is_none")] + pub hybrid_search_info: Option>, + /// Returned only for union query response. Indicates the index of the query which this document matched to. + #[serde(rename = "search_index", skip_serializing_if = "Option::is_none")] + pub search_index: Option, } -impl SearchResultHit { - pub fn new() -> Self { - Self { +impl SearchResultHit { + pub fn new() -> SearchResultHit { + SearchResultHit { highlights: None, highlight: None, document: None, text_match: None, + text_match_info: None, geo_distance_meters: None, vector_distance: None, + hybrid_search_info: None, + search_index: None, } } } + diff --git a/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs b/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs new file mode 100644 index 0000000..4035e5f --- /dev/null +++ b/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs @@ -0,0 +1,30 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +/// SearchResultHitHybridSearchInfo : Information about hybrid search scoring +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct SearchResultHitHybridSearchInfo { + /// Combined score from rank fusion of text and vector search + #[serde(rename = "rank_fusion_score", skip_serializing_if = "Option::is_none")] + pub rank_fusion_score: Option, +} + +impl SearchResultHitHybridSearchInfo { + /// Information about hybrid search scoring + pub fn new() -> SearchResultHitHybridSearchInfo { + SearchResultHitHybridSearchInfo { + rank_fusion_score: None, + } + } +} + diff --git a/typesense_codegen/src/models/search_result_hit_text_match_info.rs b/typesense_codegen/src/models/search_result_hit_text_match_info.rs new file mode 100644 index 0000000..08b0740 --- /dev/null +++ b/typesense_codegen/src/models/search_result_hit_text_match_info.rs @@ -0,0 +1,45 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct SearchResultHitTextMatchInfo { + #[serde(rename = "best_field_score", skip_serializing_if = "Option::is_none")] + pub best_field_score: Option, + #[serde(rename = "best_field_weight", skip_serializing_if = "Option::is_none")] + pub best_field_weight: Option, + #[serde(rename = "fields_matched", skip_serializing_if = "Option::is_none")] + pub fields_matched: Option, + #[serde(rename = "num_tokens_dropped", skip_serializing_if = "Option::is_none")] + pub num_tokens_dropped: Option, + #[serde(rename = "score", skip_serializing_if = "Option::is_none")] + pub score: Option, + #[serde(rename = "tokens_matched", skip_serializing_if = "Option::is_none")] + pub tokens_matched: Option, + #[serde(rename = "typo_prefix_score", skip_serializing_if = "Option::is_none")] + pub typo_prefix_score: Option, +} + +impl SearchResultHitTextMatchInfo { + pub fn new() -> SearchResultHitTextMatchInfo { + SearchResultHitTextMatchInfo { + best_field_score: None, + best_field_weight: None, + fields_matched: None, + num_tokens_dropped: None, + score: None, + tokens_matched: None, + typo_prefix_score: None, + } + } +} + diff --git a/typesense_codegen/src/models/search_synonym.rs b/typesense_codegen/src/models/search_synonym.rs index acf9fd8..bb13105 100644 --- a/typesense_codegen/src/models/search_synonym.rs +++ b/typesense_codegen/src/models/search_synonym.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchSynonym { /// For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. @@ -16,6 +19,12 @@ pub struct SearchSynonym { /// Array of words that should be considered as synonyms. #[serde(rename = "synonyms")] pub synonyms: Vec, + /// Locale for the synonym, leave blank to use the standard tokenizer. + #[serde(rename = "locale", skip_serializing_if = "Option::is_none")] + pub locale: Option, + /// By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is. + #[serde(rename = "symbols_to_index", skip_serializing_if = "Option::is_none")] + pub symbols_to_index: Option>, #[serde(rename = "id")] pub id: String, } @@ -25,7 +34,10 @@ impl SearchSynonym { SearchSynonym { root: None, synonyms, + locale: None, + symbols_to_index: None, id, } } } + diff --git a/typesense_codegen/src/models/search_synonym_delete_response.rs b/typesense_codegen/src/models/search_synonym_delete_response.rs new file mode 100644 index 0000000..3c3563a --- /dev/null +++ b/typesense_codegen/src/models/search_synonym_delete_response.rs @@ -0,0 +1,28 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct SearchSynonymDeleteResponse { + /// The id of the synonym that was deleted + #[serde(rename = "id")] + pub id: String, +} + +impl SearchSynonymDeleteResponse { + pub fn new(id: String) -> SearchSynonymDeleteResponse { + SearchSynonymDeleteResponse { + id, + } + } +} + diff --git a/typesense_codegen/src/models/search_synonym_schema.rs b/typesense_codegen/src/models/search_synonym_schema.rs index eab5596..38ef415 100644 --- a/typesense_codegen/src/models/search_synonym_schema.rs +++ b/typesense_codegen/src/models/search_synonym_schema.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchSynonymSchema { /// For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. @@ -16,6 +19,12 @@ pub struct SearchSynonymSchema { /// Array of words that should be considered as synonyms. #[serde(rename = "synonyms")] pub synonyms: Vec, + /// Locale for the synonym, leave blank to use the standard tokenizer. + #[serde(rename = "locale", skip_serializing_if = "Option::is_none")] + pub locale: Option, + /// By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is. + #[serde(rename = "symbols_to_index", skip_serializing_if = "Option::is_none")] + pub symbols_to_index: Option>, } impl SearchSynonymSchema { @@ -23,6 +32,9 @@ impl SearchSynonymSchema { SearchSynonymSchema { root: None, synonyms, + locale: None, + symbols_to_index: None, } } } + diff --git a/typesense_codegen/src/models/search_synonyms_response.rs b/typesense_codegen/src/models/search_synonyms_response.rs index a3fefdf..6c84a34 100644 --- a/typesense_codegen/src/models/search_synonyms_response.rs +++ b/typesense_codegen/src/models/search_synonyms_response.rs @@ -3,19 +3,25 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchSynonymsResponse { #[serde(rename = "synonyms")] - pub synonyms: Vec, + pub synonyms: Vec, } impl SearchSynonymsResponse { - pub fn new(synonyms: Vec) -> SearchSynonymsResponse { - SearchSynonymsResponse { synonyms } + pub fn new(synonyms: Vec) -> SearchSynonymsResponse { + SearchSynonymsResponse { + synonyms, + } } } + diff --git a/typesense_codegen/src/models/snapshot_parameters.rs b/typesense_codegen/src/models/snapshot_parameters.rs deleted file mode 100644 index aa2c6a5..0000000 --- a/typesense_codegen/src/models/snapshot_parameters.rs +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Typesense API - * - * An open source search engine for building delightful search experiences. - * - * The version of the OpenAPI document: 0.25.0 - * - * Generated by: https://openapi-generator.tech - */ - -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct SnapshotParameters { - #[serde(rename = "snapshot_path", skip_serializing_if = "Option::is_none")] - pub snapshot_path: Option, -} - -impl SnapshotParameters { - pub fn new() -> SnapshotParameters { - SnapshotParameters { - snapshot_path: None, - } - } -} diff --git a/typesense_codegen/src/models/stemming_dictionary.rs b/typesense_codegen/src/models/stemming_dictionary.rs new file mode 100644 index 0000000..db946aa --- /dev/null +++ b/typesense_codegen/src/models/stemming_dictionary.rs @@ -0,0 +1,32 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct StemmingDictionary { + /// Unique identifier for the dictionary + #[serde(rename = "id")] + pub id: String, + /// List of word mappings in the dictionary + #[serde(rename = "words")] + pub words: Vec, +} + +impl StemmingDictionary { + pub fn new(id: String, words: Vec) -> StemmingDictionary { + StemmingDictionary { + id, + words, + } + } +} + diff --git a/typesense_codegen/src/models/stemming_dictionary_words_inner.rs b/typesense_codegen/src/models/stemming_dictionary_words_inner.rs new file mode 100644 index 0000000..117e21e --- /dev/null +++ b/typesense_codegen/src/models/stemming_dictionary_words_inner.rs @@ -0,0 +1,32 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct StemmingDictionaryWordsInner { + /// The word form to be stemmed + #[serde(rename = "word")] + pub word: String, + /// The root form of the word + #[serde(rename = "root")] + pub root: String, +} + +impl StemmingDictionaryWordsInner { + pub fn new(word: String, root: String) -> StemmingDictionaryWordsInner { + StemmingDictionaryWordsInner { + word, + root, + } + } +} + diff --git a/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs b/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs new file mode 100644 index 0000000..9f61912 --- /dev/null +++ b/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs @@ -0,0 +1,27 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct StopwordsSetRetrieveSchema { + #[serde(rename = "stopwords")] + pub stopwords: Box, +} + +impl StopwordsSetRetrieveSchema { + pub fn new(stopwords: models::StopwordsSetSchema) -> StopwordsSetRetrieveSchema { + StopwordsSetRetrieveSchema { + stopwords: Box::new(stopwords), + } + } +} + diff --git a/typesense_codegen/src/models/stopwords_set_schema.rs b/typesense_codegen/src/models/stopwords_set_schema.rs new file mode 100644 index 0000000..60ae226 --- /dev/null +++ b/typesense_codegen/src/models/stopwords_set_schema.rs @@ -0,0 +1,33 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct StopwordsSetSchema { + #[serde(rename = "id")] + pub id: String, + #[serde(rename = "stopwords")] + pub stopwords: Vec, + #[serde(rename = "locale", skip_serializing_if = "Option::is_none")] + pub locale: Option, +} + +impl StopwordsSetSchema { + pub fn new(id: String, stopwords: Vec) -> StopwordsSetSchema { + StopwordsSetSchema { + id, + stopwords, + locale: None, + } + } +} + diff --git a/typesense_codegen/src/models/stopwords_set_upsert_schema.rs b/typesense_codegen/src/models/stopwords_set_upsert_schema.rs new file mode 100644 index 0000000..76ba788 --- /dev/null +++ b/typesense_codegen/src/models/stopwords_set_upsert_schema.rs @@ -0,0 +1,30 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct StopwordsSetUpsertSchema { + #[serde(rename = "stopwords")] + pub stopwords: Vec, + #[serde(rename = "locale", skip_serializing_if = "Option::is_none")] + pub locale: Option, +} + +impl StopwordsSetUpsertSchema { + pub fn new(stopwords: Vec) -> StopwordsSetUpsertSchema { + StopwordsSetUpsertSchema { + stopwords, + locale: None, + } + } +} + diff --git a/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs b/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs new file mode 100644 index 0000000..2212e37 --- /dev/null +++ b/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs @@ -0,0 +1,27 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct StopwordsSetsRetrieveAllSchema { + #[serde(rename = "stopwords")] + pub stopwords: Vec, +} + +impl StopwordsSetsRetrieveAllSchema { + pub fn new(stopwords: Vec) -> StopwordsSetsRetrieveAllSchema { + StopwordsSetsRetrieveAllSchema { + stopwords, + } + } +} + diff --git a/typesense_codegen/src/models/success_status.rs b/typesense_codegen/src/models/success_status.rs index b7d3724..490436c 100644 --- a/typesense_codegen/src/models/success_status.rs +++ b/typesense_codegen/src/models/success_status.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SuccessStatus { #[serde(rename = "success")] @@ -16,6 +19,9 @@ pub struct SuccessStatus { impl SuccessStatus { pub fn new(success: bool) -> SuccessStatus { - SuccessStatus { success } + SuccessStatus { + success, + } } } + diff --git a/typesense_codegen/src/models/synonym_item_schema.rs b/typesense_codegen/src/models/synonym_item_schema.rs new file mode 100644 index 0000000..50362c4 --- /dev/null +++ b/typesense_codegen/src/models/synonym_item_schema.rs @@ -0,0 +1,44 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct SynonymItemSchema { + /// Unique identifier for the synonym item + #[serde(rename = "id")] + pub id: String, + /// Array of words that should be considered as synonyms + #[serde(rename = "synonyms")] + pub synonyms: Vec, + /// For 1-way synonyms, indicates the root word that words in the synonyms parameter map to + #[serde(rename = "root", skip_serializing_if = "Option::is_none")] + pub root: Option, + /// Locale for the synonym, leave blank to use the standard tokenizer + #[serde(rename = "locale", skip_serializing_if = "Option::is_none")] + pub locale: Option, + /// By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is + #[serde(rename = "symbols_to_index", skip_serializing_if = "Option::is_none")] + pub symbols_to_index: Option>, +} + +impl SynonymItemSchema { + pub fn new(id: String, synonyms: Vec) -> SynonymItemSchema { + SynonymItemSchema { + id, + synonyms, + root: None, + locale: None, + symbols_to_index: None, + } + } +} + diff --git a/typesense_codegen/src/models/synonym_set_create_schema.rs b/typesense_codegen/src/models/synonym_set_create_schema.rs new file mode 100644 index 0000000..57cdfd3 --- /dev/null +++ b/typesense_codegen/src/models/synonym_set_create_schema.rs @@ -0,0 +1,28 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct SynonymSetCreateSchema { + /// Array of synonym items + #[serde(rename = "items")] + pub items: Vec, +} + +impl SynonymSetCreateSchema { + pub fn new(items: Vec) -> SynonymSetCreateSchema { + SynonymSetCreateSchema { + items, + } + } +} + diff --git a/typesense_codegen/src/models/synonym_set_delete_schema.rs b/typesense_codegen/src/models/synonym_set_delete_schema.rs new file mode 100644 index 0000000..7d5a559 --- /dev/null +++ b/typesense_codegen/src/models/synonym_set_delete_schema.rs @@ -0,0 +1,28 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct SynonymSetDeleteSchema { + /// Name of the deleted synonym set + #[serde(rename = "name")] + pub name: String, +} + +impl SynonymSetDeleteSchema { + pub fn new(name: String) -> SynonymSetDeleteSchema { + SynonymSetDeleteSchema { + name, + } + } +} + diff --git a/typesense_codegen/src/models/synonym_set_schema.rs b/typesense_codegen/src/models/synonym_set_schema.rs new file mode 100644 index 0000000..3e7cc55 --- /dev/null +++ b/typesense_codegen/src/models/synonym_set_schema.rs @@ -0,0 +1,32 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct SynonymSetSchema { + /// Array of synonym items + #[serde(rename = "items")] + pub items: Vec, + /// Name of the synonym set + #[serde(rename = "name")] + pub name: String, +} + +impl SynonymSetSchema { + pub fn new(items: Vec, name: String) -> SynonymSetSchema { + SynonymSetSchema { + items, + name, + } + } +} + diff --git a/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs b/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs new file mode 100644 index 0000000..74823bb --- /dev/null +++ b/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs @@ -0,0 +1,28 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct SynonymSetsRetrieveSchema { + /// Array of synonym sets + #[serde(rename = "synonym_sets")] + pub synonym_sets: Vec, +} + +impl SynonymSetsRetrieveSchema { + pub fn new(synonym_sets: Vec) -> SynonymSetsRetrieveSchema { + SynonymSetsRetrieveSchema { + synonym_sets, + } + } +} + diff --git a/typesense_codegen/src/models/toggle_slow_request_log_request.rs b/typesense_codegen/src/models/toggle_slow_request_log_request.rs new file mode 100644 index 0000000..7999551 --- /dev/null +++ b/typesense_codegen/src/models/toggle_slow_request_log_request.rs @@ -0,0 +1,27 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct ToggleSlowRequestLogRequest { + #[serde(rename = "log-slow-requests-time-ms")] + pub log_slow_requests_time_ms: i32, +} + +impl ToggleSlowRequestLogRequest { + pub fn new(log_slow_requests_time_ms: i32) -> ToggleSlowRequestLogRequest { + ToggleSlowRequestLogRequest { + log_slow_requests_time_ms, + } + } +} + diff --git a/typesense_codegen/src/models/update_documents_200_response.rs b/typesense_codegen/src/models/update_documents_200_response.rs index eff0990..9791d42 100644 --- a/typesense_codegen/src/models/update_documents_200_response.rs +++ b/typesense_codegen/src/models/update_documents_200_response.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct UpdateDocuments200Response { /// The number of documents that have been updated @@ -17,6 +20,9 @@ pub struct UpdateDocuments200Response { impl UpdateDocuments200Response { pub fn new(num_updated: i32) -> UpdateDocuments200Response { - UpdateDocuments200Response { num_updated } + UpdateDocuments200Response { + num_updated, + } } } + diff --git a/typesense_codegen/src/models/update_documents_update_documents_parameters_parameter.rs b/typesense_codegen/src/models/update_documents_parameters.rs similarity index 51% rename from typesense_codegen/src/models/update_documents_update_documents_parameters_parameter.rs rename to typesense_codegen/src/models/update_documents_parameters.rs index aacf476..6e48b68 100644 --- a/typesense_codegen/src/models/update_documents_update_documents_parameters_parameter.rs +++ b/typesense_codegen/src/models/update_documents_parameters.rs @@ -3,19 +3,25 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 30.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct UpdateDocumentsUpdateDocumentsParametersParameter { +pub struct UpdateDocumentsParameters { #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] pub filter_by: Option, } -impl UpdateDocumentsUpdateDocumentsParametersParameter { - pub fn new() -> UpdateDocumentsUpdateDocumentsParametersParameter { - UpdateDocumentsUpdateDocumentsParametersParameter { filter_by: None } +impl UpdateDocumentsParameters { + pub fn new() -> UpdateDocumentsParameters { + UpdateDocumentsParameters { + filter_by: None, + } } } + diff --git a/typesense_codegen/src/models/voice_query_model_collection_config.rs b/typesense_codegen/src/models/voice_query_model_collection_config.rs new file mode 100644 index 0000000..ca623f5 --- /dev/null +++ b/typesense_codegen/src/models/voice_query_model_collection_config.rs @@ -0,0 +1,29 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +/// VoiceQueryModelCollectionConfig : Configuration for the voice query model +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct VoiceQueryModelCollectionConfig { + #[serde(rename = "model_name", skip_serializing_if = "Option::is_none")] + pub model_name: Option, +} + +impl VoiceQueryModelCollectionConfig { + /// Configuration for the voice query model + pub fn new() -> VoiceQueryModelCollectionConfig { + VoiceQueryModelCollectionConfig { + model_name: None, + } + } +} + diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 0fd68d2..0552300 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -12,6 +12,7 @@ const SPEC_URL: &str = // Input spec file, expected in the project root. const INPUT_SPEC_FILE: &str = "openapi.yml"; const OUTPUT_PREPROCESSED_FILE: &str = "./preprocessed_openapi.yml"; +const CUSTOM_TEMPLATES_DIR: &str = "custom-templates"; // Directory containing our custom templates // Output directory for the generated code. const OUTPUT_DIR: &str = "typesense_codegen"; @@ -117,14 +118,14 @@ fn task_codegen() -> Result<()> { .arg("rust") .arg("-o") .arg(format!("/local/{}", OUTPUT_DIR)) // Output path inside the container + .arg("-t") // specify the template directory + .arg(format!("/local/{}", CUSTOM_TEMPLATES_DIR)) .arg("--additional-properties") .arg("library=reqwest") .arg("--additional-properties") .arg("supportMiddleware=true") .arg("--additional-properties") .arg("useSingleRequestParameter=true") - // .arg("--additional-properties") - // .arg("useBonBuilder=true") .status() .context("Failed to execute Docker command. Is Docker installed and running?")?; diff --git a/xtask/src/preprocess_openapi.rs b/xtask/src/preprocess_openapi.rs index 4189481..c0e9e81 100644 --- a/xtask/src/preprocess_openapi.rs +++ b/xtask/src/preprocess_openapi.rs @@ -33,21 +33,28 @@ pub fn preprocess_openapi_file( "/collections/{collectionName}/documents/export", "get", "exportDocumentsParameters", - Some("ExportDocumentsParameters"), // Copy schema to components + Some("ExportDocumentsParameters"), )?; unwrap_parameters_by_path( doc_root, "/collections/{collectionName}/documents", "patch", "updateDocumentsParameters", - Some("UpdateDocumentsParameters"), // Copy schema to components + Some("UpdateDocumentsParameters"), )?; unwrap_parameters_by_path( doc_root, "/collections/{collectionName}/documents", "delete", "deleteDocumentsParameters", - Some("DeleteDocumentsParameters"), // Copy schema to components + Some("DeleteDocumentsParameters"), + )?; + unwrap_parameters_by_path( + doc_root, + "/collections", + "get", + "getCollectionsParameters", + Some("GetCollectionsParameters"), )?; println!("Preprocessing complete."); From 751b471c880f33dff1f749a8d42f06f865d25dae Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Sun, 31 Aug 2025 14:12:10 +0700 Subject: [PATCH 02/41] feat(openapi-template): bon builder derive, generic model and API method --- custom-templates/model.mustache | 18 ++++++++++++++---- custom-templates/reqwest/api.mustache | 8 ++++---- openapi.yml | 2 ++ preprocessed_openapi.yml | 2 ++ typesense_codegen/src/apis/documents_api.rs | 2 +- .../src/models/analytics_event.rs | 4 ++-- .../models/analytics_event_create_response.rs | 4 ++-- .../src/models/analytics_event_data.rs | 4 ++-- .../src/models/analytics_events_response.rs | 4 ++-- .../analytics_events_response_events_inner.rs | 4 ++-- typesense_codegen/src/models/analytics_rule.rs | 4 ++-- .../src/models/analytics_rule_create.rs | 4 ++-- .../src/models/analytics_rule_create_params.rs | 4 ++-- .../src/models/analytics_rule_update.rs | 4 ++-- .../src/models/analytics_status.rs | 4 ++-- typesense_codegen/src/models/api_key.rs | 4 ++-- .../src/models/api_key_delete_response.rs | 4 ++-- typesense_codegen/src/models/api_key_schema.rs | 4 ++-- .../src/models/api_keys_response.rs | 4 ++-- typesense_codegen/src/models/api_response.rs | 4 ++-- .../src/models/api_stats_response.rs | 4 ++-- .../src/models/collection_alias.rs | 4 ++-- .../src/models/collection_alias_schema.rs | 4 ++-- .../src/models/collection_aliases_response.rs | 4 ++-- .../src/models/collection_response.rs | 4 ++-- .../src/models/collection_schema.rs | 4 ++-- .../src/models/collection_update_schema.rs | 4 ++-- .../models/conversation_model_create_schema.rs | 4 ++-- .../src/models/conversation_model_schema.rs | 4 ++-- .../models/conversation_model_update_schema.rs | 4 ++-- ...analytics_rule_200_response_one_of_inner.rs | 4 ++-- ...cs_rule_200_response_one_of_inner_any_of.rs | 4 ++-- .../src/models/debug_200_response.rs | 4 ++-- .../models/delete_documents_200_response.rs | 4 ++-- .../src/models/delete_documents_parameters.rs | 4 ++-- .../delete_stopwords_set_200_response.rs | 4 ++-- .../src/models/export_documents_parameters.rs | 4 ++-- typesense_codegen/src/models/facet_counts.rs | 4 ++-- .../src/models/facet_counts_counts_inner.rs | 4 ++-- .../src/models/facet_counts_stats.rs | 4 ++-- typesense_codegen/src/models/field.rs | 4 ++-- typesense_codegen/src/models/field_embed.rs | 4 ++-- .../src/models/field_embed_model_config.rs | 4 ++-- .../src/models/get_collections_parameters.rs | 4 ++-- typesense_codegen/src/models/health_status.rs | 4 ++-- .../src/models/import_documents_parameters.rs | 4 ++-- .../list_stemming_dictionaries_200_response.rs | 4 ++-- .../multi_search_collection_parameters.rs | 4 ++-- .../src/models/multi_search_parameters.rs | 4 ++-- .../src/models/multi_search_result.rs | 4 ++-- .../src/models/multi_search_result_item.rs | 6 +++--- .../models/multi_search_searches_parameter.rs | 4 ++-- .../src/models/nl_search_model_base.rs | 4 ++-- .../models/nl_search_model_create_schema.rs | 4 ++-- .../models/nl_search_model_delete_schema.rs | 4 ++-- .../src/models/nl_search_model_schema.rs | 4 ++-- .../src/models/preset_delete_schema.rs | 4 ++-- typesense_codegen/src/models/preset_schema.rs | 4 ++-- .../src/models/preset_upsert_schema.rs | 4 ++-- .../src/models/presets_retrieve_schema.rs | 4 ++-- .../src/models/schema_change_status.rs | 4 ++-- .../src/models/search_grouped_hit.rs | 4 ++-- .../src/models/search_highlight.rs | 4 ++-- .../src/models/search_override.rs | 4 ++-- .../models/search_override_delete_response.rs | 4 ++-- .../src/models/search_override_exclude.rs | 4 ++-- .../src/models/search_override_include.rs | 4 ++-- .../src/models/search_override_rule.rs | 4 ++-- .../src/models/search_override_schema.rs | 4 ++-- .../src/models/search_overrides_response.rs | 4 ++-- .../src/models/search_parameters.rs | 4 ++-- .../src/models/search_request_params.rs | 4 ++-- .../search_request_params_voice_query.rs | 4 ++-- typesense_codegen/src/models/search_result.rs | 10 +++++----- .../src/models/search_result_conversation.rs | 4 ++-- .../src/models/search_result_hit.rs | 10 +++++----- .../search_result_hit_hybrid_search_info.rs | 4 ++-- .../search_result_hit_text_match_info.rs | 4 ++-- typesense_codegen/src/models/search_synonym.rs | 4 ++-- .../models/search_synonym_delete_response.rs | 4 ++-- .../src/models/search_synonym_schema.rs | 4 ++-- .../src/models/search_synonyms_response.rs | 4 ++-- .../src/models/stemming_dictionary.rs | 4 ++-- .../models/stemming_dictionary_words_inner.rs | 4 ++-- .../models/stopwords_set_retrieve_schema.rs | 4 ++-- .../src/models/stopwords_set_schema.rs | 4 ++-- .../src/models/stopwords_set_upsert_schema.rs | 4 ++-- .../stopwords_sets_retrieve_all_schema.rs | 4 ++-- typesense_codegen/src/models/success_status.rs | 4 ++-- .../src/models/synonym_item_schema.rs | 4 ++-- .../src/models/synonym_set_create_schema.rs | 4 ++-- .../src/models/synonym_set_delete_schema.rs | 4 ++-- .../src/models/synonym_set_schema.rs | 4 ++-- .../src/models/synonym_sets_retrieve_schema.rs | 4 ++-- .../models/toggle_slow_request_log_request.rs | 4 ++-- .../models/update_documents_200_response.rs | 4 ++-- .../src/models/update_documents_parameters.rs | 4 ++-- .../voice_query_model_collection_config.rs | 4 ++-- 98 files changed, 216 insertions(+), 202 deletions(-) diff --git a/custom-templates/model.mustache b/custom-templates/model.mustache index a4970ab..bad954a 100644 --- a/custom-templates/model.mustache +++ b/custom-templates/model.mustache @@ -122,8 +122,8 @@ impl Default for {{classname}} { {{^isEnum}} {{^discriminator}} {{#vendorExtensions.x-rust-has-byte-array}}#[serde_as] -{{/vendorExtensions.x-rust-has-byte-array}}{{#oneOf.isEmpty}}#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct {{{classname}}} { +{{/vendorExtensions.x-rust-has-byte-array}}{{#oneOf.isEmpty}}#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +pub struct {{{classname}}}{{{vendorExtensions.x-rust-generic-parameter}}} { {{#vars}} {{#description}} /// {{{.}}} @@ -132,6 +132,10 @@ pub struct {{{classname}}} { {{#vendorExtensions.isMandatory}}#[serde_as(as = "serde_with::base64::Base64")]{{/vendorExtensions.isMandatory}}{{^vendorExtensions.isMandatory}}#[serde_as(as = "{{^serdeAsDoubleOption}}Option{{/serdeAsDoubleOption}}{{#serdeAsDoubleOption}}super::DoubleOption{{/serdeAsDoubleOption}}")]{{/vendorExtensions.isMandatory}} {{/isByteArray}} #[serde(rename = "{{{baseName}}}"{{^required}}{{#isNullable}}, default{{^isByteArray}}, with = "::serde_with::rust::double_option"{{/isByteArray}}{{/isNullable}}{{/required}}{{^required}}, skip_serializing_if = "Option::is_none"{{/required}}{{#required}}{{#isNullable}}, deserialize_with = "Option::deserialize"{{/isNullable}}{{/required}})] + {{#vendorExtensions.x-rust-type}} + pub {{{name}}}: {{{.}}}, + {{/vendorExtensions.x-rust-type}} + {{^vendorExtensions.x-rust-type}} pub {{{name}}}: {{! ### Option Start }}{{#isNullable}}Option<{{/isNullable}}{{^required}}Option<{{/required}}{{! @@ -147,10 +151,11 @@ pub struct {{{classname}}} { }}{{/isEnum}}{{! ### Option End (and trailing comma) }}{{#isNullable}}>{{/isNullable}}{{^required}}>{{/required}}, + {{/vendorExtensions.x-rust-type}} {{/vars}} } -impl {{{classname}}} { +impl{{{vendorExtensions.x-rust-generic-parameter}}} {{{classname}}}{{{vendorExtensions.x-rust-generic-parameter}}} { {{#description}} /// {{{.}}} {{/description}} @@ -164,10 +169,15 @@ impl {{{classname}}} { ### Option End }}{{#isNullable}}>{{/isNullable}}{{! ### Comma for next arguement - }}{{^-last}}, {{/-last}}{{/requiredVars}}) -> {{{classname}}} { + }}{{^-last}}, {{/-last}}{{/requiredVars}}) -> {{{classname}}}{{{vendorExtensions.x-rust-generic-parameter}}}{ {{{classname}}} { {{#vars}} + {{#vendorExtensions.x-rust-type}} + {{{name}}}: None, + {{/vendorExtensions.x-rust-type}} + {{^vendorExtensions.x-rust-type}} {{{name}}}{{^required}}: None{{/required}}{{#required}}{{#isModel}}{{^avoidBoxedModels}}: {{^isNullable}}Box::new({{{name}}}){{/isNullable}}{{#isNullable}}if let Some(x) = {{{name}}} {Some(Box::new(x))} else {None}{{/isNullable}}{{/avoidBoxedModels}}{{/isModel}}{{/required}}, + {{/vendorExtensions.x-rust-type}} {{/vars}} } } diff --git a/custom-templates/reqwest/api.mustache b/custom-templates/reqwest/api.mustache index e28ca3e..b20b669 100644 --- a/custom-templates/reqwest/api.mustache +++ b/custom-templates/reqwest/api.mustache @@ -92,7 +92,7 @@ pub enum {{{operationIdCamelCase}}}Error { /// {{{.}}} {{/notes}} {{#vendorExtensions.x-group-parameters}} -pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}(configuration: &configuration::Configuration{{#allParams}}{{#-first}}, {{! +pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}{{{vendorExtensions.x-rust-operation-generic-parameter}}}(configuration: &configuration::Configuration{{#allParams}}{{#-first}}, {{! ### Params }}params: {{{operationIdCamelCase}}}Params{{/-first}}{{/allParams}}{{! ### Function return type @@ -104,12 +104,12 @@ pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}(configuration: ### Multi response support }}{{#supportMultipleResponses}}ResponseContent<{{{operationIdCamelCase}}}Success>{{/supportMultipleResponses}}{{! ### Regular return type -}}{{^supportMultipleResponses}}{{^returnType}}(){{/returnType}}{{{returnType}}}{{/supportMultipleResponses}}{{/isResponseFile}}{{! +}}{{^supportMultipleResponses}}{{^returnType}}(){{/returnType}}{{{returnType}}}{{{vendorExtensions.x-rust-return-type-generic-parameter}}}{{/supportMultipleResponses}}{{/isResponseFile}}{{! ### Error Type }}, Error<{{{operationIdCamelCase}}}Error>> { {{/vendorExtensions.x-group-parameters}} {{^vendorExtensions.x-group-parameters}} -pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}(configuration: &configuration::Configuration, {{#allParams}}{{{paramName}}}: {{! +pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}{{{vendorExtensions.x-rust-operation-generic-parameter}}}(configuration: &configuration::Configuration, {{#allParams}}{{{paramName}}}: {{! ### Option Start }}{{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{! ### &str and Vec<&str> @@ -131,7 +131,7 @@ pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}(configuration: ### Multi response support }}{{#supportMultipleResponses}}ResponseContent<{{{operationIdCamelCase}}}Success>{{/supportMultipleResponses}}{{! ### Regular return type -}}{{^supportMultipleResponses}}{{^returnType}}(){{/returnType}}{{{returnType}}}{{/supportMultipleResponses}}{{/isResponseFile}}{{! +}}{{^supportMultipleResponses}}{{^returnType}}(){{/returnType}}{{{returnType}}}{{{vendorExtensions.x-rust-return-type-generic-parameter}}}{{/supportMultipleResponses}}{{/isResponseFile}}{{! ### Error Type }}, Error<{{{operationIdCamelCase}}}Error>> { {{#allParams.0}} diff --git a/openapi.yml b/openapi.yml index 9a878ed..e8b7b73 100644 --- a/openapi.yml +++ b/openapi.yml @@ -429,6 +429,8 @@ paths: summary: Search for documents in a collection description: Search for documents in a collection that match the search criteria. operationId: searchCollection + x-rust-operation-generic-parameter: " serde::Deserialize<'de> + Serialize>" + x-rust-return-type-generic-parameter: "" parameters: - name: collectionName in: path diff --git a/preprocessed_openapi.yml b/preprocessed_openapi.yml index c20d1c5..b839943 100644 --- a/preprocessed_openapi.yml +++ b/preprocessed_openapi.yml @@ -405,6 +405,8 @@ paths: summary: Search for documents in a collection description: Search for documents in a collection that match the search criteria. operationId: searchCollection + x-rust-operation-generic-parameter: ' serde::Deserialize<''de> + Serialize>' + x-rust-return-type-generic-parameter: parameters: - name: collectionName in: path diff --git a/typesense_codegen/src/apis/documents_api.rs b/typesense_codegen/src/apis/documents_api.rs index 9400aa3..7985003 100644 --- a/typesense_codegen/src/apis/documents_api.rs +++ b/typesense_codegen/src/apis/documents_api.rs @@ -1072,7 +1072,7 @@ pub async fn multi_search(configuration: &configuration::Configuration, params: } /// Search for documents in a collection that match the search criteria. -pub async fn search_collection(configuration: &configuration::Configuration, params: SearchCollectionParams) -> Result> { +pub async fn search_collection serde::Deserialize<'de> + Serialize>(configuration: &configuration::Configuration, params: SearchCollectionParams) -> Result, Error> { let uri_str = format!("{}/collections/{collectionName}/documents/search", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); diff --git a/typesense_codegen/src/models/analytics_event.rs b/typesense_codegen/src/models/analytics_event.rs index df09edc..77d28e8 100644 --- a/typesense_codegen/src/models/analytics_event.rs +++ b/typesense_codegen/src/models/analytics_event.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct AnalyticsEvent { /// Name of the analytics rule this event corresponds to #[serde(rename = "name")] @@ -24,7 +24,7 @@ pub struct AnalyticsEvent { } impl AnalyticsEvent { - pub fn new(name: String, event_type: String, data: models::AnalyticsEventData) -> AnalyticsEvent { + pub fn new(name: String, event_type: String, data: models::AnalyticsEventData) -> AnalyticsEvent{ AnalyticsEvent { name, event_type, diff --git a/typesense_codegen/src/models/analytics_event_create_response.rs b/typesense_codegen/src/models/analytics_event_create_response.rs index 6e5e054..21e97c1 100644 --- a/typesense_codegen/src/models/analytics_event_create_response.rs +++ b/typesense_codegen/src/models/analytics_event_create_response.rs @@ -11,14 +11,14 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct AnalyticsEventCreateResponse { #[serde(rename = "ok")] pub ok: bool, } impl AnalyticsEventCreateResponse { - pub fn new(ok: bool) -> AnalyticsEventCreateResponse { + pub fn new(ok: bool) -> AnalyticsEventCreateResponse{ AnalyticsEventCreateResponse { ok, } diff --git a/typesense_codegen/src/models/analytics_event_data.rs b/typesense_codegen/src/models/analytics_event_data.rs index d94fa7a..fd2a1fa 100644 --- a/typesense_codegen/src/models/analytics_event_data.rs +++ b/typesense_codegen/src/models/analytics_event_data.rs @@ -12,7 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; /// AnalyticsEventData : Event payload -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct AnalyticsEventData { #[serde(rename = "user_id", skip_serializing_if = "Option::is_none")] pub user_id: Option, @@ -28,7 +28,7 @@ pub struct AnalyticsEventData { impl AnalyticsEventData { /// Event payload - pub fn new() -> AnalyticsEventData { + pub fn new() -> AnalyticsEventData{ AnalyticsEventData { user_id: None, doc_id: None, diff --git a/typesense_codegen/src/models/analytics_events_response.rs b/typesense_codegen/src/models/analytics_events_response.rs index 43271dc..3f98363 100644 --- a/typesense_codegen/src/models/analytics_events_response.rs +++ b/typesense_codegen/src/models/analytics_events_response.rs @@ -11,14 +11,14 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct AnalyticsEventsResponse { #[serde(rename = "events")] pub events: Vec, } impl AnalyticsEventsResponse { - pub fn new(events: Vec) -> AnalyticsEventsResponse { + pub fn new(events: Vec) -> AnalyticsEventsResponse{ AnalyticsEventsResponse { events, } diff --git a/typesense_codegen/src/models/analytics_events_response_events_inner.rs b/typesense_codegen/src/models/analytics_events_response_events_inner.rs index 3f5b2d1..82c4e77 100644 --- a/typesense_codegen/src/models/analytics_events_response_events_inner.rs +++ b/typesense_codegen/src/models/analytics_events_response_events_inner.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct AnalyticsEventsResponseEventsInner { #[serde(rename = "name", skip_serializing_if = "Option::is_none")] pub name: Option, @@ -32,7 +32,7 @@ pub struct AnalyticsEventsResponseEventsInner { } impl AnalyticsEventsResponseEventsInner { - pub fn new() -> AnalyticsEventsResponseEventsInner { + pub fn new() -> AnalyticsEventsResponseEventsInner{ AnalyticsEventsResponseEventsInner { name: None, event_type: None, diff --git a/typesense_codegen/src/models/analytics_rule.rs b/typesense_codegen/src/models/analytics_rule.rs index 6044d9b..a02a000 100644 --- a/typesense_codegen/src/models/analytics_rule.rs +++ b/typesense_codegen/src/models/analytics_rule.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct AnalyticsRule { #[serde(rename = "name")] pub name: String, @@ -28,7 +28,7 @@ pub struct AnalyticsRule { } impl AnalyticsRule { - pub fn new(name: String, r#type: Type, collection: String, event_type: String) -> AnalyticsRule { + pub fn new(name: String, r#type: Type, collection: String, event_type: String) -> AnalyticsRule{ AnalyticsRule { name, r#type, diff --git a/typesense_codegen/src/models/analytics_rule_create.rs b/typesense_codegen/src/models/analytics_rule_create.rs index 4685277..47b31ca 100644 --- a/typesense_codegen/src/models/analytics_rule_create.rs +++ b/typesense_codegen/src/models/analytics_rule_create.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct AnalyticsRuleCreate { #[serde(rename = "name")] pub name: String, @@ -28,7 +28,7 @@ pub struct AnalyticsRuleCreate { } impl AnalyticsRuleCreate { - pub fn new(name: String, r#type: Type, collection: String, event_type: String) -> AnalyticsRuleCreate { + pub fn new(name: String, r#type: Type, collection: String, event_type: String) -> AnalyticsRuleCreate{ AnalyticsRuleCreate { name, r#type, diff --git a/typesense_codegen/src/models/analytics_rule_create_params.rs b/typesense_codegen/src/models/analytics_rule_create_params.rs index e62debd..17e5a8e 100644 --- a/typesense_codegen/src/models/analytics_rule_create_params.rs +++ b/typesense_codegen/src/models/analytics_rule_create_params.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct AnalyticsRuleCreateParams { #[serde(rename = "destination_collection", skip_serializing_if = "Option::is_none")] pub destination_collection: Option, @@ -30,7 +30,7 @@ pub struct AnalyticsRuleCreateParams { } impl AnalyticsRuleCreateParams { - pub fn new() -> AnalyticsRuleCreateParams { + pub fn new() -> AnalyticsRuleCreateParams{ AnalyticsRuleCreateParams { destination_collection: None, limit: None, diff --git a/typesense_codegen/src/models/analytics_rule_update.rs b/typesense_codegen/src/models/analytics_rule_update.rs index 78d0fad..b5f0edc 100644 --- a/typesense_codegen/src/models/analytics_rule_update.rs +++ b/typesense_codegen/src/models/analytics_rule_update.rs @@ -12,7 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; /// AnalyticsRuleUpdate : Fields allowed to update on an analytics rule -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct AnalyticsRuleUpdate { #[serde(rename = "name", skip_serializing_if = "Option::is_none")] pub name: Option, @@ -24,7 +24,7 @@ pub struct AnalyticsRuleUpdate { impl AnalyticsRuleUpdate { /// Fields allowed to update on an analytics rule - pub fn new() -> AnalyticsRuleUpdate { + pub fn new() -> AnalyticsRuleUpdate{ AnalyticsRuleUpdate { name: None, rule_tag: None, diff --git a/typesense_codegen/src/models/analytics_status.rs b/typesense_codegen/src/models/analytics_status.rs index 8cc6d1a..6522e2b 100644 --- a/typesense_codegen/src/models/analytics_status.rs +++ b/typesense_codegen/src/models/analytics_status.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct AnalyticsStatus { #[serde(rename = "popular_prefix_queries", skip_serializing_if = "Option::is_none")] pub popular_prefix_queries: Option, @@ -30,7 +30,7 @@ pub struct AnalyticsStatus { } impl AnalyticsStatus { - pub fn new() -> AnalyticsStatus { + pub fn new() -> AnalyticsStatus{ AnalyticsStatus { popular_prefix_queries: None, nohits_prefix_queries: None, diff --git a/typesense_codegen/src/models/api_key.rs b/typesense_codegen/src/models/api_key.rs index 24fc861..1899c71 100644 --- a/typesense_codegen/src/models/api_key.rs +++ b/typesense_codegen/src/models/api_key.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct ApiKey { #[serde(rename = "value", skip_serializing_if = "Option::is_none")] pub value: Option, @@ -30,7 +30,7 @@ pub struct ApiKey { } impl ApiKey { - pub fn new(description: String, actions: Vec, collections: Vec) -> ApiKey { + pub fn new(description: String, actions: Vec, collections: Vec) -> ApiKey{ ApiKey { value: None, description, diff --git a/typesense_codegen/src/models/api_key_delete_response.rs b/typesense_codegen/src/models/api_key_delete_response.rs index e59d0b5..b64efd9 100644 --- a/typesense_codegen/src/models/api_key_delete_response.rs +++ b/typesense_codegen/src/models/api_key_delete_response.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct ApiKeyDeleteResponse { /// The id of the API key that was deleted #[serde(rename = "id")] @@ -19,7 +19,7 @@ pub struct ApiKeyDeleteResponse { } impl ApiKeyDeleteResponse { - pub fn new(id: i64) -> ApiKeyDeleteResponse { + pub fn new(id: i64) -> ApiKeyDeleteResponse{ ApiKeyDeleteResponse { id, } diff --git a/typesense_codegen/src/models/api_key_schema.rs b/typesense_codegen/src/models/api_key_schema.rs index a25dc81..6c9b2ca 100644 --- a/typesense_codegen/src/models/api_key_schema.rs +++ b/typesense_codegen/src/models/api_key_schema.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct ApiKeySchema { #[serde(rename = "value", skip_serializing_if = "Option::is_none")] pub value: Option, @@ -26,7 +26,7 @@ pub struct ApiKeySchema { } impl ApiKeySchema { - pub fn new(description: String, actions: Vec, collections: Vec) -> ApiKeySchema { + pub fn new(description: String, actions: Vec, collections: Vec) -> ApiKeySchema{ ApiKeySchema { value: None, description, diff --git a/typesense_codegen/src/models/api_keys_response.rs b/typesense_codegen/src/models/api_keys_response.rs index f416c2c..a59d99c 100644 --- a/typesense_codegen/src/models/api_keys_response.rs +++ b/typesense_codegen/src/models/api_keys_response.rs @@ -11,14 +11,14 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct ApiKeysResponse { #[serde(rename = "keys")] pub keys: Vec, } impl ApiKeysResponse { - pub fn new(keys: Vec) -> ApiKeysResponse { + pub fn new(keys: Vec) -> ApiKeysResponse{ ApiKeysResponse { keys, } diff --git a/typesense_codegen/src/models/api_response.rs b/typesense_codegen/src/models/api_response.rs index 3fc9d03..e1d2d89 100644 --- a/typesense_codegen/src/models/api_response.rs +++ b/typesense_codegen/src/models/api_response.rs @@ -11,14 +11,14 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct ApiResponse { #[serde(rename = "message")] pub message: String, } impl ApiResponse { - pub fn new(message: String) -> ApiResponse { + pub fn new(message: String) -> ApiResponse{ ApiResponse { message, } diff --git a/typesense_codegen/src/models/api_stats_response.rs b/typesense_codegen/src/models/api_stats_response.rs index 9766f7f..f22d203 100644 --- a/typesense_codegen/src/models/api_stats_response.rs +++ b/typesense_codegen/src/models/api_stats_response.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct ApiStatsResponse { #[serde(rename = "delete_latency_ms", skip_serializing_if = "Option::is_none")] pub delete_latency_ms: Option, @@ -42,7 +42,7 @@ pub struct ApiStatsResponse { } impl ApiStatsResponse { - pub fn new() -> ApiStatsResponse { + pub fn new() -> ApiStatsResponse{ ApiStatsResponse { delete_latency_ms: None, delete_requests_per_second: None, diff --git a/typesense_codegen/src/models/collection_alias.rs b/typesense_codegen/src/models/collection_alias.rs index 2b3afe8..0e33f6c 100644 --- a/typesense_codegen/src/models/collection_alias.rs +++ b/typesense_codegen/src/models/collection_alias.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct CollectionAlias { /// Name of the collection alias #[serde(rename = "name")] @@ -22,7 +22,7 @@ pub struct CollectionAlias { } impl CollectionAlias { - pub fn new(name: String, collection_name: String) -> CollectionAlias { + pub fn new(name: String, collection_name: String) -> CollectionAlias{ CollectionAlias { name, collection_name, diff --git a/typesense_codegen/src/models/collection_alias_schema.rs b/typesense_codegen/src/models/collection_alias_schema.rs index bcc4029..cbebb2c 100644 --- a/typesense_codegen/src/models/collection_alias_schema.rs +++ b/typesense_codegen/src/models/collection_alias_schema.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct CollectionAliasSchema { /// Name of the collection you wish to map the alias to #[serde(rename = "collection_name")] @@ -19,7 +19,7 @@ pub struct CollectionAliasSchema { } impl CollectionAliasSchema { - pub fn new(collection_name: String) -> CollectionAliasSchema { + pub fn new(collection_name: String) -> CollectionAliasSchema{ CollectionAliasSchema { collection_name, } diff --git a/typesense_codegen/src/models/collection_aliases_response.rs b/typesense_codegen/src/models/collection_aliases_response.rs index 8b3fd5c..87a5838 100644 --- a/typesense_codegen/src/models/collection_aliases_response.rs +++ b/typesense_codegen/src/models/collection_aliases_response.rs @@ -11,14 +11,14 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct CollectionAliasesResponse { #[serde(rename = "aliases")] pub aliases: Vec, } impl CollectionAliasesResponse { - pub fn new(aliases: Vec) -> CollectionAliasesResponse { + pub fn new(aliases: Vec) -> CollectionAliasesResponse{ CollectionAliasesResponse { aliases, } diff --git a/typesense_codegen/src/models/collection_response.rs b/typesense_codegen/src/models/collection_response.rs index dc31000..b63e0f6 100644 --- a/typesense_codegen/src/models/collection_response.rs +++ b/typesense_codegen/src/models/collection_response.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct CollectionResponse { /// Name of the collection #[serde(rename = "name")] @@ -48,7 +48,7 @@ pub struct CollectionResponse { } impl CollectionResponse { - pub fn new(name: String, fields: Vec, num_documents: i64, created_at: i64) -> CollectionResponse { + pub fn new(name: String, fields: Vec, num_documents: i64, created_at: i64) -> CollectionResponse{ CollectionResponse { name, fields, diff --git a/typesense_codegen/src/models/collection_schema.rs b/typesense_codegen/src/models/collection_schema.rs index eef9df6..c5c8706 100644 --- a/typesense_codegen/src/models/collection_schema.rs +++ b/typesense_codegen/src/models/collection_schema.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct CollectionSchema { /// Name of the collection #[serde(rename = "name")] @@ -42,7 +42,7 @@ pub struct CollectionSchema { } impl CollectionSchema { - pub fn new(name: String, fields: Vec) -> CollectionSchema { + pub fn new(name: String, fields: Vec) -> CollectionSchema{ CollectionSchema { name, fields, diff --git a/typesense_codegen/src/models/collection_update_schema.rs b/typesense_codegen/src/models/collection_update_schema.rs index 494d3b9..8ff200f 100644 --- a/typesense_codegen/src/models/collection_update_schema.rs +++ b/typesense_codegen/src/models/collection_update_schema.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct CollectionUpdateSchema { /// A list of fields for querying, filtering and faceting #[serde(rename = "fields")] @@ -25,7 +25,7 @@ pub struct CollectionUpdateSchema { } impl CollectionUpdateSchema { - pub fn new(fields: Vec) -> CollectionUpdateSchema { + pub fn new(fields: Vec) -> CollectionUpdateSchema{ CollectionUpdateSchema { fields, synonym_sets: None, diff --git a/typesense_codegen/src/models/conversation_model_create_schema.rs b/typesense_codegen/src/models/conversation_model_create_schema.rs index 2a9eb42..9beecf2 100644 --- a/typesense_codegen/src/models/conversation_model_create_schema.rs +++ b/typesense_codegen/src/models/conversation_model_create_schema.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct ConversationModelCreateSchema { /// An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. #[serde(rename = "id", skip_serializing_if = "Option::is_none")] @@ -43,7 +43,7 @@ pub struct ConversationModelCreateSchema { } impl ConversationModelCreateSchema { - pub fn new(model_name: String, history_collection: String, max_bytes: i32) -> ConversationModelCreateSchema { + pub fn new(model_name: String, history_collection: String, max_bytes: i32) -> ConversationModelCreateSchema{ ConversationModelCreateSchema { id: None, model_name, diff --git a/typesense_codegen/src/models/conversation_model_schema.rs b/typesense_codegen/src/models/conversation_model_schema.rs index d5a4a0d..1afda04 100644 --- a/typesense_codegen/src/models/conversation_model_schema.rs +++ b/typesense_codegen/src/models/conversation_model_schema.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct ConversationModelSchema { /// An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. #[serde(rename = "id")] @@ -43,7 +43,7 @@ pub struct ConversationModelSchema { } impl ConversationModelSchema { - pub fn new(id: String, model_name: String, history_collection: String, max_bytes: i32) -> ConversationModelSchema { + pub fn new(id: String, model_name: String, history_collection: String, max_bytes: i32) -> ConversationModelSchema{ ConversationModelSchema { id, model_name, diff --git a/typesense_codegen/src/models/conversation_model_update_schema.rs b/typesense_codegen/src/models/conversation_model_update_schema.rs index 3dd5e8b..d1b9902 100644 --- a/typesense_codegen/src/models/conversation_model_update_schema.rs +++ b/typesense_codegen/src/models/conversation_model_update_schema.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct ConversationModelUpdateSchema { /// An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. #[serde(rename = "id", skip_serializing_if = "Option::is_none")] @@ -43,7 +43,7 @@ pub struct ConversationModelUpdateSchema { } impl ConversationModelUpdateSchema { - pub fn new() -> ConversationModelUpdateSchema { + pub fn new() -> ConversationModelUpdateSchema{ ConversationModelUpdateSchema { id: None, model_name: None, diff --git a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs index 03661e2..7c0dedf 100644 --- a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs +++ b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct CreateAnalyticsRule200ResponseOneOfInner { #[serde(rename = "name")] pub name: String, @@ -30,7 +30,7 @@ pub struct CreateAnalyticsRule200ResponseOneOfInner { } impl CreateAnalyticsRule200ResponseOneOfInner { - pub fn new(name: String, r#type: Type, collection: String, event_type: String) -> CreateAnalyticsRule200ResponseOneOfInner { + pub fn new(name: String, r#type: Type, collection: String, event_type: String) -> CreateAnalyticsRule200ResponseOneOfInner{ CreateAnalyticsRule200ResponseOneOfInner { name, r#type, diff --git a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs index 8e3d7a0..5b86508 100644 --- a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs +++ b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs @@ -11,14 +11,14 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct CreateAnalyticsRule200ResponseOneOfInnerAnyOf { #[serde(rename = "error", skip_serializing_if = "Option::is_none")] pub error: Option, } impl CreateAnalyticsRule200ResponseOneOfInnerAnyOf { - pub fn new() -> CreateAnalyticsRule200ResponseOneOfInnerAnyOf { + pub fn new() -> CreateAnalyticsRule200ResponseOneOfInnerAnyOf{ CreateAnalyticsRule200ResponseOneOfInnerAnyOf { error: None, } diff --git a/typesense_codegen/src/models/debug_200_response.rs b/typesense_codegen/src/models/debug_200_response.rs index c9ba357..a2377e0 100644 --- a/typesense_codegen/src/models/debug_200_response.rs +++ b/typesense_codegen/src/models/debug_200_response.rs @@ -11,14 +11,14 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct Debug200Response { #[serde(rename = "version", skip_serializing_if = "Option::is_none")] pub version: Option, } impl Debug200Response { - pub fn new() -> Debug200Response { + pub fn new() -> Debug200Response{ Debug200Response { version: None, } diff --git a/typesense_codegen/src/models/delete_documents_200_response.rs b/typesense_codegen/src/models/delete_documents_200_response.rs index d1a8399..7754da2 100644 --- a/typesense_codegen/src/models/delete_documents_200_response.rs +++ b/typesense_codegen/src/models/delete_documents_200_response.rs @@ -11,14 +11,14 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct DeleteDocuments200Response { #[serde(rename = "num_deleted")] pub num_deleted: i32, } impl DeleteDocuments200Response { - pub fn new(num_deleted: i32) -> DeleteDocuments200Response { + pub fn new(num_deleted: i32) -> DeleteDocuments200Response{ DeleteDocuments200Response { num_deleted, } diff --git a/typesense_codegen/src/models/delete_documents_parameters.rs b/typesense_codegen/src/models/delete_documents_parameters.rs index e18797a..b506c2f 100644 --- a/typesense_codegen/src/models/delete_documents_parameters.rs +++ b/typesense_codegen/src/models/delete_documents_parameters.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct DeleteDocumentsParameters { #[serde(rename = "filter_by")] pub filter_by: String, @@ -26,7 +26,7 @@ pub struct DeleteDocumentsParameters { } impl DeleteDocumentsParameters { - pub fn new(filter_by: String) -> DeleteDocumentsParameters { + pub fn new(filter_by: String) -> DeleteDocumentsParameters{ DeleteDocumentsParameters { filter_by, batch_size: None, diff --git a/typesense_codegen/src/models/delete_stopwords_set_200_response.rs b/typesense_codegen/src/models/delete_stopwords_set_200_response.rs index 25ab944..50fa78f 100644 --- a/typesense_codegen/src/models/delete_stopwords_set_200_response.rs +++ b/typesense_codegen/src/models/delete_stopwords_set_200_response.rs @@ -11,14 +11,14 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct DeleteStopwordsSet200Response { #[serde(rename = "id")] pub id: String, } impl DeleteStopwordsSet200Response { - pub fn new(id: String) -> DeleteStopwordsSet200Response { + pub fn new(id: String) -> DeleteStopwordsSet200Response{ DeleteStopwordsSet200Response { id, } diff --git a/typesense_codegen/src/models/export_documents_parameters.rs b/typesense_codegen/src/models/export_documents_parameters.rs index d7fcc7b..6f819fc 100644 --- a/typesense_codegen/src/models/export_documents_parameters.rs +++ b/typesense_codegen/src/models/export_documents_parameters.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct ExportDocumentsParameters { /// Filter conditions for refining your search results. Separate multiple conditions with &&. #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] @@ -25,7 +25,7 @@ pub struct ExportDocumentsParameters { } impl ExportDocumentsParameters { - pub fn new() -> ExportDocumentsParameters { + pub fn new() -> ExportDocumentsParameters{ ExportDocumentsParameters { filter_by: None, include_fields: None, diff --git a/typesense_codegen/src/models/facet_counts.rs b/typesense_codegen/src/models/facet_counts.rs index 920a49e..4eea304 100644 --- a/typesense_codegen/src/models/facet_counts.rs +++ b/typesense_codegen/src/models/facet_counts.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct FacetCounts { #[serde(rename = "counts", skip_serializing_if = "Option::is_none")] pub counts: Option>, @@ -22,7 +22,7 @@ pub struct FacetCounts { } impl FacetCounts { - pub fn new() -> FacetCounts { + pub fn new() -> FacetCounts{ FacetCounts { counts: None, field_name: None, diff --git a/typesense_codegen/src/models/facet_counts_counts_inner.rs b/typesense_codegen/src/models/facet_counts_counts_inner.rs index 7af2af8..83c07ae 100644 --- a/typesense_codegen/src/models/facet_counts_counts_inner.rs +++ b/typesense_codegen/src/models/facet_counts_counts_inner.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct FacetCountsCountsInner { #[serde(rename = "count", skip_serializing_if = "Option::is_none")] pub count: Option, @@ -24,7 +24,7 @@ pub struct FacetCountsCountsInner { } impl FacetCountsCountsInner { - pub fn new() -> FacetCountsCountsInner { + pub fn new() -> FacetCountsCountsInner{ FacetCountsCountsInner { count: None, highlighted: None, diff --git a/typesense_codegen/src/models/facet_counts_stats.rs b/typesense_codegen/src/models/facet_counts_stats.rs index 8e1109e..49efaa6 100644 --- a/typesense_codegen/src/models/facet_counts_stats.rs +++ b/typesense_codegen/src/models/facet_counts_stats.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct FacetCountsStats { #[serde(rename = "max", skip_serializing_if = "Option::is_none")] pub max: Option, @@ -26,7 +26,7 @@ pub struct FacetCountsStats { } impl FacetCountsStats { - pub fn new() -> FacetCountsStats { + pub fn new() -> FacetCountsStats{ FacetCountsStats { max: None, min: None, diff --git a/typesense_codegen/src/models/field.rs b/typesense_codegen/src/models/field.rs index 6722b99..5bad06d 100644 --- a/typesense_codegen/src/models/field.rs +++ b/typesense_codegen/src/models/field.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct Field { #[serde(rename = "name")] pub name: String, @@ -62,7 +62,7 @@ pub struct Field { } impl Field { - pub fn new(name: String, r#type: String) -> Field { + pub fn new(name: String, r#type: String) -> Field{ Field { name, r#type, diff --git a/typesense_codegen/src/models/field_embed.rs b/typesense_codegen/src/models/field_embed.rs index 80fa93c..4c9db90 100644 --- a/typesense_codegen/src/models/field_embed.rs +++ b/typesense_codegen/src/models/field_embed.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct FieldEmbed { #[serde(rename = "from")] pub from: Vec, @@ -20,7 +20,7 @@ pub struct FieldEmbed { } impl FieldEmbed { - pub fn new(from: Vec, model_config: models::FieldEmbedModelConfig) -> FieldEmbed { + pub fn new(from: Vec, model_config: models::FieldEmbedModelConfig) -> FieldEmbed{ FieldEmbed { from, model_config: Box::new(model_config), diff --git a/typesense_codegen/src/models/field_embed_model_config.rs b/typesense_codegen/src/models/field_embed_model_config.rs index 00620cc..1c15907 100644 --- a/typesense_codegen/src/models/field_embed_model_config.rs +++ b/typesense_codegen/src/models/field_embed_model_config.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct FieldEmbedModelConfig { #[serde(rename = "model_name")] pub model_name: String, @@ -36,7 +36,7 @@ pub struct FieldEmbedModelConfig { } impl FieldEmbedModelConfig { - pub fn new(model_name: String) -> FieldEmbedModelConfig { + pub fn new(model_name: String) -> FieldEmbedModelConfig{ FieldEmbedModelConfig { model_name, api_key: None, diff --git a/typesense_codegen/src/models/get_collections_parameters.rs b/typesense_codegen/src/models/get_collections_parameters.rs index c6ac5a3..3b420ef 100644 --- a/typesense_codegen/src/models/get_collections_parameters.rs +++ b/typesense_codegen/src/models/get_collections_parameters.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct GetCollectionsParameters { /// Comma-separated list of fields from the collection to exclude from the response #[serde(rename = "exclude_fields", skip_serializing_if = "Option::is_none")] @@ -25,7 +25,7 @@ pub struct GetCollectionsParameters { } impl GetCollectionsParameters { - pub fn new() -> GetCollectionsParameters { + pub fn new() -> GetCollectionsParameters{ GetCollectionsParameters { exclude_fields: None, limit: None, diff --git a/typesense_codegen/src/models/health_status.rs b/typesense_codegen/src/models/health_status.rs index 1a69ccb..baf20eb 100644 --- a/typesense_codegen/src/models/health_status.rs +++ b/typesense_codegen/src/models/health_status.rs @@ -11,14 +11,14 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct HealthStatus { #[serde(rename = "ok")] pub ok: bool, } impl HealthStatus { - pub fn new(ok: bool) -> HealthStatus { + pub fn new(ok: bool) -> HealthStatus{ HealthStatus { ok, } diff --git a/typesense_codegen/src/models/import_documents_parameters.rs b/typesense_codegen/src/models/import_documents_parameters.rs index 01e502e..ced47b9 100644 --- a/typesense_codegen/src/models/import_documents_parameters.rs +++ b/typesense_codegen/src/models/import_documents_parameters.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct ImportDocumentsParameters { #[serde(rename = "batch_size", skip_serializing_if = "Option::is_none")] pub batch_size: Option, @@ -29,7 +29,7 @@ pub struct ImportDocumentsParameters { } impl ImportDocumentsParameters { - pub fn new() -> ImportDocumentsParameters { + pub fn new() -> ImportDocumentsParameters{ ImportDocumentsParameters { batch_size: None, return_id: None, diff --git a/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs b/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs index e519db7..8d7ae85 100644 --- a/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs +++ b/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs @@ -11,14 +11,14 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct ListStemmingDictionaries200Response { #[serde(rename = "dictionaries", skip_serializing_if = "Option::is_none")] pub dictionaries: Option>, } impl ListStemmingDictionaries200Response { - pub fn new() -> ListStemmingDictionaries200Response { + pub fn new() -> ListStemmingDictionaries200Response{ ListStemmingDictionaries200Response { dictionaries: None, } diff --git a/typesense_codegen/src/models/multi_search_collection_parameters.rs b/typesense_codegen/src/models/multi_search_collection_parameters.rs index c3b7fe2..bc3df6e 100644 --- a/typesense_codegen/src/models/multi_search_collection_parameters.rs +++ b/typesense_codegen/src/models/multi_search_collection_parameters.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct MultiSearchCollectionParameters { /// The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. #[serde(rename = "q", skip_serializing_if = "Option::is_none")] @@ -216,7 +216,7 @@ pub struct MultiSearchCollectionParameters { } impl MultiSearchCollectionParameters { - pub fn new() -> MultiSearchCollectionParameters { + pub fn new() -> MultiSearchCollectionParameters{ MultiSearchCollectionParameters { q: None, query_by: None, diff --git a/typesense_codegen/src/models/multi_search_parameters.rs b/typesense_codegen/src/models/multi_search_parameters.rs index 2a94e44..7d6d8c5 100644 --- a/typesense_codegen/src/models/multi_search_parameters.rs +++ b/typesense_codegen/src/models/multi_search_parameters.rs @@ -12,7 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; /// MultiSearchParameters : Parameters for the multi search API. -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct MultiSearchParameters { /// The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. #[serde(rename = "q", skip_serializing_if = "Option::is_none")] @@ -209,7 +209,7 @@ pub struct MultiSearchParameters { impl MultiSearchParameters { /// Parameters for the multi search API. - pub fn new() -> MultiSearchParameters { + pub fn new() -> MultiSearchParameters{ MultiSearchParameters { q: None, query_by: None, diff --git a/typesense_codegen/src/models/multi_search_result.rs b/typesense_codegen/src/models/multi_search_result.rs index c0675e4..f263930 100644 --- a/typesense_codegen/src/models/multi_search_result.rs +++ b/typesense_codegen/src/models/multi_search_result.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct MultiSearchResult { #[serde(rename = "results")] pub results: Vec, @@ -20,7 +20,7 @@ pub struct MultiSearchResult { } impl MultiSearchResult { - pub fn new(results: Vec) -> MultiSearchResult { + pub fn new(results: Vec) -> MultiSearchResult{ MultiSearchResult { results, conversation: None, diff --git a/typesense_codegen/src/models/multi_search_result_item.rs b/typesense_codegen/src/models/multi_search_result_item.rs index 8cdc357..945a1c3 100644 --- a/typesense_codegen/src/models/multi_search_result_item.rs +++ b/typesense_codegen/src/models/multi_search_result_item.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct MultiSearchResultItem { #[serde(rename = "facet_counts", skip_serializing_if = "Option::is_none")] pub facet_counts: Option>, @@ -36,7 +36,7 @@ pub struct MultiSearchResultItem { pub grouped_hits: Option>, /// The documents that matched the search query #[serde(rename = "hits", skip_serializing_if = "Option::is_none")] - pub hits: Option>, + pub hits: Option>>, #[serde(rename = "request_params", skip_serializing_if = "Option::is_none")] pub request_params: Option>, #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] @@ -53,7 +53,7 @@ pub struct MultiSearchResultItem { } impl MultiSearchResultItem { - pub fn new() -> MultiSearchResultItem { + pub fn new() -> MultiSearchResultItem{ MultiSearchResultItem { facet_counts: None, found: None, diff --git a/typesense_codegen/src/models/multi_search_searches_parameter.rs b/typesense_codegen/src/models/multi_search_searches_parameter.rs index b4f53b1..0141ba6 100644 --- a/typesense_codegen/src/models/multi_search_searches_parameter.rs +++ b/typesense_codegen/src/models/multi_search_searches_parameter.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct MultiSearchSearchesParameter { /// When true, merges the search results from each search query into a single ordered set of hits. #[serde(rename = "union", skip_serializing_if = "Option::is_none")] @@ -21,7 +21,7 @@ pub struct MultiSearchSearchesParameter { } impl MultiSearchSearchesParameter { - pub fn new(searches: Vec) -> MultiSearchSearchesParameter { + pub fn new(searches: Vec) -> MultiSearchSearchesParameter{ MultiSearchSearchesParameter { union: None, searches, diff --git a/typesense_codegen/src/models/nl_search_model_base.rs b/typesense_codegen/src/models/nl_search_model_base.rs index 8474b36..570233a 100644 --- a/typesense_codegen/src/models/nl_search_model_base.rs +++ b/typesense_codegen/src/models/nl_search_model_base.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct NlSearchModelBase { /// Name of the NL model to use #[serde(rename = "model_name", skip_serializing_if = "Option::is_none")] @@ -70,7 +70,7 @@ pub struct NlSearchModelBase { } impl NlSearchModelBase { - pub fn new() -> NlSearchModelBase { + pub fn new() -> NlSearchModelBase{ NlSearchModelBase { model_name: None, api_key: None, diff --git a/typesense_codegen/src/models/nl_search_model_create_schema.rs b/typesense_codegen/src/models/nl_search_model_create_schema.rs index b4fd036..5816e8a 100644 --- a/typesense_codegen/src/models/nl_search_model_create_schema.rs +++ b/typesense_codegen/src/models/nl_search_model_create_schema.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct NlSearchModelCreateSchema { /// Name of the NL model to use #[serde(rename = "model_name", skip_serializing_if = "Option::is_none")] @@ -73,7 +73,7 @@ pub struct NlSearchModelCreateSchema { } impl NlSearchModelCreateSchema { - pub fn new() -> NlSearchModelCreateSchema { + pub fn new() -> NlSearchModelCreateSchema{ NlSearchModelCreateSchema { model_name: None, api_key: None, diff --git a/typesense_codegen/src/models/nl_search_model_delete_schema.rs b/typesense_codegen/src/models/nl_search_model_delete_schema.rs index 734e090..92fac03 100644 --- a/typesense_codegen/src/models/nl_search_model_delete_schema.rs +++ b/typesense_codegen/src/models/nl_search_model_delete_schema.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct NlSearchModelDeleteSchema { /// ID of the deleted NL search model #[serde(rename = "id")] @@ -19,7 +19,7 @@ pub struct NlSearchModelDeleteSchema { } impl NlSearchModelDeleteSchema { - pub fn new(id: String) -> NlSearchModelDeleteSchema { + pub fn new(id: String) -> NlSearchModelDeleteSchema{ NlSearchModelDeleteSchema { id, } diff --git a/typesense_codegen/src/models/nl_search_model_schema.rs b/typesense_codegen/src/models/nl_search_model_schema.rs index 7658d9a..7ebf85b 100644 --- a/typesense_codegen/src/models/nl_search_model_schema.rs +++ b/typesense_codegen/src/models/nl_search_model_schema.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct NlSearchModelSchema { /// Name of the NL model to use #[serde(rename = "model_name", skip_serializing_if = "Option::is_none")] @@ -73,7 +73,7 @@ pub struct NlSearchModelSchema { } impl NlSearchModelSchema { - pub fn new(id: String) -> NlSearchModelSchema { + pub fn new(id: String) -> NlSearchModelSchema{ NlSearchModelSchema { model_name: None, api_key: None, diff --git a/typesense_codegen/src/models/preset_delete_schema.rs b/typesense_codegen/src/models/preset_delete_schema.rs index 2e09591..12e794d 100644 --- a/typesense_codegen/src/models/preset_delete_schema.rs +++ b/typesense_codegen/src/models/preset_delete_schema.rs @@ -11,14 +11,14 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct PresetDeleteSchema { #[serde(rename = "name")] pub name: String, } impl PresetDeleteSchema { - pub fn new(name: String) -> PresetDeleteSchema { + pub fn new(name: String) -> PresetDeleteSchema{ PresetDeleteSchema { name, } diff --git a/typesense_codegen/src/models/preset_schema.rs b/typesense_codegen/src/models/preset_schema.rs index c2ad363..b7fb354 100644 --- a/typesense_codegen/src/models/preset_schema.rs +++ b/typesense_codegen/src/models/preset_schema.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct PresetSchema { #[serde(rename = "value")] pub value: Box, @@ -20,7 +20,7 @@ pub struct PresetSchema { } impl PresetSchema { - pub fn new(value: models::PresetUpsertSchemaValue, name: String) -> PresetSchema { + pub fn new(value: models::PresetUpsertSchemaValue, name: String) -> PresetSchema{ PresetSchema { value: Box::new(value), name, diff --git a/typesense_codegen/src/models/preset_upsert_schema.rs b/typesense_codegen/src/models/preset_upsert_schema.rs index f92c4f0..70c66e6 100644 --- a/typesense_codegen/src/models/preset_upsert_schema.rs +++ b/typesense_codegen/src/models/preset_upsert_schema.rs @@ -11,14 +11,14 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct PresetUpsertSchema { #[serde(rename = "value")] pub value: Box, } impl PresetUpsertSchema { - pub fn new(value: models::PresetUpsertSchemaValue) -> PresetUpsertSchema { + pub fn new(value: models::PresetUpsertSchemaValue) -> PresetUpsertSchema{ PresetUpsertSchema { value: Box::new(value), } diff --git a/typesense_codegen/src/models/presets_retrieve_schema.rs b/typesense_codegen/src/models/presets_retrieve_schema.rs index 752ea33..6828efc 100644 --- a/typesense_codegen/src/models/presets_retrieve_schema.rs +++ b/typesense_codegen/src/models/presets_retrieve_schema.rs @@ -11,14 +11,14 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct PresetsRetrieveSchema { #[serde(rename = "presets")] pub presets: Vec, } impl PresetsRetrieveSchema { - pub fn new(presets: Vec) -> PresetsRetrieveSchema { + pub fn new(presets: Vec) -> PresetsRetrieveSchema{ PresetsRetrieveSchema { presets, } diff --git a/typesense_codegen/src/models/schema_change_status.rs b/typesense_codegen/src/models/schema_change_status.rs index 6021075..86fb7ff 100644 --- a/typesense_codegen/src/models/schema_change_status.rs +++ b/typesense_codegen/src/models/schema_change_status.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct SchemaChangeStatus { /// Name of the collection being modified #[serde(rename = "collection", skip_serializing_if = "Option::is_none")] @@ -25,7 +25,7 @@ pub struct SchemaChangeStatus { } impl SchemaChangeStatus { - pub fn new() -> SchemaChangeStatus { + pub fn new() -> SchemaChangeStatus{ SchemaChangeStatus { collection: None, validated_docs: None, diff --git a/typesense_codegen/src/models/search_grouped_hit.rs b/typesense_codegen/src/models/search_grouped_hit.rs index f55ad8d..3d7394c 100644 --- a/typesense_codegen/src/models/search_grouped_hit.rs +++ b/typesense_codegen/src/models/search_grouped_hit.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct SearchGroupedHit { #[serde(rename = "found", skip_serializing_if = "Option::is_none")] pub found: Option, @@ -23,7 +23,7 @@ pub struct SearchGroupedHit { } impl SearchGroupedHit { - pub fn new(group_key: Vec, hits: Vec) -> SearchGroupedHit { + pub fn new(group_key: Vec, hits: Vec) -> SearchGroupedHit{ SearchGroupedHit { found: None, group_key, diff --git a/typesense_codegen/src/models/search_highlight.rs b/typesense_codegen/src/models/search_highlight.rs index 23b8b47..2975151 100644 --- a/typesense_codegen/src/models/search_highlight.rs +++ b/typesense_codegen/src/models/search_highlight.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct SearchHighlight { #[serde(rename = "field", skip_serializing_if = "Option::is_none")] pub field: Option, @@ -35,7 +35,7 @@ pub struct SearchHighlight { } impl SearchHighlight { - pub fn new() -> SearchHighlight { + pub fn new() -> SearchHighlight{ SearchHighlight { field: None, snippet: None, diff --git a/typesense_codegen/src/models/search_override.rs b/typesense_codegen/src/models/search_override.rs index b95ad22..518dc7b 100644 --- a/typesense_codegen/src/models/search_override.rs +++ b/typesense_codegen/src/models/search_override.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct SearchOverride { #[serde(rename = "rule")] pub rule: Box, @@ -53,7 +53,7 @@ pub struct SearchOverride { } impl SearchOverride { - pub fn new(rule: models::SearchOverrideRule, id: String) -> SearchOverride { + pub fn new(rule: models::SearchOverrideRule, id: String) -> SearchOverride{ SearchOverride { rule: Box::new(rule), includes: None, diff --git a/typesense_codegen/src/models/search_override_delete_response.rs b/typesense_codegen/src/models/search_override_delete_response.rs index 1842bd5..cc0973d 100644 --- a/typesense_codegen/src/models/search_override_delete_response.rs +++ b/typesense_codegen/src/models/search_override_delete_response.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct SearchOverrideDeleteResponse { /// The id of the override that was deleted #[serde(rename = "id")] @@ -19,7 +19,7 @@ pub struct SearchOverrideDeleteResponse { } impl SearchOverrideDeleteResponse { - pub fn new(id: String) -> SearchOverrideDeleteResponse { + pub fn new(id: String) -> SearchOverrideDeleteResponse{ SearchOverrideDeleteResponse { id, } diff --git a/typesense_codegen/src/models/search_override_exclude.rs b/typesense_codegen/src/models/search_override_exclude.rs index 177ea55..eff124a 100644 --- a/typesense_codegen/src/models/search_override_exclude.rs +++ b/typesense_codegen/src/models/search_override_exclude.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct SearchOverrideExclude { /// document id that should be excluded from the search results. #[serde(rename = "id")] @@ -19,7 +19,7 @@ pub struct SearchOverrideExclude { } impl SearchOverrideExclude { - pub fn new(id: String) -> SearchOverrideExclude { + pub fn new(id: String) -> SearchOverrideExclude{ SearchOverrideExclude { id, } diff --git a/typesense_codegen/src/models/search_override_include.rs b/typesense_codegen/src/models/search_override_include.rs index 5f275bb..2e993ee 100644 --- a/typesense_codegen/src/models/search_override_include.rs +++ b/typesense_codegen/src/models/search_override_include.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct SearchOverrideInclude { /// document id that should be included #[serde(rename = "id")] @@ -22,7 +22,7 @@ pub struct SearchOverrideInclude { } impl SearchOverrideInclude { - pub fn new(id: String, position: i32) -> SearchOverrideInclude { + pub fn new(id: String, position: i32) -> SearchOverrideInclude{ SearchOverrideInclude { id, position, diff --git a/typesense_codegen/src/models/search_override_rule.rs b/typesense_codegen/src/models/search_override_rule.rs index 923171d..4372a10 100644 --- a/typesense_codegen/src/models/search_override_rule.rs +++ b/typesense_codegen/src/models/search_override_rule.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct SearchOverrideRule { /// List of tag values to associate with this override rule. #[serde(rename = "tags", skip_serializing_if = "Option::is_none")] @@ -28,7 +28,7 @@ pub struct SearchOverrideRule { } impl SearchOverrideRule { - pub fn new() -> SearchOverrideRule { + pub fn new() -> SearchOverrideRule{ SearchOverrideRule { tags: None, query: None, diff --git a/typesense_codegen/src/models/search_override_schema.rs b/typesense_codegen/src/models/search_override_schema.rs index 5997bcd..b3be39f 100644 --- a/typesense_codegen/src/models/search_override_schema.rs +++ b/typesense_codegen/src/models/search_override_schema.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct SearchOverrideSchema { #[serde(rename = "rule")] pub rule: Box, @@ -51,7 +51,7 @@ pub struct SearchOverrideSchema { } impl SearchOverrideSchema { - pub fn new(rule: models::SearchOverrideRule) -> SearchOverrideSchema { + pub fn new(rule: models::SearchOverrideRule) -> SearchOverrideSchema{ SearchOverrideSchema { rule: Box::new(rule), includes: None, diff --git a/typesense_codegen/src/models/search_overrides_response.rs b/typesense_codegen/src/models/search_overrides_response.rs index c71e776..e9f9296 100644 --- a/typesense_codegen/src/models/search_overrides_response.rs +++ b/typesense_codegen/src/models/search_overrides_response.rs @@ -11,14 +11,14 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct SearchOverridesResponse { #[serde(rename = "overrides")] pub overrides: Vec, } impl SearchOverridesResponse { - pub fn new(overrides: Vec) -> SearchOverridesResponse { + pub fn new(overrides: Vec) -> SearchOverridesResponse{ SearchOverridesResponse { overrides, } diff --git a/typesense_codegen/src/models/search_parameters.rs b/typesense_codegen/src/models/search_parameters.rs index 28ff332..60aa8e4 100644 --- a/typesense_codegen/src/models/search_parameters.rs +++ b/typesense_codegen/src/models/search_parameters.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct SearchParameters { /// The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. #[serde(rename = "q", skip_serializing_if = "Option::is_none")] @@ -228,7 +228,7 @@ pub struct SearchParameters { } impl SearchParameters { - pub fn new() -> SearchParameters { + pub fn new() -> SearchParameters{ SearchParameters { q: None, query_by: None, diff --git a/typesense_codegen/src/models/search_request_params.rs b/typesense_codegen/src/models/search_request_params.rs index bcdca8d..246a7e4 100644 --- a/typesense_codegen/src/models/search_request_params.rs +++ b/typesense_codegen/src/models/search_request_params.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct SearchRequestParams { #[serde(rename = "collection_name")] pub collection_name: String, @@ -24,7 +24,7 @@ pub struct SearchRequestParams { } impl SearchRequestParams { - pub fn new(collection_name: String, q: String, per_page: i32) -> SearchRequestParams { + pub fn new(collection_name: String, q: String, per_page: i32) -> SearchRequestParams{ SearchRequestParams { collection_name, q, diff --git a/typesense_codegen/src/models/search_request_params_voice_query.rs b/typesense_codegen/src/models/search_request_params_voice_query.rs index 4c5efdd..88545d7 100644 --- a/typesense_codegen/src/models/search_request_params_voice_query.rs +++ b/typesense_codegen/src/models/search_request_params_voice_query.rs @@ -11,14 +11,14 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct SearchRequestParamsVoiceQuery { #[serde(rename = "transcribed_query", skip_serializing_if = "Option::is_none")] pub transcribed_query: Option, } impl SearchRequestParamsVoiceQuery { - pub fn new() -> SearchRequestParamsVoiceQuery { + pub fn new() -> SearchRequestParamsVoiceQuery{ SearchRequestParamsVoiceQuery { transcribed_query: None, } diff --git a/typesense_codegen/src/models/search_result.rs b/typesense_codegen/src/models/search_result.rs index 68179bb..6712dae 100644 --- a/typesense_codegen/src/models/search_result.rs +++ b/typesense_codegen/src/models/search_result.rs @@ -11,8 +11,8 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct SearchResult { +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +pub struct SearchResult { #[serde(rename = "facet_counts", skip_serializing_if = "Option::is_none")] pub facet_counts: Option>, /// The number of documents found @@ -36,7 +36,7 @@ pub struct SearchResult { pub grouped_hits: Option>, /// The documents that matched the search query #[serde(rename = "hits", skip_serializing_if = "Option::is_none")] - pub hits: Option>, + pub hits: Option>>, #[serde(rename = "request_params", skip_serializing_if = "Option::is_none")] pub request_params: Option>, #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] @@ -46,8 +46,8 @@ pub struct SearchResult { pub union_request_params: Option>, } -impl SearchResult { - pub fn new() -> SearchResult { +impl SearchResult { + pub fn new() -> SearchResult{ SearchResult { facet_counts: None, found: None, diff --git a/typesense_codegen/src/models/search_result_conversation.rs b/typesense_codegen/src/models/search_result_conversation.rs index 959f287..88d3659 100644 --- a/typesense_codegen/src/models/search_result_conversation.rs +++ b/typesense_codegen/src/models/search_result_conversation.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct SearchResultConversation { #[serde(rename = "answer")] pub answer: String, @@ -24,7 +24,7 @@ pub struct SearchResultConversation { } impl SearchResultConversation { - pub fn new(answer: String, conversation_history: Vec, conversation_id: String, query: String) -> SearchResultConversation { + pub fn new(answer: String, conversation_history: Vec, conversation_id: String, query: String) -> SearchResultConversation{ SearchResultConversation { answer, conversation_history, diff --git a/typesense_codegen/src/models/search_result_hit.rs b/typesense_codegen/src/models/search_result_hit.rs index 7736414..26b1afd 100644 --- a/typesense_codegen/src/models/search_result_hit.rs +++ b/typesense_codegen/src/models/search_result_hit.rs @@ -11,8 +11,8 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct SearchResultHit { +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +pub struct SearchResultHit { /// (Deprecated) Contains highlighted portions of the search fields #[serde(rename = "highlights", skip_serializing_if = "Option::is_none")] pub highlights: Option>, @@ -21,7 +21,7 @@ pub struct SearchResultHit { pub highlight: Option>, /// Can be any key-value pair #[serde(rename = "document", skip_serializing_if = "Option::is_none")] - pub document: Option>, + pub document: Option, #[serde(rename = "text_match", skip_serializing_if = "Option::is_none")] pub text_match: Option, #[serde(rename = "text_match_info", skip_serializing_if = "Option::is_none")] @@ -39,8 +39,8 @@ pub struct SearchResultHit { pub search_index: Option, } -impl SearchResultHit { - pub fn new() -> SearchResultHit { +impl SearchResultHit { + pub fn new() -> SearchResultHit{ SearchResultHit { highlights: None, highlight: None, diff --git a/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs b/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs index 4035e5f..8ac7d1b 100644 --- a/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs +++ b/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs @@ -12,7 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; /// SearchResultHitHybridSearchInfo : Information about hybrid search scoring -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct SearchResultHitHybridSearchInfo { /// Combined score from rank fusion of text and vector search #[serde(rename = "rank_fusion_score", skip_serializing_if = "Option::is_none")] @@ -21,7 +21,7 @@ pub struct SearchResultHitHybridSearchInfo { impl SearchResultHitHybridSearchInfo { /// Information about hybrid search scoring - pub fn new() -> SearchResultHitHybridSearchInfo { + pub fn new() -> SearchResultHitHybridSearchInfo{ SearchResultHitHybridSearchInfo { rank_fusion_score: None, } diff --git a/typesense_codegen/src/models/search_result_hit_text_match_info.rs b/typesense_codegen/src/models/search_result_hit_text_match_info.rs index 08b0740..6ee4bc4 100644 --- a/typesense_codegen/src/models/search_result_hit_text_match_info.rs +++ b/typesense_codegen/src/models/search_result_hit_text_match_info.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct SearchResultHitTextMatchInfo { #[serde(rename = "best_field_score", skip_serializing_if = "Option::is_none")] pub best_field_score: Option, @@ -30,7 +30,7 @@ pub struct SearchResultHitTextMatchInfo { } impl SearchResultHitTextMatchInfo { - pub fn new() -> SearchResultHitTextMatchInfo { + pub fn new() -> SearchResultHitTextMatchInfo{ SearchResultHitTextMatchInfo { best_field_score: None, best_field_weight: None, diff --git a/typesense_codegen/src/models/search_synonym.rs b/typesense_codegen/src/models/search_synonym.rs index bb13105..6ee65d6 100644 --- a/typesense_codegen/src/models/search_synonym.rs +++ b/typesense_codegen/src/models/search_synonym.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct SearchSynonym { /// For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. #[serde(rename = "root", skip_serializing_if = "Option::is_none")] @@ -30,7 +30,7 @@ pub struct SearchSynonym { } impl SearchSynonym { - pub fn new(synonyms: Vec, id: String) -> SearchSynonym { + pub fn new(synonyms: Vec, id: String) -> SearchSynonym{ SearchSynonym { root: None, synonyms, diff --git a/typesense_codegen/src/models/search_synonym_delete_response.rs b/typesense_codegen/src/models/search_synonym_delete_response.rs index 3c3563a..9610a90 100644 --- a/typesense_codegen/src/models/search_synonym_delete_response.rs +++ b/typesense_codegen/src/models/search_synonym_delete_response.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct SearchSynonymDeleteResponse { /// The id of the synonym that was deleted #[serde(rename = "id")] @@ -19,7 +19,7 @@ pub struct SearchSynonymDeleteResponse { } impl SearchSynonymDeleteResponse { - pub fn new(id: String) -> SearchSynonymDeleteResponse { + pub fn new(id: String) -> SearchSynonymDeleteResponse{ SearchSynonymDeleteResponse { id, } diff --git a/typesense_codegen/src/models/search_synonym_schema.rs b/typesense_codegen/src/models/search_synonym_schema.rs index 38ef415..be1d4c5 100644 --- a/typesense_codegen/src/models/search_synonym_schema.rs +++ b/typesense_codegen/src/models/search_synonym_schema.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct SearchSynonymSchema { /// For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. #[serde(rename = "root", skip_serializing_if = "Option::is_none")] @@ -28,7 +28,7 @@ pub struct SearchSynonymSchema { } impl SearchSynonymSchema { - pub fn new(synonyms: Vec) -> SearchSynonymSchema { + pub fn new(synonyms: Vec) -> SearchSynonymSchema{ SearchSynonymSchema { root: None, synonyms, diff --git a/typesense_codegen/src/models/search_synonyms_response.rs b/typesense_codegen/src/models/search_synonyms_response.rs index 6c84a34..fbc4a7b 100644 --- a/typesense_codegen/src/models/search_synonyms_response.rs +++ b/typesense_codegen/src/models/search_synonyms_response.rs @@ -11,14 +11,14 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct SearchSynonymsResponse { #[serde(rename = "synonyms")] pub synonyms: Vec, } impl SearchSynonymsResponse { - pub fn new(synonyms: Vec) -> SearchSynonymsResponse { + pub fn new(synonyms: Vec) -> SearchSynonymsResponse{ SearchSynonymsResponse { synonyms, } diff --git a/typesense_codegen/src/models/stemming_dictionary.rs b/typesense_codegen/src/models/stemming_dictionary.rs index db946aa..bbf5866 100644 --- a/typesense_codegen/src/models/stemming_dictionary.rs +++ b/typesense_codegen/src/models/stemming_dictionary.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct StemmingDictionary { /// Unique identifier for the dictionary #[serde(rename = "id")] @@ -22,7 +22,7 @@ pub struct StemmingDictionary { } impl StemmingDictionary { - pub fn new(id: String, words: Vec) -> StemmingDictionary { + pub fn new(id: String, words: Vec) -> StemmingDictionary{ StemmingDictionary { id, words, diff --git a/typesense_codegen/src/models/stemming_dictionary_words_inner.rs b/typesense_codegen/src/models/stemming_dictionary_words_inner.rs index 117e21e..c82be83 100644 --- a/typesense_codegen/src/models/stemming_dictionary_words_inner.rs +++ b/typesense_codegen/src/models/stemming_dictionary_words_inner.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct StemmingDictionaryWordsInner { /// The word form to be stemmed #[serde(rename = "word")] @@ -22,7 +22,7 @@ pub struct StemmingDictionaryWordsInner { } impl StemmingDictionaryWordsInner { - pub fn new(word: String, root: String) -> StemmingDictionaryWordsInner { + pub fn new(word: String, root: String) -> StemmingDictionaryWordsInner{ StemmingDictionaryWordsInner { word, root, diff --git a/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs b/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs index 9f61912..6cc7f80 100644 --- a/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs +++ b/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs @@ -11,14 +11,14 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct StopwordsSetRetrieveSchema { #[serde(rename = "stopwords")] pub stopwords: Box, } impl StopwordsSetRetrieveSchema { - pub fn new(stopwords: models::StopwordsSetSchema) -> StopwordsSetRetrieveSchema { + pub fn new(stopwords: models::StopwordsSetSchema) -> StopwordsSetRetrieveSchema{ StopwordsSetRetrieveSchema { stopwords: Box::new(stopwords), } diff --git a/typesense_codegen/src/models/stopwords_set_schema.rs b/typesense_codegen/src/models/stopwords_set_schema.rs index 60ae226..686e23f 100644 --- a/typesense_codegen/src/models/stopwords_set_schema.rs +++ b/typesense_codegen/src/models/stopwords_set_schema.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct StopwordsSetSchema { #[serde(rename = "id")] pub id: String, @@ -22,7 +22,7 @@ pub struct StopwordsSetSchema { } impl StopwordsSetSchema { - pub fn new(id: String, stopwords: Vec) -> StopwordsSetSchema { + pub fn new(id: String, stopwords: Vec) -> StopwordsSetSchema{ StopwordsSetSchema { id, stopwords, diff --git a/typesense_codegen/src/models/stopwords_set_upsert_schema.rs b/typesense_codegen/src/models/stopwords_set_upsert_schema.rs index 76ba788..7460d90 100644 --- a/typesense_codegen/src/models/stopwords_set_upsert_schema.rs +++ b/typesense_codegen/src/models/stopwords_set_upsert_schema.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct StopwordsSetUpsertSchema { #[serde(rename = "stopwords")] pub stopwords: Vec, @@ -20,7 +20,7 @@ pub struct StopwordsSetUpsertSchema { } impl StopwordsSetUpsertSchema { - pub fn new(stopwords: Vec) -> StopwordsSetUpsertSchema { + pub fn new(stopwords: Vec) -> StopwordsSetUpsertSchema{ StopwordsSetUpsertSchema { stopwords, locale: None, diff --git a/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs b/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs index 2212e37..bf58071 100644 --- a/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs +++ b/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs @@ -11,14 +11,14 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct StopwordsSetsRetrieveAllSchema { #[serde(rename = "stopwords")] pub stopwords: Vec, } impl StopwordsSetsRetrieveAllSchema { - pub fn new(stopwords: Vec) -> StopwordsSetsRetrieveAllSchema { + pub fn new(stopwords: Vec) -> StopwordsSetsRetrieveAllSchema{ StopwordsSetsRetrieveAllSchema { stopwords, } diff --git a/typesense_codegen/src/models/success_status.rs b/typesense_codegen/src/models/success_status.rs index 490436c..d2ebbf2 100644 --- a/typesense_codegen/src/models/success_status.rs +++ b/typesense_codegen/src/models/success_status.rs @@ -11,14 +11,14 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct SuccessStatus { #[serde(rename = "success")] pub success: bool, } impl SuccessStatus { - pub fn new(success: bool) -> SuccessStatus { + pub fn new(success: bool) -> SuccessStatus{ SuccessStatus { success, } diff --git a/typesense_codegen/src/models/synonym_item_schema.rs b/typesense_codegen/src/models/synonym_item_schema.rs index 50362c4..b47c770 100644 --- a/typesense_codegen/src/models/synonym_item_schema.rs +++ b/typesense_codegen/src/models/synonym_item_schema.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct SynonymItemSchema { /// Unique identifier for the synonym item #[serde(rename = "id")] @@ -31,7 +31,7 @@ pub struct SynonymItemSchema { } impl SynonymItemSchema { - pub fn new(id: String, synonyms: Vec) -> SynonymItemSchema { + pub fn new(id: String, synonyms: Vec) -> SynonymItemSchema{ SynonymItemSchema { id, synonyms, diff --git a/typesense_codegen/src/models/synonym_set_create_schema.rs b/typesense_codegen/src/models/synonym_set_create_schema.rs index 57cdfd3..5946102 100644 --- a/typesense_codegen/src/models/synonym_set_create_schema.rs +++ b/typesense_codegen/src/models/synonym_set_create_schema.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct SynonymSetCreateSchema { /// Array of synonym items #[serde(rename = "items")] @@ -19,7 +19,7 @@ pub struct SynonymSetCreateSchema { } impl SynonymSetCreateSchema { - pub fn new(items: Vec) -> SynonymSetCreateSchema { + pub fn new(items: Vec) -> SynonymSetCreateSchema{ SynonymSetCreateSchema { items, } diff --git a/typesense_codegen/src/models/synonym_set_delete_schema.rs b/typesense_codegen/src/models/synonym_set_delete_schema.rs index 7d5a559..114a46f 100644 --- a/typesense_codegen/src/models/synonym_set_delete_schema.rs +++ b/typesense_codegen/src/models/synonym_set_delete_schema.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct SynonymSetDeleteSchema { /// Name of the deleted synonym set #[serde(rename = "name")] @@ -19,7 +19,7 @@ pub struct SynonymSetDeleteSchema { } impl SynonymSetDeleteSchema { - pub fn new(name: String) -> SynonymSetDeleteSchema { + pub fn new(name: String) -> SynonymSetDeleteSchema{ SynonymSetDeleteSchema { name, } diff --git a/typesense_codegen/src/models/synonym_set_schema.rs b/typesense_codegen/src/models/synonym_set_schema.rs index 3e7cc55..57883d9 100644 --- a/typesense_codegen/src/models/synonym_set_schema.rs +++ b/typesense_codegen/src/models/synonym_set_schema.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct SynonymSetSchema { /// Array of synonym items #[serde(rename = "items")] @@ -22,7 +22,7 @@ pub struct SynonymSetSchema { } impl SynonymSetSchema { - pub fn new(items: Vec, name: String) -> SynonymSetSchema { + pub fn new(items: Vec, name: String) -> SynonymSetSchema{ SynonymSetSchema { items, name, diff --git a/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs b/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs index 74823bb..f2c7fd9 100644 --- a/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs +++ b/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct SynonymSetsRetrieveSchema { /// Array of synonym sets #[serde(rename = "synonym_sets")] @@ -19,7 +19,7 @@ pub struct SynonymSetsRetrieveSchema { } impl SynonymSetsRetrieveSchema { - pub fn new(synonym_sets: Vec) -> SynonymSetsRetrieveSchema { + pub fn new(synonym_sets: Vec) -> SynonymSetsRetrieveSchema{ SynonymSetsRetrieveSchema { synonym_sets, } diff --git a/typesense_codegen/src/models/toggle_slow_request_log_request.rs b/typesense_codegen/src/models/toggle_slow_request_log_request.rs index 7999551..de499ad 100644 --- a/typesense_codegen/src/models/toggle_slow_request_log_request.rs +++ b/typesense_codegen/src/models/toggle_slow_request_log_request.rs @@ -11,14 +11,14 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct ToggleSlowRequestLogRequest { #[serde(rename = "log-slow-requests-time-ms")] pub log_slow_requests_time_ms: i32, } impl ToggleSlowRequestLogRequest { - pub fn new(log_slow_requests_time_ms: i32) -> ToggleSlowRequestLogRequest { + pub fn new(log_slow_requests_time_ms: i32) -> ToggleSlowRequestLogRequest{ ToggleSlowRequestLogRequest { log_slow_requests_time_ms, } diff --git a/typesense_codegen/src/models/update_documents_200_response.rs b/typesense_codegen/src/models/update_documents_200_response.rs index 9791d42..0259776 100644 --- a/typesense_codegen/src/models/update_documents_200_response.rs +++ b/typesense_codegen/src/models/update_documents_200_response.rs @@ -11,7 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct UpdateDocuments200Response { /// The number of documents that have been updated #[serde(rename = "num_updated")] @@ -19,7 +19,7 @@ pub struct UpdateDocuments200Response { } impl UpdateDocuments200Response { - pub fn new(num_updated: i32) -> UpdateDocuments200Response { + pub fn new(num_updated: i32) -> UpdateDocuments200Response{ UpdateDocuments200Response { num_updated, } diff --git a/typesense_codegen/src/models/update_documents_parameters.rs b/typesense_codegen/src/models/update_documents_parameters.rs index 6e48b68..04d3226 100644 --- a/typesense_codegen/src/models/update_documents_parameters.rs +++ b/typesense_codegen/src/models/update_documents_parameters.rs @@ -11,14 +11,14 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct UpdateDocumentsParameters { #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] pub filter_by: Option, } impl UpdateDocumentsParameters { - pub fn new() -> UpdateDocumentsParameters { + pub fn new() -> UpdateDocumentsParameters{ UpdateDocumentsParameters { filter_by: None, } diff --git a/typesense_codegen/src/models/voice_query_model_collection_config.rs b/typesense_codegen/src/models/voice_query_model_collection_config.rs index ca623f5..4835158 100644 --- a/typesense_codegen/src/models/voice_query_model_collection_config.rs +++ b/typesense_codegen/src/models/voice_query_model_collection_config.rs @@ -12,7 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; /// VoiceQueryModelCollectionConfig : Configuration for the voice query model -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct VoiceQueryModelCollectionConfig { #[serde(rename = "model_name", skip_serializing_if = "Option::is_none")] pub model_name: Option, @@ -20,7 +20,7 @@ pub struct VoiceQueryModelCollectionConfig { impl VoiceQueryModelCollectionConfig { /// Configuration for the voice query model - pub fn new() -> VoiceQueryModelCollectionConfig { + pub fn new() -> VoiceQueryModelCollectionConfig{ VoiceQueryModelCollectionConfig { model_name: None, } From 5dc2593a68c328e7dc1a44560059a43635b76073 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Mon, 1 Sep 2025 14:47:18 +0700 Subject: [PATCH 03/41] feat: `x-rust-return-type`to override generated API methods' return type fix: missing generic in impl block --- custom-templates/model.mustache | 18 +++++----- custom-templates/reqwest/api.mustache | 16 ++------- openapi.yml | 9 ++++- preprocessed_openapi.yml | 9 ++++- typesense/src/client/collection/document.rs | 2 +- typesense/src/client/collection/documents.rs | 33 ++++++++++--------- typesense/src/client/collections.rs | 18 ++++++---- typesense_codegen/src/apis/documents_api.rs | 2 +- .../src/models/multi_search_result.rs | 8 ++--- .../src/models/multi_search_result_item.rs | 8 ++--- .../src/models/scoped_key_parameters.rs | 30 ----------------- .../src/models/search_grouped_hit.rs | 8 ++--- typesense_codegen/src/models/search_result.rs | 2 +- 13 files changed, 73 insertions(+), 90 deletions(-) delete mode 100644 typesense_codegen/src/models/scoped_key_parameters.rs diff --git a/custom-templates/model.mustache b/custom-templates/model.mustache index bad954a..a6ce2a0 100644 --- a/custom-templates/model.mustache +++ b/custom-templates/model.mustache @@ -160,20 +160,22 @@ impl{{{vendorExtensions.x-rust-generic-parameter}}} {{{classname}}}{{{vendorExte /// {{{.}}} {{/description}} pub fn new({{#requiredVars}}{{{name}}}: {{! - ### Option Start - }}{{#isNullable}}Option<{{/isNullable}}{{! - ### Enums - }}{{#isEnum}}{{#isArray}}{{#uniqueItems}}std::collections::HashSet<{{/uniqueItems}}{{^uniqueItems}}Vec<{{/uniqueItems}}{{/isArray}}{{{enumName}}}{{#isArray}}>{{/isArray}}{{/isEnum}}{{! - ### Non-Enums - }}{{^isEnum}}{{#isByteArray}}Vec{{/isByteArray}}{{^isByteArray}}{{{dataType}}}{{/isByteArray}}{{/isEnum}}{{! - ### Option End - }}{{#isNullable}}>{{/isNullable}}{{! + ### CHANGE 1: If x-rust-type is available for a required var, use it for the parameter type. + }}{{#vendorExtensions.x-rust-type}}{{{.}}}{{/vendorExtensions.x-rust-type}}{{! + ### Fallback to original logic if x-rust-type is not present. + }}{{^vendorExtensions.x-rust-type}}{{#isNullable}}Option<{{/isNullable}}{{#isEnum}}{{#isArray}}{{#uniqueItems}}std::collections::HashSet<{{/uniqueItems}}{{^uniqueItems}}Vec<{{/uniqueItems}}{{/isArray}}{{{enumName}}}{{#isArray}}>{{/isArray}}{{/isEnum}}{{^isEnum}}{{#isByteArray}}Vec{{/isByteArray}}{{^isByteArray}}{{{dataType}}}{{/isByteArray}}{{/isEnum}}{{#isNullable}}>{{/isNullable}}{{/vendorExtensions.x-rust-type}}{{! ### Comma for next arguement }}{{^-last}}, {{/-last}}{{/requiredVars}}) -> {{{classname}}}{{{vendorExtensions.x-rust-generic-parameter}}}{ {{{classname}}} { {{#vars}} {{#vendorExtensions.x-rust-type}} + {{! Differentiate between required and optional fields with x-rust-type.}} + {{#required}} + {{{name}}}, + {{/required}} + {{^required}} {{{name}}}: None, + {{/required}} {{/vendorExtensions.x-rust-type}} {{^vendorExtensions.x-rust-type}} {{{name}}}{{^required}}: None{{/required}}{{#required}}{{#isModel}}{{^avoidBoxedModels}}: {{^isNullable}}Box::new({{{name}}}){{/isNullable}}{{#isNullable}}if let Some(x) = {{{name}}} {Some(Box::new(x))} else {None}{{/isNullable}}{{/avoidBoxedModels}}{{/isModel}}{{/required}}, diff --git a/custom-templates/reqwest/api.mustache b/custom-templates/reqwest/api.mustache index b20b669..04deb84 100644 --- a/custom-templates/reqwest/api.mustache +++ b/custom-templates/reqwest/api.mustache @@ -96,17 +96,7 @@ pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}{{{vendorExtensi ### Params }}params: {{{operationIdCamelCase}}}Params{{/-first}}{{/allParams}}{{! ### Function return type -}}) -> Result<{{! -### Response File Support -}}{{#isResponseFile}}{{#supportAsync}}reqwest::Response{{/supportAsync}}{{^supportAsync}}reqwest::blocking::Response{{/supportAsync}}{{/isResponseFile}}{{! -### Regular Responses -}}{{^isResponseFile}}{{! -### Multi response support -}}{{#supportMultipleResponses}}ResponseContent<{{{operationIdCamelCase}}}Success>{{/supportMultipleResponses}}{{! -### Regular return type -}}{{^supportMultipleResponses}}{{^returnType}}(){{/returnType}}{{{returnType}}}{{{vendorExtensions.x-rust-return-type-generic-parameter}}}{{/supportMultipleResponses}}{{/isResponseFile}}{{! -### Error Type -}}, Error<{{{operationIdCamelCase}}}Error>> { +}}) -> Result<{{#vendorExtensions.x-rust-return-type}}{{{.}}}{{/vendorExtensions.x-rust-return-type}}{{^vendorExtensions.x-rust-return-type}}{{#isResponseFile}}{{#supportAsync}}reqwest::Response{{/supportAsync}}{{^supportAsync}}reqwest::blocking::Response{{/supportAsync}}{{/isResponseFile}}{{^isResponseFile}}{{#supportMultipleResponses}}ResponseContent<{{{operationIdCamelCase}}}Success>{{/supportMultipleResponses}}{{^supportMultipleResponses}}{{^returnType}}(){{/returnType}}{{{returnType}}}{{/supportMultipleResponses}}{{/isResponseFile}}{{/vendorExtensions.x-rust-return-type}}, Error<{{{operationIdCamelCase}}}Error>> { {{/vendorExtensions.x-group-parameters}} {{^vendorExtensions.x-group-parameters}} pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}{{{vendorExtensions.x-rust-operation-generic-parameter}}}(configuration: &configuration::Configuration, {{#allParams}}{{{paramName}}}: {{! @@ -123,7 +113,7 @@ pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}{{{vendorExtensi ### Comma for next arguement }}{{^-last}}, {{/-last}}{{/allParams}}{{! ### Function return type -}}) -> Result<{{! +}}) -> Result<{{#vendorExtensions.x-rust-return-type}}{{{vendorExtensions.x-rust-return-type}}}{{/vendorExtensions.x-rust-return-type}}{{^vendorExtensions.x-rust-return-type}}{{! ### Response File Support }}{{#isResponseFile}}{{#supportAsync}}reqwest::Response{{/supportAsync}}{{^supportAsync}}reqwest::blocking::Response{{/supportAsync}}{{/isResponseFile}}{{! ### Regular Responses @@ -131,7 +121,7 @@ pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}{{{vendorExtensi ### Multi response support }}{{#supportMultipleResponses}}ResponseContent<{{{operationIdCamelCase}}}Success>{{/supportMultipleResponses}}{{! ### Regular return type -}}{{^supportMultipleResponses}}{{^returnType}}(){{/returnType}}{{{returnType}}}{{{vendorExtensions.x-rust-return-type-generic-parameter}}}{{/supportMultipleResponses}}{{/isResponseFile}}{{! +}}{{^supportMultipleResponses}}{{^returnType}}(){{/returnType}}{{{returnType}}}{{{vendorExtensions.x-rust-return-type-generic-parameter}}}{{/supportMultipleResponses}}{{/isResponseFile}}{{/vendorExtensions.x-rust-return-type}}{{! ### Error Type }}, Error<{{{operationIdCamelCase}}}Error>> { {{#allParams.0}} diff --git a/openapi.yml b/openapi.yml index e8b7b73..2fcaec2 100644 --- a/openapi.yml +++ b/openapi.yml @@ -430,7 +430,7 @@ paths: description: Search for documents in a collection that match the search criteria. operationId: searchCollection x-rust-operation-generic-parameter: " serde::Deserialize<'de> + Serialize>" - x-rust-return-type-generic-parameter: "" + x-rust-return-type: "models::SearchResult" parameters: - name: collectionName in: path @@ -1414,6 +1414,7 @@ paths: description: This is especially useful to avoid round-trip network latencies incurred otherwise if each of these requests are sent in separate HTTP requests. You can also use this feature to do a federated search across multiple collections in a single HTTP request. + x-rust-return-type: "serde_json::Value" parameters: - name: multiSearchParameters required: true @@ -2468,6 +2469,7 @@ components: type: array items: $ref: "#/components/schemas/SearchGroupedHit" + x-rust-type: "Option>>" hits: type: array description: The documents that matched the search query @@ -2524,6 +2526,7 @@ components: required: - group_key - hits + x-rust-generic-parameter: "" properties: found: type: integer @@ -2535,6 +2538,7 @@ components: description: The documents that matched the search query items: $ref: "#/components/schemas/SearchResultHit" + x-rust-type: "Vec>" SearchResultHit: type: object x-rust-generic-parameter: "" @@ -2916,6 +2920,7 @@ components: items: $ref: "#/components/schemas/ApiKey" MultiSearchResult: + x-rust-generic-parameter: "" type: object required: - results @@ -2924,9 +2929,11 @@ components: type: array items: $ref: "#/components/schemas/MultiSearchResultItem" + x-rust-type: "Vec>" conversation: $ref: "#/components/schemas/SearchResultConversation" MultiSearchResultItem: + x-rust-generic-parameter: "" allOf: - $ref: "#/components/schemas/SearchResult" - type: object diff --git a/preprocessed_openapi.yml b/preprocessed_openapi.yml index b839943..9efa7fb 100644 --- a/preprocessed_openapi.yml +++ b/preprocessed_openapi.yml @@ -406,7 +406,7 @@ paths: description: Search for documents in a collection that match the search criteria. operationId: searchCollection x-rust-operation-generic-parameter: ' serde::Deserialize<''de> + Serialize>' - x-rust-return-type-generic-parameter: + x-rust-return-type: models::SearchResult parameters: - name: collectionName in: path @@ -1757,6 +1757,7 @@ paths: - documents summary: send multiple search requests in a single HTTP request description: This is especially useful to avoid round-trip network latencies incurred otherwise if each of these requests are sent in separate HTTP requests. You can also use this feature to do a federated search across multiple collections in a single HTTP request. + x-rust-return-type: serde_json::Value parameters: - name: q in: query @@ -3151,6 +3152,7 @@ components: type: array items: $ref: '#/components/schemas/SearchGroupedHit' + x-rust-type: Option>> hits: type: array description: The documents that matched the search query @@ -3207,6 +3209,7 @@ components: required: - group_key - hits + x-rust-generic-parameter: properties: found: type: integer @@ -3218,6 +3221,7 @@ components: description: The documents that matched the search query items: $ref: '#/components/schemas/SearchResultHit' + x-rust-type: Vec> SearchResultHit: type: object x-rust-generic-parameter: @@ -3590,6 +3594,7 @@ components: items: $ref: '#/components/schemas/ApiKey' MultiSearchResult: + x-rust-generic-parameter: type: object required: - results @@ -3598,9 +3603,11 @@ components: type: array items: $ref: '#/components/schemas/MultiSearchResultItem' + x-rust-type: Vec> conversation: $ref: '#/components/schemas/SearchResultConversation' MultiSearchResultItem: + x-rust-generic-parameter: allOf: - $ref: '#/components/schemas/SearchResult' - type: object diff --git a/typesense/src/client/collection/document.rs b/typesense/src/client/collection/document.rs index a8a1e55..bdae743 100644 --- a/typesense/src/client/collection/document.rs +++ b/typesense/src/client/collection/document.rs @@ -13,7 +13,7 @@ use typesense_codegen::{ /// Provides methods for interacting with a single document within a specific Typesense collection. /// -/// This struct is created by calling a method like `client.collection::("collection_name").document("document_id")`. +/// This struct is created by calling a method like `client.collection("collection_name").document("document_id")` or `client.collection_of::("collection_name").document("document_id")`. /// The generic `T` represents the shape of the document and must implement `Serialize` and `DeserializeOwned`. /// If `T` is not specified, it defaults to `serde_json::Value` for schemaless interactions. pub struct Document<'a, T = serde_json::Value> diff --git a/typesense/src/client/collection/documents.rs b/typesense/src/client/collection/documents.rs index 41c8cfd..4476864 100644 --- a/typesense/src/client/collection/documents.rs +++ b/typesense/src/client/collection/documents.rs @@ -132,8 +132,9 @@ where }; self.client - .execute(|config: configuration::Configuration| async move { - documents_api::import_documents(&config, params.clone()).await + .execute(|config: configuration::Configuration| { + let params_for_move = params.clone(); + async move { documents_api::import_documents(&config, params_for_move).await } }) .await } @@ -154,8 +155,9 @@ where }; self.client - .execute(|config: configuration::Configuration| async move { - documents_api::export_documents(&config, params.clone()).await + .execute(|config: configuration::Configuration| { + let params_for_move = params.clone(); + async move { documents_api::export_documents(&config, params_for_move).await } }) .await } @@ -177,8 +179,9 @@ where truncate: params.truncate, }; self.client - .execute(|config: configuration::Configuration| async move { - documents_api::delete_documents(&config, params.clone()).await + .execute(|config: configuration::Configuration| { + let params_for_move = params.clone(); + async move { documents_api::delete_documents(&config, params_for_move).await } }) .await } @@ -200,8 +203,9 @@ where body: document, }; self.client - .execute(|config: configuration::Configuration| async move { - documents_api::update_documents(&config, params.clone()).await + .execute(|config: configuration::Configuration| { + let params_for_move = params.clone(); + async move { documents_api::update_documents(&config, params_for_move).await } }) .await } @@ -292,14 +296,11 @@ where synonym_sets: params.synonym_sets, }; - let raw_result = self - .client - .execute(|config: configuration::Configuration| async move { - documents_api::search_collection(&config, params.clone()).await + self.client + .execute(|config: configuration::Configuration| { + let params_for_move = search_params.clone(); + async move { documents_api::search_collection(&config, params_for_move).await } }) - .await?; - - // Transform the raw API result into our generic, typed SearchResult. - SearchResult::from_raw(raw_result).map_err(Error::from) + .await } } diff --git a/typesense/src/client/collections.rs b/typesense/src/client/collections.rs index 3087107..c66e3cd 100644 --- a/typesense/src/client/collections.rs +++ b/typesense/src/client/collections.rs @@ -4,7 +4,10 @@ use crate::{Client, Error}; use typesense_codegen::{ - apis::{collections_api, configuration}, + apis::{ + collections_api::{self, GetCollectionsParams}, + configuration, + }, models::{self, GetCollectionsParameters}, }; @@ -20,6 +23,7 @@ impl<'a> Collections<'a> { pub(super) fn new(client: &'a Client) -> Self { Self { client } } + // --- Collection-Specific Methods --- /// Creates a new collection with the given schema. /// @@ -37,8 +41,9 @@ impl<'a> Collections<'a> { }; self.client - .execute(|config: configuration::Configuration| async move { - collections_api::create_collection(&config, params.clone()).await + .execute(|config: configuration::Configuration| { + let params_for_move = params.clone(); + async move { collections_api::create_collection(&config, params_for_move).await } }) .await } @@ -49,11 +54,12 @@ impl<'a> Collections<'a> { /// recent collections appearing first. pub async fn retrieve( &self, - params: &GetCollectionsParameters, + params: &GetCollectionsParams, ) -> Result, Error> { self.client - .execute(|config: configuration::Configuration| async move { - collections_api::get_collections(&config, params.clone()).await + .execute(|config: configuration::Configuration| { + let params_for_move = params.clone(); + async move { collections_api::get_collections(&config, params_for_move).await } }) .await } diff --git a/typesense_codegen/src/apis/documents_api.rs b/typesense_codegen/src/apis/documents_api.rs index 7985003..a11935e 100644 --- a/typesense_codegen/src/apis/documents_api.rs +++ b/typesense_codegen/src/apis/documents_api.rs @@ -836,7 +836,7 @@ pub async fn index_document(configuration: &configuration::Configuration, params } /// This is especially useful to avoid round-trip network latencies incurred otherwise if each of these requests are sent in separate HTTP requests. You can also use this feature to do a federated search across multiple collections in a single HTTP request. -pub async fn multi_search(configuration: &configuration::Configuration, params: MultiSearchParams) -> Result> { +pub async fn multi_search(configuration: &configuration::Configuration, params: MultiSearchParams) -> Result> { let uri_str = format!("{}/multi_search", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); diff --git a/typesense_codegen/src/models/multi_search_result.rs b/typesense_codegen/src/models/multi_search_result.rs index f263930..ebcd319 100644 --- a/typesense_codegen/src/models/multi_search_result.rs +++ b/typesense_codegen/src/models/multi_search_result.rs @@ -12,15 +12,15 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -pub struct MultiSearchResult { +pub struct MultiSearchResult { #[serde(rename = "results")] - pub results: Vec, + pub results: Vec>, #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] pub conversation: Option>, } -impl MultiSearchResult { - pub fn new(results: Vec) -> MultiSearchResult{ +impl MultiSearchResult { + pub fn new(results: Vec>) -> MultiSearchResult{ MultiSearchResult { results, conversation: None, diff --git a/typesense_codegen/src/models/multi_search_result_item.rs b/typesense_codegen/src/models/multi_search_result_item.rs index 945a1c3..c19ae28 100644 --- a/typesense_codegen/src/models/multi_search_result_item.rs +++ b/typesense_codegen/src/models/multi_search_result_item.rs @@ -12,7 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -pub struct MultiSearchResultItem { +pub struct MultiSearchResultItem { #[serde(rename = "facet_counts", skip_serializing_if = "Option::is_none")] pub facet_counts: Option>, /// The number of documents found @@ -33,7 +33,7 @@ pub struct MultiSearchResultItem { #[serde(rename = "page", skip_serializing_if = "Option::is_none")] pub page: Option, #[serde(rename = "grouped_hits", skip_serializing_if = "Option::is_none")] - pub grouped_hits: Option>, + pub grouped_hits: Option>>, /// The documents that matched the search query #[serde(rename = "hits", skip_serializing_if = "Option::is_none")] pub hits: Option>>, @@ -52,8 +52,8 @@ pub struct MultiSearchResultItem { pub error: Option, } -impl MultiSearchResultItem { - pub fn new() -> MultiSearchResultItem{ +impl MultiSearchResultItem { + pub fn new() -> MultiSearchResultItem{ MultiSearchResultItem { facet_counts: None, found: None, diff --git a/typesense_codegen/src/models/scoped_key_parameters.rs b/typesense_codegen/src/models/scoped_key_parameters.rs deleted file mode 100644 index 62a11af..0000000 --- a/typesense_codegen/src/models/scoped_key_parameters.rs +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Typesense API - * - * An open source search engine for building delightful search experiences. - * - * The version of the OpenAPI document: 28.0 - * - * Generated by: https://openapi-generator.tech - */ - -use crate::models; -use serde::{Deserialize, Serialize}; - -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct ScopedKeyParameters { - #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] - pub filter_by: Option, - #[serde(rename = "expires_at", skip_serializing_if = "Option::is_none")] - pub expires_at: Option, -} - -impl ScopedKeyParameters { - pub fn new() -> ScopedKeyParameters { - ScopedKeyParameters { - filter_by: None, - expires_at: None, - } - } -} - diff --git a/typesense_codegen/src/models/search_grouped_hit.rs b/typesense_codegen/src/models/search_grouped_hit.rs index 3d7394c..daffa7f 100644 --- a/typesense_codegen/src/models/search_grouped_hit.rs +++ b/typesense_codegen/src/models/search_grouped_hit.rs @@ -12,18 +12,18 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -pub struct SearchGroupedHit { +pub struct SearchGroupedHit { #[serde(rename = "found", skip_serializing_if = "Option::is_none")] pub found: Option, #[serde(rename = "group_key")] pub group_key: Vec, /// The documents that matched the search query #[serde(rename = "hits")] - pub hits: Vec, + pub hits: Vec>, } -impl SearchGroupedHit { - pub fn new(group_key: Vec, hits: Vec) -> SearchGroupedHit{ +impl SearchGroupedHit { + pub fn new(group_key: Vec, hits: Vec>) -> SearchGroupedHit{ SearchGroupedHit { found: None, group_key, diff --git a/typesense_codegen/src/models/search_result.rs b/typesense_codegen/src/models/search_result.rs index 6712dae..c76f450 100644 --- a/typesense_codegen/src/models/search_result.rs +++ b/typesense_codegen/src/models/search_result.rs @@ -33,7 +33,7 @@ pub struct SearchResult { #[serde(rename = "page", skip_serializing_if = "Option::is_none")] pub page: Option, #[serde(rename = "grouped_hits", skip_serializing_if = "Option::is_none")] - pub grouped_hits: Option>, + pub grouped_hits: Option>>, /// The documents that matched the search query #[serde(rename = "hits", skip_serializing_if = "Option::is_none")] pub hits: Option>>, From 54feb1172e013be0ecca7dceaac80ba437f0dfa3 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Mon, 1 Sep 2025 22:54:12 +0700 Subject: [PATCH 04/41] feat: bon builder string into conversion --- custom-templates/model.mustache | 1 + typesense/Cargo.toml | 4 ++-- typesense_codegen/src/models/analytics_event.rs | 1 + .../src/models/analytics_event_create_response.rs | 1 + typesense_codegen/src/models/analytics_event_data.rs | 1 + typesense_codegen/src/models/analytics_events_response.rs | 1 + .../src/models/analytics_events_response_events_inner.rs | 1 + typesense_codegen/src/models/analytics_rule.rs | 1 + typesense_codegen/src/models/analytics_rule_create.rs | 1 + typesense_codegen/src/models/analytics_rule_create_params.rs | 1 + typesense_codegen/src/models/analytics_rule_update.rs | 1 + typesense_codegen/src/models/analytics_status.rs | 1 + typesense_codegen/src/models/api_key.rs | 1 + typesense_codegen/src/models/api_key_delete_response.rs | 1 + typesense_codegen/src/models/api_key_schema.rs | 1 + typesense_codegen/src/models/api_keys_response.rs | 1 + typesense_codegen/src/models/api_response.rs | 1 + typesense_codegen/src/models/api_stats_response.rs | 1 + typesense_codegen/src/models/collection_alias.rs | 1 + typesense_codegen/src/models/collection_alias_schema.rs | 1 + typesense_codegen/src/models/collection_aliases_response.rs | 1 + typesense_codegen/src/models/collection_response.rs | 1 + typesense_codegen/src/models/collection_schema.rs | 1 + typesense_codegen/src/models/collection_update_schema.rs | 1 + .../src/models/conversation_model_create_schema.rs | 1 + typesense_codegen/src/models/conversation_model_schema.rs | 1 + .../src/models/conversation_model_update_schema.rs | 1 + .../models/create_analytics_rule_200_response_one_of_inner.rs | 1 + .../create_analytics_rule_200_response_one_of_inner_any_of.rs | 1 + typesense_codegen/src/models/debug_200_response.rs | 1 + typesense_codegen/src/models/delete_documents_200_response.rs | 1 + typesense_codegen/src/models/delete_documents_parameters.rs | 1 + .../src/models/delete_stopwords_set_200_response.rs | 1 + typesense_codegen/src/models/export_documents_parameters.rs | 1 + typesense_codegen/src/models/facet_counts.rs | 1 + typesense_codegen/src/models/facet_counts_counts_inner.rs | 1 + typesense_codegen/src/models/facet_counts_stats.rs | 1 + typesense_codegen/src/models/field.rs | 1 + typesense_codegen/src/models/field_embed.rs | 1 + typesense_codegen/src/models/field_embed_model_config.rs | 1 + typesense_codegen/src/models/get_collections_parameters.rs | 1 + typesense_codegen/src/models/health_status.rs | 1 + typesense_codegen/src/models/import_documents_parameters.rs | 1 + .../src/models/list_stemming_dictionaries_200_response.rs | 1 + .../src/models/multi_search_collection_parameters.rs | 1 + typesense_codegen/src/models/multi_search_parameters.rs | 1 + typesense_codegen/src/models/multi_search_result.rs | 1 + typesense_codegen/src/models/multi_search_result_item.rs | 1 + .../src/models/multi_search_searches_parameter.rs | 1 + typesense_codegen/src/models/nl_search_model_base.rs | 1 + typesense_codegen/src/models/nl_search_model_create_schema.rs | 1 + typesense_codegen/src/models/nl_search_model_delete_schema.rs | 1 + typesense_codegen/src/models/nl_search_model_schema.rs | 1 + typesense_codegen/src/models/preset_delete_schema.rs | 1 + typesense_codegen/src/models/preset_schema.rs | 1 + typesense_codegen/src/models/preset_upsert_schema.rs | 1 + typesense_codegen/src/models/presets_retrieve_schema.rs | 1 + typesense_codegen/src/models/schema_change_status.rs | 1 + typesense_codegen/src/models/search_grouped_hit.rs | 1 + typesense_codegen/src/models/search_highlight.rs | 1 + typesense_codegen/src/models/search_override.rs | 1 + .../src/models/search_override_delete_response.rs | 1 + typesense_codegen/src/models/search_override_exclude.rs | 1 + typesense_codegen/src/models/search_override_include.rs | 1 + typesense_codegen/src/models/search_override_rule.rs | 1 + typesense_codegen/src/models/search_override_schema.rs | 1 + typesense_codegen/src/models/search_overrides_response.rs | 1 + typesense_codegen/src/models/search_parameters.rs | 1 + typesense_codegen/src/models/search_request_params.rs | 1 + .../src/models/search_request_params_voice_query.rs | 1 + typesense_codegen/src/models/search_result.rs | 1 + typesense_codegen/src/models/search_result_conversation.rs | 1 + typesense_codegen/src/models/search_result_hit.rs | 1 + .../src/models/search_result_hit_hybrid_search_info.rs | 1 + .../src/models/search_result_hit_text_match_info.rs | 1 + typesense_codegen/src/models/search_synonym.rs | 1 + .../src/models/search_synonym_delete_response.rs | 1 + typesense_codegen/src/models/search_synonym_schema.rs | 1 + typesense_codegen/src/models/search_synonyms_response.rs | 1 + typesense_codegen/src/models/stemming_dictionary.rs | 1 + .../src/models/stemming_dictionary_words_inner.rs | 1 + typesense_codegen/src/models/stopwords_set_retrieve_schema.rs | 1 + typesense_codegen/src/models/stopwords_set_schema.rs | 1 + typesense_codegen/src/models/stopwords_set_upsert_schema.rs | 1 + .../src/models/stopwords_sets_retrieve_all_schema.rs | 1 + typesense_codegen/src/models/success_status.rs | 1 + typesense_codegen/src/models/synonym_item_schema.rs | 1 + typesense_codegen/src/models/synonym_set_create_schema.rs | 1 + typesense_codegen/src/models/synonym_set_delete_schema.rs | 1 + typesense_codegen/src/models/synonym_set_schema.rs | 1 + typesense_codegen/src/models/synonym_sets_retrieve_schema.rs | 1 + .../src/models/toggle_slow_request_log_request.rs | 1 + typesense_codegen/src/models/update_documents_200_response.rs | 1 + typesense_codegen/src/models/update_documents_parameters.rs | 1 + .../src/models/voice_query_model_collection_config.rs | 1 + 95 files changed, 96 insertions(+), 2 deletions(-) diff --git a/custom-templates/model.mustache b/custom-templates/model.mustache index a6ce2a0..b72f188 100644 --- a/custom-templates/model.mustache +++ b/custom-templates/model.mustache @@ -123,6 +123,7 @@ impl Default for {{classname}} { {{^discriminator}} {{#vendorExtensions.x-rust-has-byte-array}}#[serde_as] {{/vendorExtensions.x-rust-has-byte-array}}{{#oneOf.isEmpty}}#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct {{{classname}}}{{{vendorExtensions.x-rust-generic-parameter}}} { {{#vars}} {{#description}} diff --git a/typesense/Cargo.toml b/typesense/Cargo.toml index 479f3a1..f64cc64 100644 --- a/typesense/Cargo.toml +++ b/typesense/Cargo.toml @@ -64,5 +64,5 @@ path = "tests/derive/lib.rs" required-features = ["derive"] [[test]] -name = "api_tests" -path = "tests/api/lib.rs" +name = "client" +path = "tests/client/mod.rs" \ No newline at end of file diff --git a/typesense_codegen/src/models/analytics_event.rs b/typesense_codegen/src/models/analytics_event.rs index 77d28e8..c02ad1a 100644 --- a/typesense_codegen/src/models/analytics_event.rs +++ b/typesense_codegen/src/models/analytics_event.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct AnalyticsEvent { /// Name of the analytics rule this event corresponds to #[serde(rename = "name")] diff --git a/typesense_codegen/src/models/analytics_event_create_response.rs b/typesense_codegen/src/models/analytics_event_create_response.rs index 21e97c1..db9a23b 100644 --- a/typesense_codegen/src/models/analytics_event_create_response.rs +++ b/typesense_codegen/src/models/analytics_event_create_response.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct AnalyticsEventCreateResponse { #[serde(rename = "ok")] pub ok: bool, diff --git a/typesense_codegen/src/models/analytics_event_data.rs b/typesense_codegen/src/models/analytics_event_data.rs index fd2a1fa..c9434be 100644 --- a/typesense_codegen/src/models/analytics_event_data.rs +++ b/typesense_codegen/src/models/analytics_event_data.rs @@ -13,6 +13,7 @@ use serde::{Deserialize, Serialize}; /// AnalyticsEventData : Event payload #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct AnalyticsEventData { #[serde(rename = "user_id", skip_serializing_if = "Option::is_none")] pub user_id: Option, diff --git a/typesense_codegen/src/models/analytics_events_response.rs b/typesense_codegen/src/models/analytics_events_response.rs index 3f98363..85a68d8 100644 --- a/typesense_codegen/src/models/analytics_events_response.rs +++ b/typesense_codegen/src/models/analytics_events_response.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct AnalyticsEventsResponse { #[serde(rename = "events")] pub events: Vec, diff --git a/typesense_codegen/src/models/analytics_events_response_events_inner.rs b/typesense_codegen/src/models/analytics_events_response_events_inner.rs index 82c4e77..d090aac 100644 --- a/typesense_codegen/src/models/analytics_events_response_events_inner.rs +++ b/typesense_codegen/src/models/analytics_events_response_events_inner.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct AnalyticsEventsResponseEventsInner { #[serde(rename = "name", skip_serializing_if = "Option::is_none")] pub name: Option, diff --git a/typesense_codegen/src/models/analytics_rule.rs b/typesense_codegen/src/models/analytics_rule.rs index a02a000..eba704a 100644 --- a/typesense_codegen/src/models/analytics_rule.rs +++ b/typesense_codegen/src/models/analytics_rule.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct AnalyticsRule { #[serde(rename = "name")] pub name: String, diff --git a/typesense_codegen/src/models/analytics_rule_create.rs b/typesense_codegen/src/models/analytics_rule_create.rs index 47b31ca..fe494b2 100644 --- a/typesense_codegen/src/models/analytics_rule_create.rs +++ b/typesense_codegen/src/models/analytics_rule_create.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct AnalyticsRuleCreate { #[serde(rename = "name")] pub name: String, diff --git a/typesense_codegen/src/models/analytics_rule_create_params.rs b/typesense_codegen/src/models/analytics_rule_create_params.rs index 17e5a8e..116cac7 100644 --- a/typesense_codegen/src/models/analytics_rule_create_params.rs +++ b/typesense_codegen/src/models/analytics_rule_create_params.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct AnalyticsRuleCreateParams { #[serde(rename = "destination_collection", skip_serializing_if = "Option::is_none")] pub destination_collection: Option, diff --git a/typesense_codegen/src/models/analytics_rule_update.rs b/typesense_codegen/src/models/analytics_rule_update.rs index b5f0edc..c5a393f 100644 --- a/typesense_codegen/src/models/analytics_rule_update.rs +++ b/typesense_codegen/src/models/analytics_rule_update.rs @@ -13,6 +13,7 @@ use serde::{Deserialize, Serialize}; /// AnalyticsRuleUpdate : Fields allowed to update on an analytics rule #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct AnalyticsRuleUpdate { #[serde(rename = "name", skip_serializing_if = "Option::is_none")] pub name: Option, diff --git a/typesense_codegen/src/models/analytics_status.rs b/typesense_codegen/src/models/analytics_status.rs index 6522e2b..c160da3 100644 --- a/typesense_codegen/src/models/analytics_status.rs +++ b/typesense_codegen/src/models/analytics_status.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct AnalyticsStatus { #[serde(rename = "popular_prefix_queries", skip_serializing_if = "Option::is_none")] pub popular_prefix_queries: Option, diff --git a/typesense_codegen/src/models/api_key.rs b/typesense_codegen/src/models/api_key.rs index 1899c71..fe95571 100644 --- a/typesense_codegen/src/models/api_key.rs +++ b/typesense_codegen/src/models/api_key.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct ApiKey { #[serde(rename = "value", skip_serializing_if = "Option::is_none")] pub value: Option, diff --git a/typesense_codegen/src/models/api_key_delete_response.rs b/typesense_codegen/src/models/api_key_delete_response.rs index b64efd9..36bef3f 100644 --- a/typesense_codegen/src/models/api_key_delete_response.rs +++ b/typesense_codegen/src/models/api_key_delete_response.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct ApiKeyDeleteResponse { /// The id of the API key that was deleted #[serde(rename = "id")] diff --git a/typesense_codegen/src/models/api_key_schema.rs b/typesense_codegen/src/models/api_key_schema.rs index 6c9b2ca..a0fed21 100644 --- a/typesense_codegen/src/models/api_key_schema.rs +++ b/typesense_codegen/src/models/api_key_schema.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct ApiKeySchema { #[serde(rename = "value", skip_serializing_if = "Option::is_none")] pub value: Option, diff --git a/typesense_codegen/src/models/api_keys_response.rs b/typesense_codegen/src/models/api_keys_response.rs index a59d99c..ec1c0b2 100644 --- a/typesense_codegen/src/models/api_keys_response.rs +++ b/typesense_codegen/src/models/api_keys_response.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct ApiKeysResponse { #[serde(rename = "keys")] pub keys: Vec, diff --git a/typesense_codegen/src/models/api_response.rs b/typesense_codegen/src/models/api_response.rs index e1d2d89..1253278 100644 --- a/typesense_codegen/src/models/api_response.rs +++ b/typesense_codegen/src/models/api_response.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct ApiResponse { #[serde(rename = "message")] pub message: String, diff --git a/typesense_codegen/src/models/api_stats_response.rs b/typesense_codegen/src/models/api_stats_response.rs index f22d203..41b886d 100644 --- a/typesense_codegen/src/models/api_stats_response.rs +++ b/typesense_codegen/src/models/api_stats_response.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct ApiStatsResponse { #[serde(rename = "delete_latency_ms", skip_serializing_if = "Option::is_none")] pub delete_latency_ms: Option, diff --git a/typesense_codegen/src/models/collection_alias.rs b/typesense_codegen/src/models/collection_alias.rs index 0e33f6c..a3b22b7 100644 --- a/typesense_codegen/src/models/collection_alias.rs +++ b/typesense_codegen/src/models/collection_alias.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct CollectionAlias { /// Name of the collection alias #[serde(rename = "name")] diff --git a/typesense_codegen/src/models/collection_alias_schema.rs b/typesense_codegen/src/models/collection_alias_schema.rs index cbebb2c..a2946d4 100644 --- a/typesense_codegen/src/models/collection_alias_schema.rs +++ b/typesense_codegen/src/models/collection_alias_schema.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct CollectionAliasSchema { /// Name of the collection you wish to map the alias to #[serde(rename = "collection_name")] diff --git a/typesense_codegen/src/models/collection_aliases_response.rs b/typesense_codegen/src/models/collection_aliases_response.rs index 87a5838..a74e69c 100644 --- a/typesense_codegen/src/models/collection_aliases_response.rs +++ b/typesense_codegen/src/models/collection_aliases_response.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct CollectionAliasesResponse { #[serde(rename = "aliases")] pub aliases: Vec, diff --git a/typesense_codegen/src/models/collection_response.rs b/typesense_codegen/src/models/collection_response.rs index b63e0f6..00442c2 100644 --- a/typesense_codegen/src/models/collection_response.rs +++ b/typesense_codegen/src/models/collection_response.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct CollectionResponse { /// Name of the collection #[serde(rename = "name")] diff --git a/typesense_codegen/src/models/collection_schema.rs b/typesense_codegen/src/models/collection_schema.rs index c5c8706..9640c6f 100644 --- a/typesense_codegen/src/models/collection_schema.rs +++ b/typesense_codegen/src/models/collection_schema.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct CollectionSchema { /// Name of the collection #[serde(rename = "name")] diff --git a/typesense_codegen/src/models/collection_update_schema.rs b/typesense_codegen/src/models/collection_update_schema.rs index 8ff200f..9abcce6 100644 --- a/typesense_codegen/src/models/collection_update_schema.rs +++ b/typesense_codegen/src/models/collection_update_schema.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct CollectionUpdateSchema { /// A list of fields for querying, filtering and faceting #[serde(rename = "fields")] diff --git a/typesense_codegen/src/models/conversation_model_create_schema.rs b/typesense_codegen/src/models/conversation_model_create_schema.rs index 9beecf2..327a757 100644 --- a/typesense_codegen/src/models/conversation_model_create_schema.rs +++ b/typesense_codegen/src/models/conversation_model_create_schema.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct ConversationModelCreateSchema { /// An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. #[serde(rename = "id", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/conversation_model_schema.rs b/typesense_codegen/src/models/conversation_model_schema.rs index 1afda04..92cf6c6 100644 --- a/typesense_codegen/src/models/conversation_model_schema.rs +++ b/typesense_codegen/src/models/conversation_model_schema.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct ConversationModelSchema { /// An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. #[serde(rename = "id")] diff --git a/typesense_codegen/src/models/conversation_model_update_schema.rs b/typesense_codegen/src/models/conversation_model_update_schema.rs index d1b9902..98d710a 100644 --- a/typesense_codegen/src/models/conversation_model_update_schema.rs +++ b/typesense_codegen/src/models/conversation_model_update_schema.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct ConversationModelUpdateSchema { /// An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. #[serde(rename = "id", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs index 7c0dedf..7b72e4b 100644 --- a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs +++ b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct CreateAnalyticsRule200ResponseOneOfInner { #[serde(rename = "name")] pub name: String, diff --git a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs index 5b86508..126d313 100644 --- a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs +++ b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct CreateAnalyticsRule200ResponseOneOfInnerAnyOf { #[serde(rename = "error", skip_serializing_if = "Option::is_none")] pub error: Option, diff --git a/typesense_codegen/src/models/debug_200_response.rs b/typesense_codegen/src/models/debug_200_response.rs index a2377e0..2032659 100644 --- a/typesense_codegen/src/models/debug_200_response.rs +++ b/typesense_codegen/src/models/debug_200_response.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct Debug200Response { #[serde(rename = "version", skip_serializing_if = "Option::is_none")] pub version: Option, diff --git a/typesense_codegen/src/models/delete_documents_200_response.rs b/typesense_codegen/src/models/delete_documents_200_response.rs index 7754da2..4d9f208 100644 --- a/typesense_codegen/src/models/delete_documents_200_response.rs +++ b/typesense_codegen/src/models/delete_documents_200_response.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct DeleteDocuments200Response { #[serde(rename = "num_deleted")] pub num_deleted: i32, diff --git a/typesense_codegen/src/models/delete_documents_parameters.rs b/typesense_codegen/src/models/delete_documents_parameters.rs index b506c2f..972005c 100644 --- a/typesense_codegen/src/models/delete_documents_parameters.rs +++ b/typesense_codegen/src/models/delete_documents_parameters.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct DeleteDocumentsParameters { #[serde(rename = "filter_by")] pub filter_by: String, diff --git a/typesense_codegen/src/models/delete_stopwords_set_200_response.rs b/typesense_codegen/src/models/delete_stopwords_set_200_response.rs index 50fa78f..2d9bf3a 100644 --- a/typesense_codegen/src/models/delete_stopwords_set_200_response.rs +++ b/typesense_codegen/src/models/delete_stopwords_set_200_response.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct DeleteStopwordsSet200Response { #[serde(rename = "id")] pub id: String, diff --git a/typesense_codegen/src/models/export_documents_parameters.rs b/typesense_codegen/src/models/export_documents_parameters.rs index 6f819fc..fbf8b61 100644 --- a/typesense_codegen/src/models/export_documents_parameters.rs +++ b/typesense_codegen/src/models/export_documents_parameters.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct ExportDocumentsParameters { /// Filter conditions for refining your search results. Separate multiple conditions with &&. #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/facet_counts.rs b/typesense_codegen/src/models/facet_counts.rs index 4eea304..b48c6cf 100644 --- a/typesense_codegen/src/models/facet_counts.rs +++ b/typesense_codegen/src/models/facet_counts.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct FacetCounts { #[serde(rename = "counts", skip_serializing_if = "Option::is_none")] pub counts: Option>, diff --git a/typesense_codegen/src/models/facet_counts_counts_inner.rs b/typesense_codegen/src/models/facet_counts_counts_inner.rs index 83c07ae..fc5f6ff 100644 --- a/typesense_codegen/src/models/facet_counts_counts_inner.rs +++ b/typesense_codegen/src/models/facet_counts_counts_inner.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct FacetCountsCountsInner { #[serde(rename = "count", skip_serializing_if = "Option::is_none")] pub count: Option, diff --git a/typesense_codegen/src/models/facet_counts_stats.rs b/typesense_codegen/src/models/facet_counts_stats.rs index 49efaa6..b54f770 100644 --- a/typesense_codegen/src/models/facet_counts_stats.rs +++ b/typesense_codegen/src/models/facet_counts_stats.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct FacetCountsStats { #[serde(rename = "max", skip_serializing_if = "Option::is_none")] pub max: Option, diff --git a/typesense_codegen/src/models/field.rs b/typesense_codegen/src/models/field.rs index 5bad06d..0d367af 100644 --- a/typesense_codegen/src/models/field.rs +++ b/typesense_codegen/src/models/field.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct Field { #[serde(rename = "name")] pub name: String, diff --git a/typesense_codegen/src/models/field_embed.rs b/typesense_codegen/src/models/field_embed.rs index 4c9db90..628bfc3 100644 --- a/typesense_codegen/src/models/field_embed.rs +++ b/typesense_codegen/src/models/field_embed.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct FieldEmbed { #[serde(rename = "from")] pub from: Vec, diff --git a/typesense_codegen/src/models/field_embed_model_config.rs b/typesense_codegen/src/models/field_embed_model_config.rs index 1c15907..92fe3fe 100644 --- a/typesense_codegen/src/models/field_embed_model_config.rs +++ b/typesense_codegen/src/models/field_embed_model_config.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct FieldEmbedModelConfig { #[serde(rename = "model_name")] pub model_name: String, diff --git a/typesense_codegen/src/models/get_collections_parameters.rs b/typesense_codegen/src/models/get_collections_parameters.rs index 3b420ef..198ec45 100644 --- a/typesense_codegen/src/models/get_collections_parameters.rs +++ b/typesense_codegen/src/models/get_collections_parameters.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct GetCollectionsParameters { /// Comma-separated list of fields from the collection to exclude from the response #[serde(rename = "exclude_fields", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/health_status.rs b/typesense_codegen/src/models/health_status.rs index baf20eb..7ee44c8 100644 --- a/typesense_codegen/src/models/health_status.rs +++ b/typesense_codegen/src/models/health_status.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct HealthStatus { #[serde(rename = "ok")] pub ok: bool, diff --git a/typesense_codegen/src/models/import_documents_parameters.rs b/typesense_codegen/src/models/import_documents_parameters.rs index ced47b9..ad6f325 100644 --- a/typesense_codegen/src/models/import_documents_parameters.rs +++ b/typesense_codegen/src/models/import_documents_parameters.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct ImportDocumentsParameters { #[serde(rename = "batch_size", skip_serializing_if = "Option::is_none")] pub batch_size: Option, diff --git a/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs b/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs index 8d7ae85..8934aa6 100644 --- a/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs +++ b/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct ListStemmingDictionaries200Response { #[serde(rename = "dictionaries", skip_serializing_if = "Option::is_none")] pub dictionaries: Option>, diff --git a/typesense_codegen/src/models/multi_search_collection_parameters.rs b/typesense_codegen/src/models/multi_search_collection_parameters.rs index bc3df6e..fba4310 100644 --- a/typesense_codegen/src/models/multi_search_collection_parameters.rs +++ b/typesense_codegen/src/models/multi_search_collection_parameters.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct MultiSearchCollectionParameters { /// The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. #[serde(rename = "q", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/multi_search_parameters.rs b/typesense_codegen/src/models/multi_search_parameters.rs index 7d6d8c5..ef4651d 100644 --- a/typesense_codegen/src/models/multi_search_parameters.rs +++ b/typesense_codegen/src/models/multi_search_parameters.rs @@ -13,6 +13,7 @@ use serde::{Deserialize, Serialize}; /// MultiSearchParameters : Parameters for the multi search API. #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct MultiSearchParameters { /// The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. #[serde(rename = "q", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/multi_search_result.rs b/typesense_codegen/src/models/multi_search_result.rs index ebcd319..e8e07cd 100644 --- a/typesense_codegen/src/models/multi_search_result.rs +++ b/typesense_codegen/src/models/multi_search_result.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct MultiSearchResult { #[serde(rename = "results")] pub results: Vec>, diff --git a/typesense_codegen/src/models/multi_search_result_item.rs b/typesense_codegen/src/models/multi_search_result_item.rs index c19ae28..99f9936 100644 --- a/typesense_codegen/src/models/multi_search_result_item.rs +++ b/typesense_codegen/src/models/multi_search_result_item.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct MultiSearchResultItem { #[serde(rename = "facet_counts", skip_serializing_if = "Option::is_none")] pub facet_counts: Option>, diff --git a/typesense_codegen/src/models/multi_search_searches_parameter.rs b/typesense_codegen/src/models/multi_search_searches_parameter.rs index 0141ba6..91878e9 100644 --- a/typesense_codegen/src/models/multi_search_searches_parameter.rs +++ b/typesense_codegen/src/models/multi_search_searches_parameter.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct MultiSearchSearchesParameter { /// When true, merges the search results from each search query into a single ordered set of hits. #[serde(rename = "union", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/nl_search_model_base.rs b/typesense_codegen/src/models/nl_search_model_base.rs index 570233a..596c740 100644 --- a/typesense_codegen/src/models/nl_search_model_base.rs +++ b/typesense_codegen/src/models/nl_search_model_base.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct NlSearchModelBase { /// Name of the NL model to use #[serde(rename = "model_name", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/nl_search_model_create_schema.rs b/typesense_codegen/src/models/nl_search_model_create_schema.rs index 5816e8a..880c084 100644 --- a/typesense_codegen/src/models/nl_search_model_create_schema.rs +++ b/typesense_codegen/src/models/nl_search_model_create_schema.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct NlSearchModelCreateSchema { /// Name of the NL model to use #[serde(rename = "model_name", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/nl_search_model_delete_schema.rs b/typesense_codegen/src/models/nl_search_model_delete_schema.rs index 92fac03..cf5912a 100644 --- a/typesense_codegen/src/models/nl_search_model_delete_schema.rs +++ b/typesense_codegen/src/models/nl_search_model_delete_schema.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct NlSearchModelDeleteSchema { /// ID of the deleted NL search model #[serde(rename = "id")] diff --git a/typesense_codegen/src/models/nl_search_model_schema.rs b/typesense_codegen/src/models/nl_search_model_schema.rs index 7ebf85b..4d9b126 100644 --- a/typesense_codegen/src/models/nl_search_model_schema.rs +++ b/typesense_codegen/src/models/nl_search_model_schema.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct NlSearchModelSchema { /// Name of the NL model to use #[serde(rename = "model_name", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/preset_delete_schema.rs b/typesense_codegen/src/models/preset_delete_schema.rs index 12e794d..4d93986 100644 --- a/typesense_codegen/src/models/preset_delete_schema.rs +++ b/typesense_codegen/src/models/preset_delete_schema.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct PresetDeleteSchema { #[serde(rename = "name")] pub name: String, diff --git a/typesense_codegen/src/models/preset_schema.rs b/typesense_codegen/src/models/preset_schema.rs index b7fb354..9b4eb95 100644 --- a/typesense_codegen/src/models/preset_schema.rs +++ b/typesense_codegen/src/models/preset_schema.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct PresetSchema { #[serde(rename = "value")] pub value: Box, diff --git a/typesense_codegen/src/models/preset_upsert_schema.rs b/typesense_codegen/src/models/preset_upsert_schema.rs index 70c66e6..1ccb101 100644 --- a/typesense_codegen/src/models/preset_upsert_schema.rs +++ b/typesense_codegen/src/models/preset_upsert_schema.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct PresetUpsertSchema { #[serde(rename = "value")] pub value: Box, diff --git a/typesense_codegen/src/models/presets_retrieve_schema.rs b/typesense_codegen/src/models/presets_retrieve_schema.rs index 6828efc..b1f1b0b 100644 --- a/typesense_codegen/src/models/presets_retrieve_schema.rs +++ b/typesense_codegen/src/models/presets_retrieve_schema.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct PresetsRetrieveSchema { #[serde(rename = "presets")] pub presets: Vec, diff --git a/typesense_codegen/src/models/schema_change_status.rs b/typesense_codegen/src/models/schema_change_status.rs index 86fb7ff..c0414d9 100644 --- a/typesense_codegen/src/models/schema_change_status.rs +++ b/typesense_codegen/src/models/schema_change_status.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct SchemaChangeStatus { /// Name of the collection being modified #[serde(rename = "collection", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/search_grouped_hit.rs b/typesense_codegen/src/models/search_grouped_hit.rs index daffa7f..e74cd76 100644 --- a/typesense_codegen/src/models/search_grouped_hit.rs +++ b/typesense_codegen/src/models/search_grouped_hit.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct SearchGroupedHit { #[serde(rename = "found", skip_serializing_if = "Option::is_none")] pub found: Option, diff --git a/typesense_codegen/src/models/search_highlight.rs b/typesense_codegen/src/models/search_highlight.rs index 2975151..aefa1eb 100644 --- a/typesense_codegen/src/models/search_highlight.rs +++ b/typesense_codegen/src/models/search_highlight.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct SearchHighlight { #[serde(rename = "field", skip_serializing_if = "Option::is_none")] pub field: Option, diff --git a/typesense_codegen/src/models/search_override.rs b/typesense_codegen/src/models/search_override.rs index 518dc7b..006d556 100644 --- a/typesense_codegen/src/models/search_override.rs +++ b/typesense_codegen/src/models/search_override.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct SearchOverride { #[serde(rename = "rule")] pub rule: Box, diff --git a/typesense_codegen/src/models/search_override_delete_response.rs b/typesense_codegen/src/models/search_override_delete_response.rs index cc0973d..b89be93 100644 --- a/typesense_codegen/src/models/search_override_delete_response.rs +++ b/typesense_codegen/src/models/search_override_delete_response.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct SearchOverrideDeleteResponse { /// The id of the override that was deleted #[serde(rename = "id")] diff --git a/typesense_codegen/src/models/search_override_exclude.rs b/typesense_codegen/src/models/search_override_exclude.rs index eff124a..f4a0c24 100644 --- a/typesense_codegen/src/models/search_override_exclude.rs +++ b/typesense_codegen/src/models/search_override_exclude.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct SearchOverrideExclude { /// document id that should be excluded from the search results. #[serde(rename = "id")] diff --git a/typesense_codegen/src/models/search_override_include.rs b/typesense_codegen/src/models/search_override_include.rs index 2e993ee..56f3fc8 100644 --- a/typesense_codegen/src/models/search_override_include.rs +++ b/typesense_codegen/src/models/search_override_include.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct SearchOverrideInclude { /// document id that should be included #[serde(rename = "id")] diff --git a/typesense_codegen/src/models/search_override_rule.rs b/typesense_codegen/src/models/search_override_rule.rs index 4372a10..9985d30 100644 --- a/typesense_codegen/src/models/search_override_rule.rs +++ b/typesense_codegen/src/models/search_override_rule.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct SearchOverrideRule { /// List of tag values to associate with this override rule. #[serde(rename = "tags", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/search_override_schema.rs b/typesense_codegen/src/models/search_override_schema.rs index b3be39f..0463084 100644 --- a/typesense_codegen/src/models/search_override_schema.rs +++ b/typesense_codegen/src/models/search_override_schema.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct SearchOverrideSchema { #[serde(rename = "rule")] pub rule: Box, diff --git a/typesense_codegen/src/models/search_overrides_response.rs b/typesense_codegen/src/models/search_overrides_response.rs index e9f9296..b888bfa 100644 --- a/typesense_codegen/src/models/search_overrides_response.rs +++ b/typesense_codegen/src/models/search_overrides_response.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct SearchOverridesResponse { #[serde(rename = "overrides")] pub overrides: Vec, diff --git a/typesense_codegen/src/models/search_parameters.rs b/typesense_codegen/src/models/search_parameters.rs index 60aa8e4..a7253d5 100644 --- a/typesense_codegen/src/models/search_parameters.rs +++ b/typesense_codegen/src/models/search_parameters.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct SearchParameters { /// The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. #[serde(rename = "q", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/search_request_params.rs b/typesense_codegen/src/models/search_request_params.rs index 246a7e4..0b0dcd1 100644 --- a/typesense_codegen/src/models/search_request_params.rs +++ b/typesense_codegen/src/models/search_request_params.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct SearchRequestParams { #[serde(rename = "collection_name")] pub collection_name: String, diff --git a/typesense_codegen/src/models/search_request_params_voice_query.rs b/typesense_codegen/src/models/search_request_params_voice_query.rs index 88545d7..5afcd97 100644 --- a/typesense_codegen/src/models/search_request_params_voice_query.rs +++ b/typesense_codegen/src/models/search_request_params_voice_query.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct SearchRequestParamsVoiceQuery { #[serde(rename = "transcribed_query", skip_serializing_if = "Option::is_none")] pub transcribed_query: Option, diff --git a/typesense_codegen/src/models/search_result.rs b/typesense_codegen/src/models/search_result.rs index c76f450..303ec88 100644 --- a/typesense_codegen/src/models/search_result.rs +++ b/typesense_codegen/src/models/search_result.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct SearchResult { #[serde(rename = "facet_counts", skip_serializing_if = "Option::is_none")] pub facet_counts: Option>, diff --git a/typesense_codegen/src/models/search_result_conversation.rs b/typesense_codegen/src/models/search_result_conversation.rs index 88d3659..5e7e124 100644 --- a/typesense_codegen/src/models/search_result_conversation.rs +++ b/typesense_codegen/src/models/search_result_conversation.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct SearchResultConversation { #[serde(rename = "answer")] pub answer: String, diff --git a/typesense_codegen/src/models/search_result_hit.rs b/typesense_codegen/src/models/search_result_hit.rs index 26b1afd..7ce8215 100644 --- a/typesense_codegen/src/models/search_result_hit.rs +++ b/typesense_codegen/src/models/search_result_hit.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct SearchResultHit { /// (Deprecated) Contains highlighted portions of the search fields #[serde(rename = "highlights", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs b/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs index 8ac7d1b..e675e57 100644 --- a/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs +++ b/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs @@ -13,6 +13,7 @@ use serde::{Deserialize, Serialize}; /// SearchResultHitHybridSearchInfo : Information about hybrid search scoring #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct SearchResultHitHybridSearchInfo { /// Combined score from rank fusion of text and vector search #[serde(rename = "rank_fusion_score", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/search_result_hit_text_match_info.rs b/typesense_codegen/src/models/search_result_hit_text_match_info.rs index 6ee4bc4..89cb80f 100644 --- a/typesense_codegen/src/models/search_result_hit_text_match_info.rs +++ b/typesense_codegen/src/models/search_result_hit_text_match_info.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct SearchResultHitTextMatchInfo { #[serde(rename = "best_field_score", skip_serializing_if = "Option::is_none")] pub best_field_score: Option, diff --git a/typesense_codegen/src/models/search_synonym.rs b/typesense_codegen/src/models/search_synonym.rs index 6ee65d6..5dcbb5c 100644 --- a/typesense_codegen/src/models/search_synonym.rs +++ b/typesense_codegen/src/models/search_synonym.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct SearchSynonym { /// For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. #[serde(rename = "root", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/search_synonym_delete_response.rs b/typesense_codegen/src/models/search_synonym_delete_response.rs index 9610a90..6bb092f 100644 --- a/typesense_codegen/src/models/search_synonym_delete_response.rs +++ b/typesense_codegen/src/models/search_synonym_delete_response.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct SearchSynonymDeleteResponse { /// The id of the synonym that was deleted #[serde(rename = "id")] diff --git a/typesense_codegen/src/models/search_synonym_schema.rs b/typesense_codegen/src/models/search_synonym_schema.rs index be1d4c5..08db709 100644 --- a/typesense_codegen/src/models/search_synonym_schema.rs +++ b/typesense_codegen/src/models/search_synonym_schema.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct SearchSynonymSchema { /// For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. #[serde(rename = "root", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/search_synonyms_response.rs b/typesense_codegen/src/models/search_synonyms_response.rs index fbc4a7b..82d93b0 100644 --- a/typesense_codegen/src/models/search_synonyms_response.rs +++ b/typesense_codegen/src/models/search_synonyms_response.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct SearchSynonymsResponse { #[serde(rename = "synonyms")] pub synonyms: Vec, diff --git a/typesense_codegen/src/models/stemming_dictionary.rs b/typesense_codegen/src/models/stemming_dictionary.rs index bbf5866..978d4c0 100644 --- a/typesense_codegen/src/models/stemming_dictionary.rs +++ b/typesense_codegen/src/models/stemming_dictionary.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct StemmingDictionary { /// Unique identifier for the dictionary #[serde(rename = "id")] diff --git a/typesense_codegen/src/models/stemming_dictionary_words_inner.rs b/typesense_codegen/src/models/stemming_dictionary_words_inner.rs index c82be83..88a2b83 100644 --- a/typesense_codegen/src/models/stemming_dictionary_words_inner.rs +++ b/typesense_codegen/src/models/stemming_dictionary_words_inner.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct StemmingDictionaryWordsInner { /// The word form to be stemmed #[serde(rename = "word")] diff --git a/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs b/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs index 6cc7f80..b1a1934 100644 --- a/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs +++ b/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct StopwordsSetRetrieveSchema { #[serde(rename = "stopwords")] pub stopwords: Box, diff --git a/typesense_codegen/src/models/stopwords_set_schema.rs b/typesense_codegen/src/models/stopwords_set_schema.rs index 686e23f..01049b1 100644 --- a/typesense_codegen/src/models/stopwords_set_schema.rs +++ b/typesense_codegen/src/models/stopwords_set_schema.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct StopwordsSetSchema { #[serde(rename = "id")] pub id: String, diff --git a/typesense_codegen/src/models/stopwords_set_upsert_schema.rs b/typesense_codegen/src/models/stopwords_set_upsert_schema.rs index 7460d90..0e98ef1 100644 --- a/typesense_codegen/src/models/stopwords_set_upsert_schema.rs +++ b/typesense_codegen/src/models/stopwords_set_upsert_schema.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct StopwordsSetUpsertSchema { #[serde(rename = "stopwords")] pub stopwords: Vec, diff --git a/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs b/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs index bf58071..8cab67c 100644 --- a/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs +++ b/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct StopwordsSetsRetrieveAllSchema { #[serde(rename = "stopwords")] pub stopwords: Vec, diff --git a/typesense_codegen/src/models/success_status.rs b/typesense_codegen/src/models/success_status.rs index d2ebbf2..c27ffe7 100644 --- a/typesense_codegen/src/models/success_status.rs +++ b/typesense_codegen/src/models/success_status.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct SuccessStatus { #[serde(rename = "success")] pub success: bool, diff --git a/typesense_codegen/src/models/synonym_item_schema.rs b/typesense_codegen/src/models/synonym_item_schema.rs index b47c770..c21afad 100644 --- a/typesense_codegen/src/models/synonym_item_schema.rs +++ b/typesense_codegen/src/models/synonym_item_schema.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct SynonymItemSchema { /// Unique identifier for the synonym item #[serde(rename = "id")] diff --git a/typesense_codegen/src/models/synonym_set_create_schema.rs b/typesense_codegen/src/models/synonym_set_create_schema.rs index 5946102..0f3d0ee 100644 --- a/typesense_codegen/src/models/synonym_set_create_schema.rs +++ b/typesense_codegen/src/models/synonym_set_create_schema.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct SynonymSetCreateSchema { /// Array of synonym items #[serde(rename = "items")] diff --git a/typesense_codegen/src/models/synonym_set_delete_schema.rs b/typesense_codegen/src/models/synonym_set_delete_schema.rs index 114a46f..1b142df 100644 --- a/typesense_codegen/src/models/synonym_set_delete_schema.rs +++ b/typesense_codegen/src/models/synonym_set_delete_schema.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct SynonymSetDeleteSchema { /// Name of the deleted synonym set #[serde(rename = "name")] diff --git a/typesense_codegen/src/models/synonym_set_schema.rs b/typesense_codegen/src/models/synonym_set_schema.rs index 57883d9..dea8b9b 100644 --- a/typesense_codegen/src/models/synonym_set_schema.rs +++ b/typesense_codegen/src/models/synonym_set_schema.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct SynonymSetSchema { /// Array of synonym items #[serde(rename = "items")] diff --git a/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs b/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs index f2c7fd9..c43a073 100644 --- a/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs +++ b/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct SynonymSetsRetrieveSchema { /// Array of synonym sets #[serde(rename = "synonym_sets")] diff --git a/typesense_codegen/src/models/toggle_slow_request_log_request.rs b/typesense_codegen/src/models/toggle_slow_request_log_request.rs index de499ad..282ddb2 100644 --- a/typesense_codegen/src/models/toggle_slow_request_log_request.rs +++ b/typesense_codegen/src/models/toggle_slow_request_log_request.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct ToggleSlowRequestLogRequest { #[serde(rename = "log-slow-requests-time-ms")] pub log_slow_requests_time_ms: i32, diff --git a/typesense_codegen/src/models/update_documents_200_response.rs b/typesense_codegen/src/models/update_documents_200_response.rs index 0259776..ec87fff 100644 --- a/typesense_codegen/src/models/update_documents_200_response.rs +++ b/typesense_codegen/src/models/update_documents_200_response.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct UpdateDocuments200Response { /// The number of documents that have been updated #[serde(rename = "num_updated")] diff --git a/typesense_codegen/src/models/update_documents_parameters.rs b/typesense_codegen/src/models/update_documents_parameters.rs index 04d3226..5735f53 100644 --- a/typesense_codegen/src/models/update_documents_parameters.rs +++ b/typesense_codegen/src/models/update_documents_parameters.rs @@ -12,6 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct UpdateDocumentsParameters { #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] pub filter_by: Option, diff --git a/typesense_codegen/src/models/voice_query_model_collection_config.rs b/typesense_codegen/src/models/voice_query_model_collection_config.rs index 4835158..dbab78f 100644 --- a/typesense_codegen/src/models/voice_query_model_collection_config.rs +++ b/typesense_codegen/src/models/voice_query_model_collection_config.rs @@ -13,6 +13,7 @@ use serde::{Deserialize, Serialize}; /// VoiceQueryModelCollectionConfig : Configuration for the voice query model #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[builder(on(String, into))] pub struct VoiceQueryModelCollectionConfig { #[serde(rename = "model_name", skip_serializing_if = "Option::is_none")] pub model_name: Option, From 935073549d6005d5beb6aba97996c31f6b2cc6fb Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Mon, 1 Sep 2025 22:54:33 +0700 Subject: [PATCH 05/41] feat: multi-node client --- typesense/src/builders/mod.rs | 13 - .../multi_search_collection_parameters.rs | 265 ------------- .../src/builders/multi_search_parameters.rs | 260 ------------ .../multi_search_searches_parameters.rs | 127 ------ typesense/src/client/collection/document.rs | 5 +- typesense/src/client/collections.rs | 8 +- typesense/src/lib.rs | 2 - .../src/models/document_index_parameters.rs | 3 + typesense/src/models/mod.rs | 7 +- typesense/src/models/multi_search.rs | 121 +++++- typesense/tests/client/client_test.rs | 322 +++++++++++++++ typesense/tests/client/collections_test.rs | 164 ++++++++ typesense/tests/client/documents_test.rs | 374 ++++++++++++++++++ typesense/tests/client/keys_test.rs | 144 +++++++ typesense/tests/client/mod.rs | 41 ++ typesense/tests/derive/collection.rs | 2 +- typesense_derive/src/lib.rs | 18 +- 17 files changed, 1183 insertions(+), 693 deletions(-) delete mode 100644 typesense/src/builders/mod.rs delete mode 100644 typesense/src/builders/multi_search_collection_parameters.rs delete mode 100644 typesense/src/builders/multi_search_parameters.rs delete mode 100644 typesense/src/builders/multi_search_searches_parameters.rs create mode 100644 typesense/tests/client/client_test.rs create mode 100644 typesense/tests/client/collections_test.rs create mode 100644 typesense/tests/client/documents_test.rs create mode 100644 typesense/tests/client/keys_test.rs create mode 100644 typesense/tests/client/mod.rs diff --git a/typesense/src/builders/mod.rs b/typesense/src/builders/mod.rs deleted file mode 100644 index 662b21e..0000000 --- a/typesense/src/builders/mod.rs +++ /dev/null @@ -1,13 +0,0 @@ -//! Contain convenient builders for Typesense schemas. - -mod multi_search_collection_parameters; -mod multi_search_parameters; -mod multi_search_searches_parameters; - -pub use multi_search_collection_parameters::{ - MultiSearchCollectionParametersBuilder, new_multi_search_collection_parameters, -}; -pub use multi_search_parameters::{MultiSearchParametersBuilder, new_multi_search_parameters}; -pub use multi_search_searches_parameters::{ - MultiSearchSearchesParameterBuilder, new_multi_search_searches_parameter, -}; diff --git a/typesense/src/builders/multi_search_collection_parameters.rs b/typesense/src/builders/multi_search_collection_parameters.rs deleted file mode 100644 index 5cad599..0000000 --- a/typesense/src/builders/multi_search_collection_parameters.rs +++ /dev/null @@ -1,265 +0,0 @@ -//! Module for the `MultiSearchCollectionParameters` builder. - -use crate::models::{DropTokensMode, MultiSearchCollectionParameters}; -use bon::builder; - -/// Creates a new [`MultiSearchCollectionParameters`] builder. -/// -/// This builder helps construct an individual search query for a multi-search request. -/// All parameters are optional. -#[builder( - // expose a public builder type and a public finish_fn - builder_type(name = MultiSearchCollectionParametersBuilder, vis = "pub"), - finish_fn(name = build, vis = "pub"), - // allow passing &str into String params - on(String, into) -)] -pub fn new_multi_search_collection_parameters( - /// The collection to search in. - collection: Option, - /// The query text to search for in the collection. - q: Option, - /// A list of `string` fields that should be queried against. - query_by: Option, - /// The relative weight to give each `query_by` field when ranking results. - query_by_weights: Option, - /// How the representative text match score is calculated. - text_match_type: Option, - /// Indicates if the last word in the query should be treated as a prefix. - prefix: Option, - /// Infix search configuration. Can be `off`, `always`, or `fallback`. - infix: Option, - /// Maximum number of extra symbols before a query token for infix searching. - max_extra_prefix: Option, - /// Maximum number of extra symbols after a query token for infix searching. - max_extra_suffix: Option, - /// Filter conditions for refining search results. - filter_by: Option, - /// A list of fields and their sort orders. - sort_by: Option, - /// A list of fields to facet by. - facet_by: Option, - /// Maximum number of facet values to be returned. - max_facet_values: Option, - /// A query to filter facet values. - facet_query: Option, - /// The number of typographical errors (1 or 2) that would be tolerated. - num_typos: Option, - /// The page number to fetch. - page: Option, - /// Number of results to fetch per page. - per_page: Option, - /// Number of hits to fetch. - limit: Option, - /// The starting point of the result set. - offset: Option, - /// Fields to group results by. - group_by: Option, - /// Maximum number of hits to return for every group. - group_limit: Option, - /// Whether to group documents with null values in the `group_by` field. - group_missing_values: Option, - /// List of fields to include in the search result. - include_fields: Option, - /// List of fields to exclude from the search result. - exclude_fields: Option, - /// List of fields which should be highlighted fully. - highlight_full_fields: Option, - /// The number of tokens surrounding the highlighted text. - highlight_affix_num_tokens: Option, - /// The start tag for highlighted snippets. - highlight_start_tag: Option, - /// The end tag for highlighted snippets. - highlight_end_tag: Option, - /// Field values under this length will be fully highlighted. - snippet_threshold: Option, - /// Threshold for dropping query tokens to find more results. - drop_tokens_threshold: Option, - drop_tokens_mode: Option, - /// Threshold for trying more typos to find more results. - typo_tokens_threshold: Option, - /// Whether to enable typos on alphanumerical tokens. - enable_typos_for_alpha_numerical_tokens: Option, - /// Whether the `filter_by` condition applies to curated results. - filter_curated_hits: Option, - /// Whether to enable synonyms for the query. - enable_synonyms: Option, - /// Allow synonym resolution on word prefixes. - synonym_prefix: Option, - /// Number of typos allowed for synonym resolution. - synonym_num_typos: Option, - /// A list of records to unconditionally include at specific positions. - pinned_hits: Option, - /// A list of records to unconditionally hide from search results. - hidden_hits: Option, - /// Comma-separated list of tags to trigger curation rules. - override_tags: Option, - /// A list of custom fields that must be highlighted. - highlight_fields: Option, - /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same - pre_segmented_query: Option, - /// Search using a preset of search parameters. - preset: Option, - /// Whether to enable overrides for the query. - enable_overrides: Option, - /// Whether to prioritize an exact match. - prioritize_exact_match: Option, - /// Prioritize documents where query words appear earlier in the text. - prioritize_token_position: Option, - /// Prioritize documents where query words appear in more fields. - prioritize_num_matching_fields: Option, - /// Disable typos for numerical tokens. - enable_typos_for_numerical_tokens: Option, - /// Whether to perform an exhaustive search. - exhaustive_search: Option, - /// Search cutoff time in milliseconds. - search_cutoff_ms: Option, - /// Enable server-side caching of search results. - use_cache: Option, - /// The TTL for the search query cache. - cache_ttl: Option, - /// Minimum word length for 1-typo correction. - min_len_1typo: Option, - /// Minimum word length for 2-typo correction. - min_len_2typo: Option, - /// Vector query expression. - vector_query: Option, - /// Timeout for fetching remote embeddings. - remote_embedding_timeout_ms: Option, - /// Number of retries for fetching remote embeddings. - remote_embedding_num_tries: Option, - /// The underlying faceting strategy to use. - facet_strategy: Option, - /// Name of the stopwords set to apply for this search. - stopwords: Option, - /// Nested facet fields whose parent object should be returned. - facet_return_parent: Option, - /// The base64 encoded audio file. - voice_query: Option, - /// Enable conversational search. - conversation: Option, - /// The ID of the Conversation Model to use. - conversation_model_id: Option, - /// The ID of a previous conversation to continue. - conversation_id: Option, - /// A separate search API key for this specific search. - x_typesense_api_key: Option, - /// When true, computes both text match and vector distance scores for all matches in hybrid search. - rerank_hybrid_matches: Option, -) -> MultiSearchCollectionParameters { - MultiSearchCollectionParameters { - collection, - q, - query_by, - query_by_weights, - text_match_type, - prefix, - infix, - max_extra_prefix, - max_extra_suffix, - filter_by, - sort_by, - facet_by, - max_facet_values, - facet_query, - num_typos, - page, - per_page, - limit, - offset, - group_by, - group_limit, - group_missing_values, - include_fields, - exclude_fields, - highlight_full_fields, - highlight_affix_num_tokens, - highlight_start_tag, - highlight_end_tag, - snippet_threshold, - drop_tokens_threshold, - drop_tokens_mode, - typo_tokens_threshold, - enable_typos_for_alpha_numerical_tokens, - filter_curated_hits, - enable_synonyms, - synonym_prefix, - synonym_num_typos, - pinned_hits, - hidden_hits, - override_tags, - highlight_fields, - pre_segmented_query, - preset, - enable_overrides, - prioritize_exact_match, - prioritize_token_position, - prioritize_num_matching_fields, - enable_typos_for_numerical_tokens, - exhaustive_search, - search_cutoff_ms, - use_cache, - cache_ttl, - min_len_1typo, - min_len_2typo, - vector_query, - remote_embedding_timeout_ms, - remote_embedding_num_tries, - facet_strategy, - stopwords, - facet_return_parent, - voice_query, - conversation, - conversation_model_id, - conversation_id, - x_typesense_api_key, - rerank_hybrid_matches, - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::models::MultiSearchCollectionParameters; - - #[test] - fn test_multi_search_collection_parameters_builder_basic() { - let built = new_multi_search_collection_parameters() - .collection("products") - .q("phone") - .limit(10) - .build(); - - let expected = MultiSearchCollectionParameters { - collection: Some("products".to_string()), - q: Some("phone".to_string()), - limit: Some(10), - ..Default::default() - }; - - assert_eq!(built, expected); - } - - #[test] - fn test_multi_search_collection_parameters_builder_api_key() { - let built = new_multi_search_collection_parameters() - .collection("private_docs") - .x_typesense_api_key("specific_key_for_this_search") - .build(); - - let expected = MultiSearchCollectionParameters { - collection: Some("private_docs".to_string()), - x_typesense_api_key: Some("specific_key_for_this_search".to_string()), - ..Default::default() - }; - - assert_eq!(built, expected); - } - - #[test] - fn test_multi_search_collection_parameters_builder_defaults() { - let built = new_multi_search_collection_parameters().build(); - let expected = MultiSearchCollectionParameters::default(); - assert_eq!(built, expected); - } -} diff --git a/typesense/src/builders/multi_search_parameters.rs b/typesense/src/builders/multi_search_parameters.rs deleted file mode 100644 index 9375697..0000000 --- a/typesense/src/builders/multi_search_parameters.rs +++ /dev/null @@ -1,260 +0,0 @@ -//! Module for the `MultiSearchParameters` builder. - -use crate::models::{DropTokensMode, MultiSearchParameters}; -use bon::builder; - -/// Creates a new [`MultiSearchParameters`] builder. -/// -/// This builder helps construct a set of common search parameters that can be applied -/// to all search queries within a multi-search request. -#[builder( - // expose a public builder type and a public finish_fn - builder_type(name = MultiSearchParametersBuilder, vis = "pub"), - finish_fn(name = build, vis = "pub"), - // allow passing &str into String params - on(String, into) -)] -pub fn new_multi_search_parameters( - /// The query text to search for in the collection. - q: Option, - /// A list of `string` fields that should be queried against. - query_by: Option, - /// The relative weight to give each `query_by` field when ranking results. - query_by_weights: Option, - /// How the representative text match score is calculated. - text_match_type: Option, - /// Indicates if the last word in the query should be treated as a prefix. - prefix: Option, - /// Infix search configuration. Can be `off`, `always`, or `fallback`. - infix: Option, - /// Maximum number of extra symbols before a query token for infix searching. - max_extra_prefix: Option, - /// Maximum number of extra symbols after a query token for infix searching. - max_extra_suffix: Option, - /// Filter conditions for refining search results. - filter_by: Option, - /// A list of fields and their sort orders. - sort_by: Option, - /// A list of fields to facet by. - facet_by: Option, - /// Maximum number of facet values to be returned. - max_facet_values: Option, - /// A query to filter facet values. - facet_query: Option, - /// The number of typographical errors (1 or 2) that would be tolerated. - num_typos: Option, - /// The page number to fetch. - page: Option, - /// Number of results to fetch per page. - per_page: Option, - /// Number of hits to fetch. - limit: Option, - /// The starting point of the result set. - offset: Option, - /// Fields to group results by. - group_by: Option, - /// Maximum number of hits to return for every group. - group_limit: Option, - /// Whether to group documents with null values in the `group_by` field. - group_missing_values: Option, - /// List of fields to include in the search result. - include_fields: Option, - /// List of fields to exclude from the search result. - exclude_fields: Option, - /// List of fields which should be highlighted fully. - highlight_full_fields: Option, - /// The number of tokens surrounding the highlighted text. - highlight_affix_num_tokens: Option, - /// The start tag for highlighted snippets. - highlight_start_tag: Option, - /// The end tag for highlighted snippets. - highlight_end_tag: Option, - /// Field values under this length will be fully highlighted. - snippet_threshold: Option, - /// Threshold for dropping query tokens to find more results. - drop_tokens_threshold: Option, - drop_tokens_mode: Option, - /// Threshold for trying more typos to find more results. - typo_tokens_threshold: Option, - /// Whether to enable typos on alphanumerical tokens. - enable_typos_for_alpha_numerical_tokens: Option, - /// Whether the `filter_by` condition applies to curated results. - filter_curated_hits: Option, - /// Whether to enable synonyms for the query. - enable_synonyms: Option, - /// Allow synonym resolution on word prefixes. - synonym_prefix: Option, - /// Number of typos allowed for synonym resolution. - synonym_num_typos: Option, - /// A list of records to unconditionally include at specific positions. - pinned_hits: Option, - /// A list of records to unconditionally hide from search results. - hidden_hits: Option, - /// Comma-separated list of tags to trigger curation rules. - override_tags: Option, - /// A list of custom fields that must be highlighted. - highlight_fields: Option, - /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same - pre_segmented_query: Option, - /// Search using a preset of search parameters. - preset: Option, - /// Whether to enable overrides for the query. - enable_overrides: Option, - /// Whether to prioritize an exact match. - prioritize_exact_match: Option, - /// Prioritize documents where query words appear earlier in the text. - prioritize_token_position: Option, - /// Prioritize documents where query words appear in more fields. - prioritize_num_matching_fields: Option, - /// Disable typos for numerical tokens. - enable_typos_for_numerical_tokens: Option, - /// Whether to perform an exhaustive search. - exhaustive_search: Option, - /// Search cutoff time in milliseconds. - search_cutoff_ms: Option, - /// Enable server-side caching of search results. - use_cache: Option, - /// The TTL for the search query cache. - cache_ttl: Option, - /// Minimum word length for 1-typo correction. - min_len_1typo: Option, - /// Minimum word length for 2-typo correction. - min_len_2typo: Option, - /// Vector query expression. - vector_query: Option, - /// Timeout for fetching remote embeddings. - remote_embedding_timeout_ms: Option, - /// Number of retries for fetching remote embeddings. - remote_embedding_num_tries: Option, - /// The underlying faceting strategy to use. - facet_strategy: Option, - /// Name of the stopwords set to apply for this search. - stopwords: Option, - /// Nested facet fields whose parent object should be returned. - facet_return_parent: Option, - /// The base64 encoded audio file. - voice_query: Option, - /// Enable conversational search. - conversation: Option, - /// The ID of the Conversation Model to use. - conversation_model_id: Option, - /// The ID of a previous conversation to continue. - conversation_id: Option, -) -> MultiSearchParameters { - MultiSearchParameters { - q, - query_by, - query_by_weights, - text_match_type, - prefix, - infix, - max_extra_prefix, - max_extra_suffix, - filter_by, - sort_by, - facet_by, - max_facet_values, - facet_query, - num_typos, - page, - per_page, - limit, - offset, - group_by, - group_limit, - group_missing_values, - include_fields, - exclude_fields, - highlight_full_fields, - highlight_affix_num_tokens, - highlight_start_tag, - highlight_end_tag, - snippet_threshold, - drop_tokens_threshold, - drop_tokens_mode, - typo_tokens_threshold, - enable_typos_for_alpha_numerical_tokens, - filter_curated_hits, - enable_synonyms, - synonym_prefix, - synonym_num_typos, - pinned_hits, - hidden_hits, - override_tags, - highlight_fields, - pre_segmented_query, - preset, - enable_overrides, - prioritize_exact_match, - prioritize_token_position, - prioritize_num_matching_fields, - enable_typos_for_numerical_tokens, - exhaustive_search, - search_cutoff_ms, - use_cache, - cache_ttl, - min_len_1typo, - min_len_2typo, - vector_query, - remote_embedding_timeout_ms, - remote_embedding_num_tries, - facet_strategy, - stopwords, - facet_return_parent, - voice_query, - conversation, - conversation_model_id, - conversation_id, - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::models::{DropTokensMode, MultiSearchParameters}; - - #[test] - fn test_multi_search_parameters_builder_basic() { - let built = new_multi_search_parameters() - .query_by("title") - .per_page(5) - .build(); - - let expected = MultiSearchParameters { - query_by: Some("title".to_string()), - per_page: Some(5), - ..Default::default() - }; - - assert_eq!(built, expected); - } - - #[test] - fn test_multi_search_parameters_builder_full() { - let built = new_multi_search_parameters() - .q("*") - .filter_by("category:shoes") - .use_cache(true) - .drop_tokens_mode(DropTokensMode::LeftToRight) - .search_cutoff_ms(100) - .build(); - - let expected = MultiSearchParameters { - q: Some("*".to_string()), - filter_by: Some("category:shoes".to_string()), - use_cache: Some(true), - drop_tokens_mode: Some(DropTokensMode::LeftToRight), - search_cutoff_ms: Some(100), - ..Default::default() - }; - - assert_eq!(built, expected); - } - - #[test] - fn test_multi_search_parameters_builder_defaults() { - let built = new_multi_search_parameters().build(); - let expected = MultiSearchParameters::default(); - assert_eq!(built, expected); - } -} diff --git a/typesense/src/builders/multi_search_searches_parameters.rs b/typesense/src/builders/multi_search_searches_parameters.rs deleted file mode 100644 index 60a3490..0000000 --- a/typesense/src/builders/multi_search_searches_parameters.rs +++ /dev/null @@ -1,127 +0,0 @@ -//! Module for the `MultiSearchSearchesParameter` builder. - -use crate::models::{MultiSearchCollectionParameters, MultiSearchSearchesParameter}; - -/// A builder for creating a `MultiSearchSearchesParameter` object. -/// -/// This builder is used to construct the body of a multi-search request by -/// adding individual search queries one by one. -#[derive(Debug, Default)] -pub struct MultiSearchSearchesParameterBuilder { - searches: Vec, -} - -impl MultiSearchSearchesParameterBuilder { - /// Creates a new, empty builder. - pub fn new() -> Self { - Self::default() - } - - /// Adds a single search query to the multi-search request. - /// - /// # Arguments - /// - /// * `search` - A `MultiSearchCollectionParameters` object representing an - /// individual search query. - pub fn add_search(mut self, search: MultiSearchCollectionParameters) -> Self { - self.searches.push(search); - self - } - - /// Adds multiple search queries to the multi-search request from an iterator. - /// - /// # Arguments - /// - /// * `searches` - An iterator that yields `MultiSearchCollectionParameters` objects. - pub fn add_searches( - mut self, - searches: impl IntoIterator, - ) -> Self { - self.searches.extend(searches); - self - } - - /// Consumes the builder and returns a `MultiSearchSearchesParameter` object. - pub fn build(self) -> MultiSearchSearchesParameter { - MultiSearchSearchesParameter { - searches: self.searches, - } - } -} - -/// Creates a new [`MultiSearchSearchesParameterBuilder`]. -/// -/// This is the entry point for building a multi-search request body. -pub fn new_multi_search_searches_parameter() -> MultiSearchSearchesParameterBuilder { - MultiSearchSearchesParameterBuilder::new() -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::builders::new_multi_search_collection_parameters; - - #[test] - fn test_multi_search_builder_new_is_empty() { - let multi_search_request = new_multi_search_searches_parameter().build(); - assert!(multi_search_request.searches.is_empty()); - } - - #[test] - fn test_multi_search_builder_add_one_search() { - let search1 = new_multi_search_collection_parameters() - .collection("products") - .q("shoe") - .build(); - - let multi_search_request = new_multi_search_searches_parameter() - .add_search(search1.clone()) - .build(); - - assert_eq!(multi_search_request.searches.len(), 1); - assert_eq!(multi_search_request.searches[0], search1); - } - - #[test] - fn test_multi_search_builder_add_multiple_searches_chained() { - let search1 = new_multi_search_collection_parameters() - .collection("products") - .q("shoe") - .build(); - let search2 = new_multi_search_collection_parameters() - .collection("brands") - .q("Nike") - .build(); - - let multi_search_request = new_multi_search_searches_parameter() - .add_search(search1.clone()) - .add_search(search2.clone()) - .build(); - - assert_eq!(multi_search_request.searches.len(), 2); - assert_eq!(multi_search_request.searches[0], search1); - assert_eq!(multi_search_request.searches[1], search2); - } - - #[test] - fn test_multi_search_builder_add_searches_from_iterator() { - let searches_vec = vec![ - new_multi_search_collection_parameters() - .collection("c1") - .build(), - new_multi_search_collection_parameters() - .collection("c2") - .build(), - new_multi_search_collection_parameters() - .collection("c3") - .build(), - ]; - - let multi_search_request = new_multi_search_searches_parameter() - .add_searches(searches_vec.clone()) - .build(); - - assert_eq!(multi_search_request.searches.len(), 3); - assert_eq!(multi_search_request.searches, searches_vec); - } -} diff --git a/typesense/src/client/collection/document.rs b/typesense/src/client/collection/document.rs index bdae743..5d2835b 100644 --- a/typesense/src/client/collection/document.rs +++ b/typesense/src/client/collection/document.rs @@ -6,10 +6,7 @@ use crate::{Client, Error}; use serde::{Serialize, de::DeserializeOwned}; -use typesense_codegen::{ - apis::{configuration, documents_api}, - models, -}; +use typesense_codegen::apis::{configuration, documents_api}; /// Provides methods for interacting with a single document within a specific Typesense collection. /// diff --git a/typesense/src/client/collections.rs b/typesense/src/client/collections.rs index c66e3cd..6654818 100644 --- a/typesense/src/client/collections.rs +++ b/typesense/src/client/collections.rs @@ -54,11 +54,15 @@ impl<'a> Collections<'a> { /// recent collections appearing first. pub async fn retrieve( &self, - params: &GetCollectionsParams, + params: &GetCollectionsParameters, ) -> Result, Error> { self.client .execute(|config: configuration::Configuration| { - let params_for_move = params.clone(); + let params_for_move = GetCollectionsParams { + exclude_fields: params.exclude_fields.clone(), + limit: params.limit, + offset: params.offset, + }; async move { collections_api::get_collections(&config, params_for_move).await } }) .await diff --git a/typesense/src/lib.rs b/typesense/src/lib.rs index 722f658..47b1e06 100644 --- a/typesense/src/lib.rs +++ b/typesense/src/lib.rs @@ -45,12 +45,10 @@ mod client; mod traits; -pub mod builders; pub mod error; pub mod models; pub mod prelude; -pub use builders::*; pub use client::Client; pub use error::*; pub use models::*; diff --git a/typesense/src/models/document_index_parameters.rs b/typesense/src/models/document_index_parameters.rs index 09fb7fe..ae85edd 100644 --- a/typesense/src/models/document_index_parameters.rs +++ b/typesense/src/models/document_index_parameters.rs @@ -1,12 +1,15 @@ use serde::{Deserialize, Serialize}; +/// Specify #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct DocumentIndexParameters { + /// #[serde(rename = "dirty_values", skip_serializing_if = "Option::is_none")] pub dirty_values: Option, } impl DocumentIndexParameters { + /// Creates a new `DocumentIndexParameters`. pub fn new() -> DocumentIndexParameters { DocumentIndexParameters { dirty_values: None } } diff --git a/typesense/src/models/mod.rs b/typesense/src/models/mod.rs index d0fd696..9bfcd7d 100644 --- a/typesense/src/models/mod.rs +++ b/typesense/src/models/mod.rs @@ -3,8 +3,9 @@ mod document_index_parameters; mod multi_search; mod scoped_key_parameters; -pub use document_index_parameters::*; - +pub use document_index_parameters::DocumentIndexParameters; pub use scoped_key_parameters::*; - +pub use typesense_codegen::apis::operations_api::TakeSnapshotParams; pub use typesense_codegen::models::*; + +pub use multi_search::MultiSearchBody; diff --git a/typesense/src/models/multi_search.rs b/typesense/src/models/multi_search.rs index 3e67ccd..355c181 100644 --- a/typesense/src/models/multi_search.rs +++ b/typesense/src/models/multi_search.rs @@ -1,5 +1,6 @@ use crate::models; use serde::{Deserialize, Serialize}; +use typesense_codegen::models::MultiSearchCollectionParameters; /// Represents the body of a multi-search request. /// @@ -7,17 +8,123 @@ use serde::{Deserialize, Serialize}; /// sent to the Typesense multi-search endpoint. Each search query is defined in a /// `MultiSearchCollectionParameters` struct within the `searches` vector. #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct MultiSearchSearchesParameter { +pub struct MultiSearchBody { /// A vector of individual search queries to be executed. The order of the search results returned by Typesense will match the order of these queries. #[serde(rename = "searches")] pub searches: Vec, } -impl MultiSearchSearchesParameter { - /// Creates a new `MultiSearchSearchesParameter` instance. - pub fn new( - searches: Vec, - ) -> MultiSearchSearchesParameter { - MultiSearchSearchesParameter { searches } +impl MultiSearchBody { + /// Creates a new `MultiSearchBody` instance. + pub fn new(searches: Vec) -> MultiSearchBody { + MultiSearchBody { searches } + } +} + +impl MultiSearchBody { + /// Creates a new, empty builder. + pub fn builder() -> Self { + Self::default() + } + + /// Adds a single search query to the multi-search request. + /// + /// # Arguments + /// + /// * `search` - A `MultiSearchCollectionParameters` object representing an + /// individual search query. + pub fn add_search(mut self, search: MultiSearchCollectionParameters) -> Self { + self.searches.push(search); + self + } + + /// Adds multiple search queries to the multi-search request from an iterator. + /// + /// # Arguments + /// + /// * `searches` - An iterator that yields `MultiSearchCollectionParameters` objects. + pub fn add_searches( + mut self, + searches: impl IntoIterator, + ) -> Self { + self.searches.extend(searches); + self + } + + /// Consumes the builder and returns a `MultiSearchBody` object. + pub fn build(self) -> MultiSearchBody { + MultiSearchBody { + searches: self.searches, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::models::MultiSearchCollectionParameters; + + #[test] + fn test_multi_search_builder_new_is_empty() { + let multi_search_request = MultiSearchBody::builder().build(); + assert!(multi_search_request.searches.is_empty()); + } + + #[test] + fn test_multi_search_builder_add_one_search() { + let search1 = MultiSearchCollectionParameters::builder() + .collection("products") + .q("shoe") + .build(); + + let multi_search_request = MultiSearchBody::builder() + .add_search(search1.clone()) + .build(); + + assert_eq!(multi_search_request.searches.len(), 1); + assert_eq!(multi_search_request.searches[0], search1); + } + + #[test] + fn test_multi_search_builder_add_multiple_searches_chained() { + let search1 = MultiSearchCollectionParameters::builder() + .collection("products") + .q("shoe") + .build(); + let search2 = MultiSearchCollectionParameters::builder() + .collection("brands") + .q("Nike") + .build(); + + let multi_search_request = MultiSearchBody::builder() + .add_search(search1.clone()) + .add_search(search2.clone()) + .build(); + + assert_eq!(multi_search_request.searches.len(), 2); + assert_eq!(multi_search_request.searches[0], search1); + assert_eq!(multi_search_request.searches[1], search2); + } + + #[test] + fn test_multi_search_builder_add_searches_from_iterator() { + let searches_vec = vec![ + MultiSearchCollectionParameters::builder() + .collection("c1") + .build(), + MultiSearchCollectionParameters::builder() + .collection("c2") + .build(), + MultiSearchCollectionParameters::builder() + .collection("c3") + .build(), + ]; + + let multi_search_request = MultiSearchBody::builder() + .add_searches(searches_vec.clone()) + .build(); + + assert_eq!(multi_search_request.searches.len(), 3); + assert_eq!(multi_search_request.searches, searches_vec); } } diff --git a/typesense/tests/client/client_test.rs b/typesense/tests/client/client_test.rs new file mode 100644 index 0000000..931d3aa --- /dev/null +++ b/typesense/tests/client/client_test.rs @@ -0,0 +1,322 @@ +#![cfg(not(target_family = "wasm"))] + +use reqwest::Url; +use reqwest_retry::policies::ExponentialBackoff; +use std::time::Duration; +use typesense::models::CollectionResponse; +use typesense::*; +use wiremock::matchers::{header, method, path}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +// Helper to create a mock Typesense server for a successful collection retrieval. +async fn setup_mock_server_ok(server: &MockServer, collection_name: &str) { + let response_body = CollectionResponse { + name: collection_name.to_string(), + ..Default::default() + }; + + Mock::given(method("GET")) + .and(path(format!("/collections/{}", collection_name))) + .and(header("X-TYPESENSE-API-KEY", "test-key")) + .respond_with(ResponseTemplate::new(200).set_body_json(response_body)) + .mount(server) + .await; +} + +// Helper to create a mock Typesense server that returns a server error. +async fn setup_mock_server_503(server: &MockServer, collection_name: &str) { + Mock::given(method("GET")) + .and(path(format!("/collections/{}", collection_name))) + .respond_with(ResponseTemplate::new(503)) + .mount(server) + .await; +} + +// Helper to create a mock Typesense server that returns a 404 Not Found error. +async fn setup_mock_server_404(server: &MockServer, collection_name: &str) { + Mock::given(method("GET")) + .and(path(format!("/collections/{}", collection_name))) + .respond_with(ResponseTemplate::new(404)) + .mount(server) + .await; +} + +// Helper function to create a client configuration for tests. +fn get_client(nodes: Vec, nearest_node: Option) -> Client { + Client::builder() + .nodes(nodes) + .maybe_nearest_node(nearest_node) + .api_key("test-key") + .healthcheck_interval(Duration::from_secs(60)) + .retry_policy(ExponentialBackoff::builder().build_with_max_retries(0)) + .connection_timeout(Duration::from_secs(1)) + .build() + .expect("Failed to create client") +} + +#[tokio::test] +async fn test_success_on_first_node() { + let server1 = MockServer::start().await; + setup_mock_server_ok(&server1, "products").await; + + let client = get_client(vec![Url::parse(&server1.uri()).unwrap()], None); + + let result = client.collection("products").retrieve().await; + + assert!(result.is_ok()); + assert_eq!(result.unwrap().name, "products"); + // Check that the server received exactly one request. + assert_eq!(server1.received_requests().await.unwrap().len(), 1); +} + +#[tokio::test] +async fn test_failover_to_second_node() { + let server1 = MockServer::start().await; + let server2 = MockServer::start().await; + setup_mock_server_503(&server1, "products").await; + setup_mock_server_ok(&server2, "products").await; + + let client = get_client( + vec![ + Url::parse(&server1.uri()).unwrap(), + Url::parse(&server2.uri()).unwrap(), + ], + None, + ); + + let result = client.collection("products").retrieve().await; + assert!(result.is_ok()); + + // The first server should have been tried and failed. + assert_eq!(server1.received_requests().await.unwrap().len(), 1); + // The second server should have been tried and succeeded. + assert_eq!(server2.received_requests().await.unwrap().len(), 1); +} + +#[tokio::test] +async fn test_nearest_node_is_prioritized() { + let nearest_server = MockServer::start().await; + let regular_server = MockServer::start().await; + setup_mock_server_ok(&nearest_server, "products").await; + setup_mock_server_ok(®ular_server, "products").await; + + let client = get_client( + vec![Url::parse(®ular_server.uri()).unwrap()], + Some(Url::parse(&nearest_server.uri()).unwrap()), + ); + + let result = client.collection("products").retrieve().await; + assert!(result.is_ok()); + + // Only the nearest node should have received a request. + assert_eq!(nearest_server.received_requests().await.unwrap().len(), 1); + assert_eq!(regular_server.received_requests().await.unwrap().len(), 0); +} + +#[tokio::test] +async fn test_failover_from_nearest_to_regular_node() { + let nearest_server = MockServer::start().await; + let regular_server = MockServer::start().await; + setup_mock_server_503(&nearest_server, "products").await; + setup_mock_server_ok(®ular_server, "products").await; + + let client = get_client( + vec![Url::parse(®ular_server.uri()).unwrap()], + Some(Url::parse(&nearest_server.uri()).unwrap()), + ); + + let result = client.collection("products").retrieve().await; + assert!(result.is_ok()); + + // Nearest node should have failed. + assert_eq!(nearest_server.received_requests().await.unwrap().len(), 1); + // Regular node should have succeeded. + assert_eq!(regular_server.received_requests().await.unwrap().len(), 1); +} + +#[tokio::test] +async fn test_round_robin_failover() { + let server1 = MockServer::start().await; + let server2 = MockServer::start().await; + let server3 = MockServer::start().await; + setup_mock_server_503(&server1, "products").await; + setup_mock_server_503(&server2, "products").await; + setup_mock_server_ok(&server3, "products").await; + + let client = get_client( + vec![ + Url::parse(&server1.uri()).unwrap(), + Url::parse(&server2.uri()).unwrap(), + Url::parse(&server3.uri()).unwrap(), + ], + None, + ); + + // First request should fail over to the third node + let result = client.collection("products").retrieve().await; + assert!(result.is_ok()); + assert_eq!(server1.received_requests().await.unwrap().len(), 1); + assert_eq!(server2.received_requests().await.unwrap().len(), 1); + assert_eq!(server3.received_requests().await.unwrap().len(), 1); + + // The next request should start from the now-healthy 3rd node, but round-robin + // logic will have advanced the internal counter. Let's see it wrap around. + // We expect the next attempt to be on server 3 again, then 1 (if 3 fails). + + // Reset server 3 to also fail + server3.reset().await; + setup_mock_server_503(&server3, "products").await; + // Make server 1 healthy again + server1.reset().await; + setup_mock_server_ok(&server1, "products").await; + + let result2 = client.collection("products").retrieve().await; + assert!(result2.is_ok()); + + // Server 3 was tried first and failed. + assert_eq!(server3.received_requests().await.unwrap().len(), 1); + // Server 1 was tried next and succeeded. + assert_eq!(server1.received_requests().await.unwrap().len(), 1); + // Server 2 was not touched this time. + assert_eq!(server2.received_requests().await.unwrap().len(), 1); // Remains 1 from first call +} + +#[tokio::test] +async fn test_health_check_and_node_recovery() { + let server1 = MockServer::start().await; + let server2 = MockServer::start().await; + + setup_mock_server_503(&server1, "products").await; + setup_mock_server_ok(&server2, "products").await; + + let client = Client::builder() + .nodes(vec![ + Url::parse(&server1.uri()).unwrap(), + Url::parse(&server2.uri()).unwrap(), + ]) + .api_key("test-key") + .healthcheck_interval(Duration::from_millis(500)) // Use a very short healthcheck interval for the test + .retry_policy(ExponentialBackoff::builder().build_with_max_retries(0)) + .connection_timeout(Duration::from_secs(1)) + .build() + .expect("Failed to create client"); + + // 1. First request fails over to server2, marking server1 as unhealthy. + assert!(client.collection("products").retrieve().await.is_ok()); + assert_eq!(server1.received_requests().await.unwrap().len(), 1); + assert_eq!(server2.received_requests().await.unwrap().len(), 1); + + // 2. Immediate second request should go directly to server2. + assert!(client.collection("products").retrieve().await.is_ok()); + assert_eq!(server1.received_requests().await.unwrap().len(), 1); // No new request + assert_eq!(server2.received_requests().await.unwrap().len(), 2); // Got another request + + // 3. Wait for the healthcheck interval to pass. + tokio::time::sleep(Duration::from_millis(600)).await; + + // 4. Make server1 healthy again. + server1.reset().await; + setup_mock_server_ok(&server1, "products").await; + + // 5. The next request should try server1 again (due to healthcheck expiry) and succeed. + assert!(client.collection("products").retrieve().await.is_ok()); + assert_eq!(server1.received_requests().await.unwrap().len(), 1); // Server 1 received its first successful req + assert_eq!(server2.received_requests().await.unwrap().len(), 2); // No new request for server 2 +} + +#[tokio::test] +async fn test_all_nodes_fail() { + let server1 = MockServer::start().await; + let server2 = MockServer::start().await; + setup_mock_server_503(&server1, "products").await; + setup_mock_server_503(&server2, "products").await; + + let client = get_client( + vec![ + Url::parse(&server1.uri()).unwrap(), + Url::parse(&server2.uri()).unwrap(), + ], + None, + ); + + let result = client.collection("products").retrieve().await; + assert!(result.is_err()); + + match result.err().unwrap() { + Error::AllNodesFailed { .. } => { /* This is the expected outcome */ } + _ => panic!("Expected AllNodesFailed error"), + } + + // Both servers should have been tried. + assert_eq!(server1.received_requests().await.unwrap().len(), 1); + assert_eq!(server2.received_requests().await.unwrap().len(), 1); +} + +#[tokio::test] +async fn test_fail_fast_on_non_retriable_error() { + let server1 = MockServer::start().await; + let server2 = MockServer::start().await; + + setup_mock_server_404(&server1, "products").await; + setup_mock_server_ok(&server2, "products").await; + + let client = get_client( + vec![ + Url::parse(&server1.uri()).unwrap(), + Url::parse(&server2.uri()).unwrap(), + ], + None, + ); + + let result = client.collection("products").retrieve().await; + assert!(result.is_err()); + + // Check that the error is the non-retriable API error. + match result.err().unwrap() { + Error::Api(typesense_codegen::apis::Error::ResponseError(content)) => { + assert_eq!(content.status, reqwest::StatusCode::NOT_FOUND); + } + e => panic!("Expected an API error, but got {:?}", e), + } + + // The first server should have been tried. + assert_eq!(server1.received_requests().await.unwrap().len(), 1); + // The second server should NOT have been tried. + assert_eq!(server2.received_requests().await.unwrap().len(), 0); +} + +#[tokio::test] +async fn test_load_balancing_with_healthy_nodes() { + // 1. Setup three healthy mock servers + let server1 = MockServer::start().await; + let server2 = MockServer::start().await; + let server3 = MockServer::start().await; + setup_mock_server_ok(&server1, "products").await; + setup_mock_server_ok(&server2, "products").await; + setup_mock_server_ok(&server3, "products").await; + + // 2. Setup client with the three nodes + let client = get_client( + vec![ + Url::parse(&server1.uri()).unwrap(), + Url::parse(&server2.uri()).unwrap(), + Url::parse(&server3.uri()).unwrap(), + ], + None, + ); + + // 3. Make three consecutive requests + let result1 = client.collection("products").retrieve().await; + let result2 = client.collection("products").retrieve().await; + let result3 = client.collection("products").retrieve().await; + + // 4. Assert all requests were successful + assert!(result1.is_ok()); + assert!(result2.is_ok()); + assert!(result3.is_ok()); + + // 5. Assert that each server received exactly one request, proving round-robin distribution + assert_eq!(server1.received_requests().await.unwrap().len(), 1); + assert_eq!(server2.received_requests().await.unwrap().len(), 1); + assert_eq!(server3.received_requests().await.unwrap().len(), 1); +} diff --git a/typesense/tests/client/collections_test.rs b/typesense/tests/client/collections_test.rs new file mode 100644 index 0000000..84d3d23 --- /dev/null +++ b/typesense/tests/client/collections_test.rs @@ -0,0 +1,164 @@ +use typesense::{ + GetCollectionsParameters, + models::{CollectionSchema, CollectionUpdateSchema, Field}, +}; +use typesense_codegen::apis::collections_api::GetCollectionParams; + +use super::{get_client, new_id}; + +async fn logic_test_collections_and_collection_lifecycle() { + let client = get_client(); + let collection_name = new_id("products"); + + // --- 1. Create a Collection (via `collections`) --- + let schema = CollectionSchema { + name: collection_name.clone(), + fields: vec![ + Field { + name: "name".to_string(), + r#type: "string".to_string(), + ..Default::default() + }, + Field { + name: "price".to_string(), + r#type: "int32".to_string(), + ..Default::default() + }, + ], + ..Default::default() + }; + + let create_result = client.collections().create(schema).await; + assert!(create_result.is_ok(), "Failed to create collection"); + let created_collection = create_result.unwrap(); + assert_eq!(created_collection.name, collection_name); + + // --- 2. Retrieve the specific Collection (via `collection`) --- + let retrieve_one_result = client.collection(&collection_name).retrieve().await; + assert!( + retrieve_one_result.is_ok(), + "Failed to retrieve the newly created collection." + ); + let retrieved_collection = retrieve_one_result.unwrap(); + assert_eq!(retrieved_collection.name, collection_name); + assert_eq!(retrieved_collection.fields.len(), 2); + + // --- 3. Retrieve all collections (via `collections`) --- + let retrieve_all_result = client + .collections() + .retrieve(&GetCollectionsParameters::default()) + .await; + assert!( + retrieve_all_result.is_ok(), + "Failed to retrieve the list of collections." + ); + let all_collections = retrieve_all_result.unwrap(); + + // --- 4. Find our specific collection within the list --- + let our_collection = all_collections.iter().find(|c| c.name == collection_name); + assert!( + our_collection.is_some(), + "The newly created collection was not found in the list." + ); + + // --- 5. Update the Collection to add and drop a field (via `collection`) --- + let update_schema = CollectionUpdateSchema { + fields: vec![ + // Add a new field + Field { + name: "description".to_string(), + r#type: "string".to_string(), + optional: Some(true), + ..Default::default() + }, + // Drop an existing field + Field { + name: "price".to_string(), + drop: Some(true), + ..Default::default() + }, + ], + ..Default::default() + }; + + let update_result = client + .collection(&collection_name) + .update(update_schema) + .await; + assert!(update_result.is_ok(), "Failed to update collection"); + + // The update response contains the fields that were modified + let updated_fields_response = update_result.unwrap(); + assert_eq!( + updated_fields_response.fields.len(), + 2, + "The update response should contain the two modified fields." + ); + + // --- 6. Verify the update by retrieving the full schema again --- + let retrieve_after_update_result = client.collection(&collection_name).retrieve().await; + let retrieved_after_update = retrieve_after_update_result.unwrap(); + + // Initial fields: name, price. Update: +description, -price. Final fields: name, description. + assert_eq!( + retrieved_after_update.fields.len(), + 2, + "The number of fields should be 2 after the update." + ); + assert!( + retrieved_after_update + .fields + .iter() + .any(|f| f.name == "name"), + "The 'name' field should still exist." + ); + assert!( + retrieved_after_update + .fields + .iter() + .any(|f| f.name == "description"), + "The 'description' field should have been added." + ); + assert!( + !retrieved_after_update + .fields + .iter() + .any(|f| f.name == "price"), + "The 'price' field should have been dropped." + ); + + // --- 7. Delete the Collection (via `collection`) --- + let delete_result = client.collection(&collection_name).delete().await; + assert!(delete_result.is_ok(), "Failed to delete collection"); + + // --- 8. Verify Deletion --- + let get_after_delete_result = client.collection(&collection_name).retrieve().await; + assert!( + get_after_delete_result.is_err(), + "Collection should not exist after deletion" + ); +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tokio_test { + use super::*; + + #[tokio::test] + async fn test_collections_and_collection_lifecycle() { + logic_test_collections_and_collection_lifecycle().await; + } +} + +#[cfg(all(test, target_arch = "wasm32"))] +mod wasm_test { + use super::*; + use wasm_bindgen_test::wasm_bindgen_test; + + wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser); + + #[wasm_bindgen_test] + async fn test_collections_and_collection_lifecycle() { + console_error_panic_hook::set_once(); + logic_test_collections_and_collection_lifecycle().await; + } +} diff --git a/typesense/tests/client/documents_test.rs b/typesense/tests/client/documents_test.rs new file mode 100644 index 0000000..8d94fc9 --- /dev/null +++ b/typesense/tests/client/documents_test.rs @@ -0,0 +1,374 @@ +use serde::{Deserialize, Serialize}; +use serde_json::json; +use typesense::models::{ + CollectionSchema, DeleteDocumentsParameters, DirtyValues, DocumentIndexParameters, + ExportDocumentsParameters, Field, ImportDocumentsParameters, IndexAction, SearchParameters, + UpdateDocumentsParameters, +}; + +use super::{get_client, new_id}; + +async fn run_test_document_lifecycle() { + let client = get_client(); + let collection_name = new_id("books"); + + // --- 1. Setup: Create a Collection --- + let schema = CollectionSchema { + name: collection_name.clone(), + fields: vec![ + Field { + name: "title".to_string(), + r#type: "string".to_string(), + ..Default::default() + }, + Field { + name: "author".to_string(), + r#type: "string".to_string(), + facet: Some(true), + ..Default::default() + }, + Field { + name: "publication_year".to_string(), + r#type: "int32".to_string(), + ..Default::default() + }, + ], + ..Default::default() + }; + + let create_collection_result = client.collections().create(schema).await; + assert!( + create_collection_result.is_ok(), + "Failed to create collection" + ); + + let book_1_id = &new_id("document_1"); + let book_1 = json!({ + "id": book_1_id, + "title": "The Hitchhiker's Guide to the Galaxy", + "author": "Douglas Adams", + "publication_year": 1979 + }); + + let book_2 = json!({ + "title": "The Lord of the Rings", + "author": "J.R.R. Tolkien", + "publication_year": 1954 + }); + let collection_client = client.collection(&collection_name); + let documents_client = collection_client.documents(); + + // --- 2. Create a document (via `documents().create()`) --- + let create_res = documents_client.create(&book_1, None).await; + assert!(create_res.is_ok(), "Failed to create document 1"); + + // --- 3. Upsert a document (via `documents().upsert()`) --- + let upsert_res = documents_client.upsert(&book_2, None).await; + assert!(upsert_res.is_ok(), "Failed to upsert document 2"); + + // --- 4. Retrieve a single document (via `document(id).retrieve()`) --- + let retrieve_res = client + .collection(&collection_name) + .document(book_1_id) + .retrieve() + .await; + assert!(retrieve_res.is_ok(), "Failed to retrieve document 1"); + assert_eq!(retrieve_res.unwrap(), book_1); + + // --- 5. Search for documents --- + let search_params = SearchParameters::builder() + .q("the") + .query_by("title") + .build(); + let search_res = documents_client.search(search_params).await; + assert!(search_res.is_ok(), "Search failed"); + assert_eq!(search_res.unwrap().found, Some(2)); + + // --- 6. Update a single document --- + let partial_update = json!({ "publication_year": 1980 }); + let update_res = client + .collection(&collection_name) + .document(book_1_id) + .update(&partial_update, None) + .await; + assert!(update_res.is_ok(), "Failed to update document 1"); + + // --- 7. Verify the single update --- + let retrieve_after_update_res = client + .collection(&collection_name) + .document(book_1_id) + .retrieve() + .await; + let updated_doc = retrieve_after_update_res.unwrap(); + assert_eq!( + updated_doc.get("publication_year").unwrap().as_i64(), + Some(1980) + ); + + // --- 8. Delete a single document --- + let delete_res = client + .collection(&collection_name) + .document(book_1_id) + .delete() + .await; + assert!(delete_res.is_ok(), "Failed to delete document 1"); + + // --- 9. Verify single deletion --- + let retrieve_after_delete_res = client + .collection(&collection_name) + .document(book_1_id) + .retrieve() + .await; + assert!( + retrieve_after_delete_res.is_err(), + "Document should not exist after deletion" + ); + + // --- 10. Bulk Import --- + let new_books_jsonl = format!( + "{}\n{}", + json!({"title": "Foundation", "author": "Isaac Asimov", "publication_year": 1951}), + json!({"title": "Dune", "author": "Frank Herbert", "publication_year": 1965}) + ); + + let import_params = ImportDocumentsParameters { + action: Some(IndexAction::Create), + ..Default::default() + }; + let import_res = documents_client + .import(new_books_jsonl, import_params) + .await; + assert!(import_res.is_ok(), "Bulk import failed"); + + // --- 11. Verify Import via Search --- + let search_after_import_params = SearchParameters { + q: Some("*".to_string()), + query_by: Some("title".to_string()), + ..Default::default() + }; + let search_after_import_res = documents_client.search(search_after_import_params).await; + let search_results = search_after_import_res.unwrap(); + // 1 remaining (book_2) + 2 new imports = 3 + assert_eq!(search_results.found, Some(3)); + + // --- 12. Bulk Update (via `documents().update()`) --- + let bulk_update_params = UpdateDocumentsParameters { + filter_by: Some("publication_year:<1960".to_string()), + }; + let bulk_update_payload = json!({ "author": "Sci-Fi Pioneer" }); + let bulk_update_res = documents_client + .update(bulk_update_payload, bulk_update_params) + .await; + assert!(bulk_update_res.is_ok(), "Bulk update failed"); + // Should update Lord of the Rings (1954) and Foundation (1951) + assert_eq!(bulk_update_res.unwrap().num_updated, 2); + + // --- 13. Export documents (via `documents().export()`) --- + let export_params = ExportDocumentsParameters { + filter_by: Some("author:\"Sci-Fi Pioneer\"".to_string()), + ..Default::default() + }; + let export_res = documents_client.export(export_params).await; + + assert!(export_res.is_ok(), "Export failed"); + let exported_jsonl = export_res.unwrap(); + + // Verify the exported content is a JSONL string with 2 lines. + let lines: Vec<&str> = exported_jsonl.trim().split('\n').collect(); + assert_eq!(lines.len(), 2, "Exported JSONL should have 2 lines"); + let exported_doc_1: serde_json::Value = serde_json::from_str(lines[0]).unwrap(); + assert_eq!(exported_doc_1["author"], "Sci-Fi Pioneer"); + + // --- 14. Bulk Delete --- + let delete_params = DeleteDocumentsParameters { + filter_by: "publication_year:>1960".to_string(), + ..Default::default() + }; + let bulk_delete_res = documents_client.delete(delete_params).await; + assert!(bulk_delete_res.is_ok(), "Bulk delete failed"); + // Only "Dune" (1965) should be deleted + assert_eq!(bulk_delete_res.unwrap().num_deleted, 1); +} + +// --- TESTS FOR GENERIC FEATURES --- + +/// A strongly-typed representation of a book document. +#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] +struct Book { + id: String, + title: String, + author: String, + publication_year: i32, + #[serde(default, skip_serializing_if = "Option::is_none")] + in_stock: Option, +} + +async fn run_test_generic_document_lifecycle() { + let client = get_client(); + let collection_name = new_id("generic_books"); + + // --- 1. Setup: Create a Collection matching the Book struct --- + let schema = CollectionSchema { + name: collection_name.clone(), + fields: vec![ + Field { + name: "title".to_string(), + r#type: "string".to_string(), + ..Default::default() + }, + Field { + name: "author".to_string(), + r#type: "string".to_string(), + facet: Some(true), + ..Default::default() + }, + Field { + name: "publication_year".to_string(), + r#type: "int32".to_string(), + ..Default::default() + }, + Field { + name: "in_stock".to_string(), + r#type: "bool".to_string(), + optional: Some(true), + ..Default::default() + }, + ], + ..Default::default() + }; + + let create_collection_result = client.collections().create(schema).await; + assert!( + create_collection_result.is_ok(), + "Failed to create collection for generic test" + ); + + // Use the strongly-typed collection client + let typed_collection = client.collection_of::(&collection_name); + + let book_1 = Book { + id: new_id("book_1"), + title: "Dune".to_string(), + author: "Frank Herbert".to_string(), + publication_year: 1965, + in_stock: Some(true), + }; + + let book_2 = Book { + id: new_id("book_2"), + title: "Foundation".to_string(), + author: "Isaac Asimov".to_string(), + publication_year: 1951, + in_stock: Some(false), + }; + + // --- 2. Create a document using a typed struct --- + let create_res = typed_collection.documents().create(&book_1, None).await; + assert!(create_res.is_ok(), "Failed to create typed document"); + // The created document should be returned and be equal to the input + assert_eq!(create_res.unwrap(), book_1); + + // --- 3. Upsert a document using a typed struct --- + let upsert_res = typed_collection.documents().upsert(&book_2, None).await; + assert!(upsert_res.is_ok(), "Failed to upsert typed document"); + assert_eq!(upsert_res.unwrap(), book_2); + + // --- 4. Retrieve a single document and deserialize into a struct --- + let retrieve_res = typed_collection.document(&book_1.id).retrieve().await; + assert!(retrieve_res.is_ok(), "Failed to retrieve typed document"); + assert_eq!(retrieve_res.unwrap(), book_1); + + // --- 5. Search for documents with strongly-typed results --- + let search_params = SearchParameters { + q: Some("dune".to_string()), + query_by: Some("title".to_string()), + ..Default::default() + }; + let search_res = typed_collection.documents().search(search_params).await; + assert!(search_res.is_ok(), "Typed search failed"); + let search_results = search_res.unwrap(); + + assert_eq!(search_results.found, Some(1)); + let hits = search_results.hits.expect("Search should have hits"); + assert_eq!(hits.len(), 1); + // The document within the hit should be the deserialized Book struct + let hit_doc = hits[0] + .document + .as_ref() + .expect("Hit should contain a document"); + assert_eq!(hit_doc, &book_1); + + // --- 6. Update a single document with a partial payload --- + #[derive(Serialize)] + struct BookUpdate { + publication_year: i32, + in_stock: bool, + } + let partial_update_struct = BookUpdate { + publication_year: 1966, + in_stock: false, + }; + let index_params = DocumentIndexParameters { + dirty_values: Some(DirtyValues::CoerceOrReject), + }; + let update_res = typed_collection + .document(&book_1.id) + .update(&partial_update_struct, Some(index_params)) + .await; + assert!(update_res.is_ok(), "Failed to update typed document"); + + // The returned document should be the full, updated Book struct + let updated_book = update_res.unwrap(); + assert_eq!(updated_book.publication_year, 1966); + assert_eq!(updated_book.in_stock, Some(false)); + assert_eq!(updated_book.title, book_1.title); // Other fields are preserved + + // --- 7. Delete a single document, receiving the typed struct back --- + let delete_res = typed_collection.document(&book_1.id).delete().await; + assert!(delete_res.is_ok(), "Failed to delete typed document"); + // The deleted document (in its state just before deletion) is returned + let deleted_book = delete_res.unwrap(); + assert_eq!(deleted_book.id, book_1.id); + assert_eq!(deleted_book.publication_year, 1966); // It was the updated version + + // --- 8. Verify single deletion --- + let retrieve_after_delete_res = typed_collection.document(&book_1.id).retrieve().await; + assert!( + retrieve_after_delete_res.is_err(), + "Typed document should not exist after deletion" + ); +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tokio_test { + use super::*; + + #[tokio::test] + async fn test_document_lifecycle() { + run_test_document_lifecycle().await; + } + #[tokio::test] + async fn test_generic_document_lifecycle() { + run_test_generic_document_lifecycle().await; + } +} + +#[cfg(all(test, target_arch = "wasm32"))] +mod wasm_test { + use super::*; + use wasm_bindgen_test::wasm_bindgen_test; + + wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser); + + #[wasm_bindgen_test] + async fn test_document_lifecycle() { + console_error_panic_hook::set_once(); + run_test_document_lifecycle().await; + } + + #[wasm_bindgen_test] + async fn test_generic_document_lifecycle() { + console_error_panic_hook::set_once(); + run_test_generic_document_lifecycle().await; + } +} diff --git a/typesense/tests/client/keys_test.rs b/typesense/tests/client/keys_test.rs new file mode 100644 index 0000000..95683ac --- /dev/null +++ b/typesense/tests/client/keys_test.rs @@ -0,0 +1,144 @@ +use super::get_client; +use typesense::models::{ApiKeySchema, ScopedKeyParameters, SearchParameters}; + +async fn run_test_keys_lifecycle() { + let client = get_client(); + let key_description = "A test search-only key."; + + // --- 1. Create a new API Key (via `keys`) --- + let key_schema = ApiKeySchema { + description: key_description.to_string(), + actions: vec!["documents:search".to_string()], // Grant only search permissions + collections: vec!["*".to_string()], // For all collections + ..Default::default() + }; + + let create_result = client.keys().create(key_schema).await; + assert!(create_result.is_ok(), "Failed to create the API key."); + let created_key = create_result.unwrap(); + + // The full key value is only returned on creation + assert!( + created_key.value.is_some(), + "The full API key value should be present upon creation." + ); + assert_eq!(created_key.description, key_description.to_string()); + + let key_id = created_key.id.unwrap(); + + // --- 2. Retrieve the specific key (via `key`) --- + let retrieve_one_result = client.key(key_id).retrieve().await; + assert!( + retrieve_one_result.is_ok(), + "Failed to retrieve the specific API key." + ); + let retrieved_key = retrieve_one_result.unwrap(); + + // On retrieval, the value should be None and the prefix should be present + assert_eq!(retrieved_key.id.unwrap(), key_id); + assert!( + retrieved_key.value.is_none(), + "The retrieved key should not contain the full value." + ); + assert!( + retrieved_key.value_prefix.is_some(), + "The retrieved key should have a value prefix." + ); + + // --- 3. Retrieve all keys (via `keys`) --- + let retrieve_all_result = client.keys().retrieve().await; + assert!( + retrieve_all_result.is_ok(), + "Failed to retrieve the list of keys." + ); + let all_keys_response = retrieve_all_result.unwrap(); + + // --- 4. Find our specific key within the list --- + let our_key = all_keys_response + .keys + .iter() + .find(|k| k.id.unwrap() == (key_id)); + assert!( + our_key.is_some(), + "The newly created key was not found in the list." + ); + + // --- 5. Delete the key (via `key`) --- + let delete_result = client.key(key_id).delete().await; + assert!(delete_result.is_ok(), "Failed to delete the API key."); + let delete_response = delete_result.unwrap(); + assert_eq!( + delete_response.id, key_id, + "The response from delete should contain the correct key ID." + ); + + // --- 6. Verify Deletion --- + let get_after_delete_result = client.key(key_id).retrieve().await; + assert!( + get_after_delete_result.is_err(), + "API key should not exist after deletion." + ); +} + +#[test] +fn test_generate_scoped_search_key_with_example_values() { + // The parent key with `documents:search` permissions. + let search_only_api_key = "RN23GFr1s6jQ9kgSNg2O7fYcAUXU7127"; + + // The parameters to be embedded in the new scoped key. + let params = ScopedKeyParameters { + search_params: Some(SearchParameters { + filter_by: Some("company_id:124".to_string()), + ..Default::default() + }), + expires_at: Some(1906054106), + ..Default::default() + }; + + // The known correct output from the Typesense documentation. + let expected_scoped_key = "OW9DYWZGS1Q1RGdSbmo0S1QrOWxhbk9PL2kxbTU1eXA3bCthdmE5eXJKRT1STjIzeyJmaWx0ZXJfYnkiOiJjb21wYW55X2lkOjEyNCIsImV4cGlyZXNfYXQiOjE5MDYwNTQxMDZ9"; + + let client = get_client(); + + let generated_key_result = client + .keys() + .generate_scoped_search_key(search_only_api_key, ¶ms); + + // First, ensure the function returned an Ok result. + assert!( + generated_key_result.is_ok(), + "Function returned an error: {:?}", + generated_key_result.err() + ); + + // Unwrap the result and compare it with the expected output. + let generated_key = generated_key_result.unwrap(); + assert_eq!( + generated_key, expected_scoped_key, + "The generated key does not match the expected key." + ); +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tokio_test { + use super::*; + + #[tokio::test] + async fn test_keys_lifecycle() { + run_test_keys_lifecycle().await; + } +} + +#[cfg(all(test, target_arch = "wasm32"))] +mod wasm_test { + use super::*; + use wasm_bindgen_test::wasm_bindgen_test; + + wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser); + + #[wasm_bindgen_test] + async fn test_keys_lifecycle() { + console_error_panic_hook::set_once(); + run_test_keys_lifecycle().await; + } +} diff --git a/typesense/tests/client/mod.rs b/typesense/tests/client/mod.rs new file mode 100644 index 0000000..6231090 --- /dev/null +++ b/typesense/tests/client/mod.rs @@ -0,0 +1,41 @@ +mod client_test; +mod collections_test; + +mod documents_test; +mod keys_test; + +use reqwest::Url; +use reqwest_retry::policies::ExponentialBackoff; +use std::time::Duration; +use typesense::Client; +use web_time::{SystemTime, UNIX_EPOCH}; + +/// Helper function to create a new client for all tests in this suite. +pub fn get_client() -> Client { + Client::builder() + .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) + .api_key("xyz") + .healthcheck_interval(Duration::from_secs(5)) + .retry_policy(ExponentialBackoff::builder().build_with_max_retries(1)) + .connection_timeout(Duration::from_secs(3)) + .build() + .expect("Failed to create Typesense client") +} + +/// Generates a unique name for a test resource by combining a prefix, +/// a nanoid, and an optional suffix. +/// e.g., "test_collection_aB1cD2eF_create" +pub fn new_id(prefix: &str) -> String { + // Using nanoid for a short, URL-friendly, and collision-resistant random ID. + // The default length of 21 is more than enough. We use 8 for conciseness. + let random_part = nanoid::nanoid!(8); // e.g., "fX3a-b_1" + + // The timestamp helps ensure IDs are unique even across test runs that happen close together, + // although nanoid is likely sufficient on its own. + let timestamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_millis(); + + format!("test_{}_{}_{}", prefix, timestamp, random_part) +} diff --git a/typesense/tests/derive/collection.rs b/typesense/tests/derive/collection.rs index f4e8da2..b83b9a2 100644 --- a/typesense/tests/derive/collection.rs +++ b/typesense/tests/derive/collection.rs @@ -1,6 +1,6 @@ use serde::{Deserialize, Serialize}; use typesense::Typesense; -use typesense::document::Document; +use typesense::prelude::Document; #[test] fn derived_document_generates_schema() { diff --git a/typesense_derive/src/lib.rs b/typesense_derive/src/lib.rs index 4b1d70f..ba004af 100644 --- a/typesense_derive/src/lib.rs +++ b/typesense_derive/src/lib.rs @@ -63,7 +63,7 @@ fn impl_typesense_collection(item: ItemStruct) -> syn::Result { let default_sorting_field = if let Some(v) = default_sorting_field { quote! { - builder = builder.default_sorting_field(#v); + let builder = builder.default_sorting_field(#v); } } else { proc_macro2::TokenStream::new() @@ -71,19 +71,19 @@ fn impl_typesense_collection(item: ItemStruct) -> syn::Result { let enable_nested_fields = if let Some(v) = enable_nested_fields { quote! { - builder = builder.enable_nested_fields(Some(#v)); + let builder = builder.enable_nested_fields(#v); } } else { proc_macro2::TokenStream::new() }; let generated_code = quote! { - impl #impl_generics typesense::document::Document for #ident #ty_generics #where_clause { - fn collection_schema() -> typesense::collection_schema::CollectionSchema { + impl #impl_generics typesense::prelude::Document for #ident #ty_generics #where_clause { + fn collection_schema() -> typesense::models::CollectionSchema { let name = #collection_name.to_owned(); let fields = vec![#(#typesense_fields,)*]; - let mut builder = typesense::collection_schema::CollectionSchemaBuilder::new(name, fields); + let mut builder = typesense::models::CollectionSchema::builder().name(name).fields(fields); #default_sorting_field #enable_nested_fields @@ -285,13 +285,13 @@ fn to_typesense_field_type(field: &Field) -> syn::Result::to_typesense_type().to_owned() + <#ty as typesense::prelude::ToTypesenseField>::to_typesense_type().to_owned() ); Ok(quote! { - typesense::field::FieldBuilder::new(std::string::String::from(stringify!(#name)), #typesense_field_type) - .optional(#optional) - .facet(#facet) + typesense::models::Field::builder().name(std::string::String::from(stringify!(#name))).r#type(#typesense_field_type) + .maybe_optional(#optional) + .maybe_facet(#facet) .build() }) } From bc37f4f5b9a645c61b5930283c4c059a195c4202 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Tue, 2 Sep 2025 17:48:14 +0700 Subject: [PATCH 06/41] fix: avoid JSON serializing the request body of endpoints that accept plain text (JSONL) --- compose.yml | 2 +- custom-templates/reqwest/api.mustache | 19 +++++++++++++++---- openapi.yml | 3 +++ preprocessed_openapi.yml | 3 +++ typesense_codegen/src/apis/analytics_api.rs | 4 ++-- typesense_codegen/src/apis/collections_api.rs | 4 ++-- .../src/apis/conversations_api.rs | 4 ++-- typesense_codegen/src/apis/documents_api.rs | 16 +++++++--------- .../src/apis/nl_search_models_api.rs | 4 ++-- typesense_codegen/src/apis/operations_api.rs | 4 ++-- typesense_codegen/src/apis/synonyms_api.rs | 4 ++-- 11 files changed, 41 insertions(+), 26 deletions(-) diff --git a/compose.yml b/compose.yml index c77de65..ad85db6 100644 --- a/compose.yml +++ b/compose.yml @@ -1,6 +1,6 @@ services: typesense: - image: typesense/typesense:29.0 + image: typesense/typesense:30.0.rc10 restart: on-failure ports: - '8108:8108' diff --git a/custom-templates/reqwest/api.mustache b/custom-templates/reqwest/api.mustache index 04deb84..d88f89a 100644 --- a/custom-templates/reqwest/api.mustache +++ b/custom-templates/reqwest/api.mustache @@ -433,6 +433,16 @@ pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}{{{vendorExtensi {{/hasFormParams}} {{/isMultipart}} {{#hasBodyParam}} + {{! Check for the raw text body extension first }} + {{#vendorExtensions.x-rust-body-is-raw-text}} + {{! If the flag is true, we generate only the raw text body logic }} + {{#bodyParams}} + req_builder = req_builder.header(reqwest::header::CONTENT_TYPE, "text/plain").body({{{vendorExtensions.x-rust-param-identifier}}}); + {{/bodyParams}} + {{/vendorExtensions.x-rust-body-is-raw-text}} + {{! Now, handle the case where the extension is NOT present. This is the "else" block }} + {{^vendorExtensions.x-rust-body-is-raw-text}} + {{! This contains the original default logic }} {{#bodyParams}} {{#isFile}} req_builder = req_builder.body({{{vendorExtensions.x-rust-param-identifier}}}); @@ -441,6 +451,7 @@ pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}{{{vendorExtensi req_builder = req_builder.json(&{{{vendorExtensions.x-rust-param-identifier}}}); {{/isFile}} {{/bodyParams}} + {{/vendorExtensions.x-rust-body-is-raw-text}} {{/hasBodyParam}} let req = req_builder.build()?; @@ -472,14 +483,14 @@ pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}{{{vendorExtensi {{#returnType}} let content = resp.text(){{#supportAsync}}.await{{/supportAsync}}?; match content_type { - ContentType::Json => serde_json::from_str(&content).map_err(Error::from), {{#vendorExtensions.x-supports-plain-text}} - ContentType::Text => return Ok(content), + ContentType::Json | ContentType::Text => return Ok(content), {{/vendorExtensions.x-supports-plain-text}} {{^vendorExtensions.x-supports-plain-text}} - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `{{returnType}}`"))), + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `{{#vendorExtensions.x-rust-return-type}}{{{.}}}{{/vendorExtensions.x-rust-return-type}}{{^vendorExtensions.x-rust-return-type}}{{{returnType}}}{{/vendorExtensions.x-rust-return-type}}`"))), {{/vendorExtensions.x-supports-plain-text}} - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `{{returnType}}`")))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `{{#vendorExtensions.x-rust-return-type}}{{{.}}}{{/vendorExtensions.x-rust-return-type}}{{^vendorExtensions.x-rust-return-type}}{{{returnType}}}{{/vendorExtensions.x-rust-return-type}}`")))), } {{/returnType}} {{/isResponseFile}} diff --git a/openapi.yml b/openapi.yml index 2fcaec2..f40206f 100644 --- a/openapi.yml +++ b/openapi.yml @@ -697,6 +697,7 @@ paths: summary: Export all documents in a collection description: Export all documents in a collection in JSON lines format. operationId: exportDocuments + x-supports-plain-text: true parameters: - name: collectionName in: path @@ -748,6 +749,8 @@ paths: JSON structure. You can feed the output file from a Typesense export operation directly as import. operationId: importDocuments + x-rust-body-is-raw-text: true + x-supports-plain-text: true parameters: - name: collectionName in: path diff --git a/preprocessed_openapi.yml b/preprocessed_openapi.yml index 9efa7fb..6f82fbd 100644 --- a/preprocessed_openapi.yml +++ b/preprocessed_openapi.yml @@ -1075,6 +1075,7 @@ paths: summary: Export all documents in a collection description: Export all documents in a collection in JSON lines format. operationId: exportDocuments + x-supports-plain-text: true parameters: - name: collectionName in: path @@ -1121,6 +1122,8 @@ paths: summary: Import documents into a collection description: The documents to be imported must be formatted in a newline delimited JSON structure. You can feed the output file from a Typesense export operation directly as import. operationId: importDocuments + x-rust-body-is-raw-text: true + x-supports-plain-text: true parameters: - name: collectionName in: path diff --git a/typesense_codegen/src/apis/analytics_api.rs b/typesense_codegen/src/apis/analytics_api.rs index b4a672d..bbab7fd 100644 --- a/typesense_codegen/src/apis/analytics_api.rs +++ b/typesense_codegen/src/apis/analytics_api.rs @@ -481,8 +481,8 @@ pub async fn retrieve_analytics_rules(configuration: &configuration::Configurati let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec<models::AnalyticsRule>`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec<models::AnalyticsRule>`")))), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec`")))), } } else { let content = resp.text().await?; diff --git a/typesense_codegen/src/apis/collections_api.rs b/typesense_codegen/src/apis/collections_api.rs index 9ee7a2d..bccc4da 100644 --- a/typesense_codegen/src/apis/collections_api.rs +++ b/typesense_codegen/src/apis/collections_api.rs @@ -450,8 +450,8 @@ pub async fn get_collections(configuration: &configuration::Configuration, param let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec<models::CollectionResponse>`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec<models::CollectionResponse>`")))), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec`")))), } } else { let content = resp.text().await?; diff --git a/typesense_codegen/src/apis/conversations_api.rs b/typesense_codegen/src/apis/conversations_api.rs index 28b81f0..1a071e0 100644 --- a/typesense_codegen/src/apis/conversations_api.rs +++ b/typesense_codegen/src/apis/conversations_api.rs @@ -200,8 +200,8 @@ pub async fn retrieve_all_conversation_models(configuration: &configuration::Con let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec<models::ConversationModelSchema>`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec<models::ConversationModelSchema>`")))), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec`")))), } } else { let content = resp.text().await?; diff --git a/typesense_codegen/src/apis/documents_api.rs b/typesense_codegen/src/apis/documents_api.rs index a11935e..596d6c9 100644 --- a/typesense_codegen/src/apis/documents_api.rs +++ b/typesense_codegen/src/apis/documents_api.rs @@ -584,8 +584,7 @@ pub async fn export_documents(configuration: &configuration::Configuration, para if !status.is_client_error() && !status.is_server_error() { let content = resp.text().await?; match content_type { - ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `String`"))), + ContentType::Json | ContentType::Text => return Ok(content), ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `String`")))), } } else { @@ -758,7 +757,7 @@ pub async fn import_documents(configuration: &configuration::Configuration, para }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - req_builder = req_builder.json(¶ms.body); + req_builder = req_builder.header(reqwest::header::CONTENT_TYPE, "text/plain").body(params.body); let req = req_builder.build()?; let resp = configuration.client.execute(req).await?; @@ -774,8 +773,7 @@ pub async fn import_documents(configuration: &configuration::Configuration, para if !status.is_client_error() && !status.is_server_error() { let content = resp.text().await?; match content_type { - ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `String`"))), + ContentType::Json | ContentType::Text => return Ok(content), ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `String`")))), } } else { @@ -1061,8 +1059,8 @@ pub async fn multi_search(configuration: &configuration::Configuration, params: let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::MultiSearchResult`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::MultiSearchResult`")))), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `serde_json::Value`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))), } } else { let content = resp.text().await?; @@ -1317,8 +1315,8 @@ pub async fn search_collection serde::Deserialize<'de> + Serialize>( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchResult`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchResult`")))), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchResult`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchResult`")))), } } else { let content = resp.text().await?; diff --git a/typesense_codegen/src/apis/nl_search_models_api.rs b/typesense_codegen/src/apis/nl_search_models_api.rs index 1e6e93a..fbf5493 100644 --- a/typesense_codegen/src/apis/nl_search_models_api.rs +++ b/typesense_codegen/src/apis/nl_search_models_api.rs @@ -206,8 +206,8 @@ pub async fn retrieve_all_nl_search_models(configuration: &configuration::Config let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec<models::NlSearchModelSchema>`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec<models::NlSearchModelSchema>`")))), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec`")))), } } else { let content = resp.text().await?; diff --git a/typesense_codegen/src/apis/operations_api.rs b/typesense_codegen/src/apis/operations_api.rs index 31750f3..f80dcbd 100644 --- a/typesense_codegen/src/apis/operations_api.rs +++ b/typesense_codegen/src/apis/operations_api.rs @@ -204,8 +204,8 @@ pub async fn get_schema_changes(configuration: &configuration::Configuration) -> let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec<models::SchemaChangeStatus>`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec<models::SchemaChangeStatus>`")))), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec`")))), } } else { let content = resp.text().await?; diff --git a/typesense_codegen/src/apis/synonyms_api.rs b/typesense_codegen/src/apis/synonyms_api.rs index f568fc6..27b259a 100644 --- a/typesense_codegen/src/apis/synonyms_api.rs +++ b/typesense_codegen/src/apis/synonyms_api.rs @@ -189,8 +189,8 @@ pub async fn retrieve_synonym_sets(configuration: &configuration::Configuration) let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec<models::SynonymSetSchema>`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec<models::SynonymSetSchema>`")))), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec`")))), } } else { let content = resp.text().await?; From bbbb4504597f3bae448dcd660400df4fefa4af42 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Wed, 3 Sep 2025 17:37:44 +0700 Subject: [PATCH 07/41] feat: multi search --- typesense/src/client/collection/document.rs | 21 +- typesense/src/client/collection/documents.rs | 44 +- typesense/src/client/collection/mod.rs | 25 +- typesense/src/client/collections.rs | 11 +- typesense/src/client/key.rs | 2 +- typesense/src/client/keys.rs | 2 +- typesense/src/client/mod.rs | 79 ++- typesense/src/client/multi_search.rs | 330 +++++++++++ typesense/src/collection_schema.rs | 136 ----- typesense/src/document.rs | 14 - typesense/src/error.rs | 1 - typesense/src/lib.rs | 134 ++++- .../src/models/document_index_parameters.rs | 13 +- typesense/src/models/mod.rs | 3 +- typesense/src/models/multi_search.rs | 120 +--- typesense/src/models/scoped_key_parameters.rs | 1 - typesense/src/prelude.rs | 2 +- typesense/src/traits/field_type.rs | 14 - typesense/src/traits/mod.rs | 2 +- typesense/src/traits/multi_search_ext.rs | 236 ++++++++ typesense/tests/client/collections_test.rs | 3 +- typesense/tests/client/documents_test.rs | 2 +- typesense/tests/client/mod.rs | 1 + typesense/tests/client/multi_search_test.rs | 531 ++++++++++++++++++ 24 files changed, 1321 insertions(+), 406 deletions(-) create mode 100644 typesense/src/client/multi_search.rs delete mode 100644 typesense/src/collection_schema.rs delete mode 100644 typesense/src/document.rs create mode 100644 typesense/tests/client/multi_search_test.rs diff --git a/typesense/src/client/collection/document.rs b/typesense/src/client/collection/document.rs index 5d2835b..7e5ae12 100644 --- a/typesense/src/client/collection/document.rs +++ b/typesense/src/client/collection/document.rs @@ -18,8 +18,8 @@ where T: DeserializeOwned + Serialize + Send + Sync, { pub(super) client: &'a Client, - pub(super) collection_name: &'a str, - pub(super) document_id: &'a str, + pub(super) collection_name: String, + pub(super) document_id: String, pub(super) _phantom: std::marker::PhantomData, } @@ -28,8 +28,7 @@ where T: DeserializeOwned + Serialize + Send + Sync, { /// Creates a new `Document` instance for a specific document ID. - /// This is intended for internal use by the parent `Collection` struct. - pub(super) fn new(client: &'a Client, collection_name: &'a str, document_id: &'a str) -> Self { + pub(super) fn new(client: &'a Client, collection_name: String, document_id: String) -> Self { Self { client, collection_name, @@ -44,8 +43,8 @@ where /// A `Result` containing the strongly-typed document `T` if successful. pub async fn retrieve(&self) -> Result> { let params = documents_api::GetDocumentParams { - collection_name: self.collection_name.to_string(), - document_id: self.document_id.to_string(), + collection_name: self.collection_name.to_owned(), + document_id: self.document_id.to_owned(), }; let result_value = self @@ -104,12 +103,12 @@ where /// ``` pub async fn update( &self, - partial_document: &U, + partial_document: U, params: Option, ) -> Result> { let params = documents_api::UpdateDocumentParams { - collection_name: self.collection_name.to_string(), - document_id: self.document_id.to_string(), + collection_name: self.collection_name.to_owned(), + document_id: self.document_id.to_owned(), body: serde_json::to_value(partial_document)?, dirty_values: params.unwrap_or_default().dirty_values, }; @@ -133,8 +132,8 @@ where /// A `Result` containing the deleted document deserialized into `T`. pub async fn delete(&self) -> Result> { let params = documents_api::DeleteDocumentParams { - collection_name: self.collection_name.to_string(), - document_id: self.document_id.to_string(), + collection_name: self.collection_name.to_owned(), + document_id: self.document_id.to_owned(), }; let result_value = self diff --git a/typesense/src/client/collection/documents.rs b/typesense/src/client/collection/documents.rs index 4476864..3030954 100644 --- a/typesense/src/client/collection/documents.rs +++ b/typesense/src/client/collection/documents.rs @@ -25,7 +25,7 @@ where T: DeserializeOwned + Serialize + Send + Sync, { pub(super) client: &'a Client, - pub(super) collection_name: &'a str, + pub(super) collection_name: String, pub(super) _phantom: std::marker::PhantomData, } @@ -34,9 +34,7 @@ where T: DeserializeOwned + Serialize + Send + Sync, { /// Creates a new `Documents` instance. - /// - /// This is typically called by `Client::documents()`. - pub(super) fn new(client: &'a Client, collection_name: &'a str) -> Self { + pub(super) fn new(client: &'a Client, collection_name: String) -> Self { Self { client, collection_name, @@ -55,9 +53,9 @@ where params: Option, ) -> Result> { let params = documents_api::IndexDocumentParams { - collection_name: self.collection_name.to_string(), + collection_name: self.collection_name.to_owned(), body: document, - action: Some(action.to_string()), + action: Some(action.to_owned()), dirty_values: params.unwrap_or_default().dirty_values, // Or expose this as an argument if needed }; self.client @@ -75,11 +73,11 @@ where /// auto-generate an ID. The newly indexed document is returned. /// /// # Arguments - /// * `document` - A reference to the document to create. + /// * `document` - A serializable struct or a `serde_json::Value` representing the document to create. /// * `params` - Optional parameters like `dirty_values`. - pub async fn create( + pub async fn create( &self, - document: &T, + document: U, params: Option, ) -> Result> { let doc_value = serde_json::to_value(document)?; @@ -90,14 +88,14 @@ where /// Creates a new document or updates an existing one if an ID match is found. /// /// This method requires the full document to be sent. For partial updates, use - /// `collection.document("...").update()`. The indexed document is returned. + /// `collection("...").document("...").update()`. The indexed document is returned. /// /// # Arguments - /// * `document` - A reference to the document to upsert. + /// * `document` - A serializable struct or a `serde_json::Value` representing the document to upsert. /// * `params` - Optional parameters like `dirty_values`. - pub async fn upsert( + pub async fn upsert( &self, - document: &T, + document: U, params: Option, ) -> Result> { let doc_value = serde_json::to_value(document)?; @@ -114,14 +112,14 @@ where /// # Arguments /// * `documents_jsonl` - A string containing the documents in JSONL format. /// * `params` - An `ImportDocumentsParameters` struct containing options like `action` and `batch_size`. - pub async fn import( + pub async fn import_jsonl( &self, documents_jsonl: String, params: ImportDocumentsParameters, ) -> Result> { let params = documents_api::ImportDocumentsParams { body: documents_jsonl, - collection_name: self.collection_name.to_string(), + collection_name: self.collection_name.to_owned(), action: params.action, batch_size: params.batch_size, @@ -148,7 +146,7 @@ where params: ExportDocumentsParameters, ) -> Result> { let params = documents_api::ExportDocumentsParams { - collection_name: self.collection_name.to_string(), + collection_name: self.collection_name.to_owned(), exclude_fields: params.exclude_fields, filter_by: params.filter_by, include_fields: params.include_fields, @@ -172,7 +170,7 @@ where ) -> Result> { let params = documents_api::DeleteDocumentsParams { - collection_name: self.collection_name.to_string(), + collection_name: self.collection_name.to_owned(), filter_by: Some(params.filter_by), batch_size: params.batch_size, ignore_not_found: params.ignore_not_found, @@ -189,18 +187,18 @@ where /// Updates a batch of documents matching a specific filter condition. /// /// # Arguments - /// * `document` - A `serde_json::Value` containing the fields to update. + /// * `document` - A serializable struct or a `serde_json::Value` containing the fields to update. /// * `params` - A `UpdateDocumentsParameters` describing the conditions for updating documents. - pub async fn update( + pub async fn update( &self, - document: serde_json::Value, + document: U, params: UpdateDocumentsParameters, ) -> Result> { let params = documents_api::UpdateDocumentsParams { - collection_name: self.collection_name.to_string(), + collection_name: self.collection_name.to_owned(), filter_by: params.filter_by, - body: document, + body: serde_json::to_value(document)?, }; self.client .execute(|config: configuration::Configuration| { @@ -220,7 +218,7 @@ where params: raw_models::SearchParameters, ) -> Result, Error> { let search_params = documents_api::SearchCollectionParams { - collection_name: self.collection_name.to_string(), + collection_name: self.collection_name.to_owned(), // Map all corresponding fields directly. cache_ttl: params.cache_ttl, diff --git a/typesense/src/client/collection/mod.rs b/typesense/src/client/collection/mod.rs index 0edae44..d4dfb7d 100644 --- a/typesense/src/client/collection/mod.rs +++ b/typesense/src/client/collection/mod.rs @@ -1,6 +1,6 @@ //! Provides access to the collection and alias-related API endpoints. //! -//! A `Collections` instance is created via the main `Client::collections()` method. +//! A `Collections` instance is created via the main `client.collections()` method. mod document; mod documents; @@ -20,7 +20,7 @@ where T: DeserializeOwned + Serialize + Send + Sync, { pub(super) client: &'a Client, - pub(super) collection_name: &'a str, + pub(super) collection_name: String, pub(super) _phantom: std::marker::PhantomData, } @@ -29,7 +29,7 @@ where T: DeserializeOwned + Serialize + Send + Sync, { /// Creates a new `Collection` instance. - pub(super) fn new(client: &'a Client, collection_name: &'a str) -> Self { + pub(super) fn new(client: &'a Client, collection_name: String) -> Self { Self { client, collection_name, @@ -39,12 +39,16 @@ where /// Provides access to the document-related API endpoints for a specific collection. pub fn documents(&'a self) -> documents::Documents<'a, T> { - documents::Documents::new(self.client, self.collection_name) + documents::Documents::new(self.client, self.collection_name.to_owned()) } /// Provides access to the API endpoints for a single document within a Typesense collection. - pub fn document(&'a self, document_id: &'a str) -> document::Document<'a, T> { - document::Document::new(self.client, self.collection_name, document_id) + pub fn document(&'a self, document_id: impl Into) -> document::Document<'a, T> { + document::Document::new( + self.client, + self.collection_name.to_owned(), + document_id.into(), + ) } /// Retrieves the details of a collection, given its name. @@ -52,7 +56,7 @@ where &self, ) -> Result> { let params = collections_api::GetCollectionParams { - collection_name: self.collection_name.to_string(), + collection_name: self.collection_name.to_owned(), }; self.client @@ -64,14 +68,11 @@ where } /// Permanently drops a collection. - /// - /// This action cannot be undone. For large collections, this might have an - /// impact on read latencies during the delete operation. pub async fn delete( &self, ) -> Result> { let params = collections_api::DeleteCollectionParams { - collection_name: self.collection_name.to_string(), + collection_name: self.collection_name.to_owned(), }; self.client .execute(|config: configuration::Configuration| { @@ -90,7 +91,7 @@ where update_schema: models::CollectionUpdateSchema, ) -> Result> { let params = collections_api::UpdateCollectionParams { - collection_name: self.collection_name.to_string(), + collection_name: self.collection_name.to_owned(), collection_update_schema: update_schema, }; self.client diff --git a/typesense/src/client/collections.rs b/typesense/src/client/collections.rs index 6654818..dd9db45 100644 --- a/typesense/src/client/collections.rs +++ b/typesense/src/client/collections.rs @@ -23,13 +23,9 @@ impl<'a> Collections<'a> { pub(super) fn new(client: &'a Client) -> Self { Self { client } } - // --- Collection-Specific Methods --- /// Creates a new collection with the given schema. /// - /// When a collection is created, you give it a name and describe the fields - /// that will be indexed from the documents added to the collection. - /// /// # Arguments /// * `schema` - A `CollectionSchema` object describing the collection to be created. pub async fn create( @@ -48,13 +44,10 @@ impl<'a> Collections<'a> { .await } - /// Returns a summary of all collections in the Typesense cluster. - /// - /// The collections are returned sorted by creation date, with the most - /// recent collections appearing first. + /// List the existing Typesense collections. pub async fn retrieve( &self, - params: &GetCollectionsParameters, + params: GetCollectionsParameters, ) -> Result, Error> { self.client .execute(|config: configuration::Configuration| { diff --git a/typesense/src/client/key.rs b/typesense/src/client/key.rs index fb2701d..5fe8e7d 100644 --- a/typesense/src/client/key.rs +++ b/typesense/src/client/key.rs @@ -1,6 +1,6 @@ //! Provides access to the API endpoints for managing a single API key. //! -//! A `Key` instance is created via the `Client::key(key_id)` method. +//! A `Key` instance is created via the `client.key(key_id)` method. use crate::{Client, Error}; use typesense_codegen::{ diff --git a/typesense/src/client/keys.rs b/typesense/src/client/keys.rs index 12b791c..ad0896d 100644 --- a/typesense/src/client/keys.rs +++ b/typesense/src/client/keys.rs @@ -1,6 +1,6 @@ //! Provides access to the API endpoints for managing the collection of API keys. //! -//! An `Keys` instance is created via the `Client::keys()` method. +//! An `Keys` instance is created via the `client.keys()` method. use crate::{ Client, Error, diff --git a/typesense/src/client/mod.rs b/typesense/src/client/mod.rs index 96f78ea..d285786 100644 --- a/typesense/src/client/mod.rs +++ b/typesense/src/client/mod.rs @@ -18,9 +18,8 @@ //! ```no_run //! #[cfg(not(target_family = "wasm"))] //! { -//! use typesense::{Client, models}; +//! use typesense::{Client, models, ExponentialBackoff}; //! use reqwest::Url; -//! use reqwest_retry::policies::ExponentialBackoff; //! use std::time::Duration; //! //! #[tokio::main] @@ -60,12 +59,9 @@ //! //! ### WebAssembly (Wasm) Usage //! -//! When compiling for a WebAssembly target (`wasm32-unknown-unknown`), the -//! client's underlying HTTP transport and runtime are different. -//! -//! - `reqwest` internally uses the browser's **fetch API**. -//! - Tokio-based features such as middleware, retries, and connection -//! timeouts are **not available**. +//! When compiling for a WebAssembly target (`wasm32-unknown-unknown`), +//! Tokio-based features such as middleware, retries, and connection +//! timeouts are **not available**. //! //! Example: //! @@ -115,6 +111,7 @@ mod collection; mod collections; mod key; mod keys; +mod multi_search; use collection::Collection; use collections::Collections; @@ -130,7 +127,7 @@ use reqwest::Url; use reqwest_middleware::ClientBuilder as ReqwestMiddlewareClientBuilder; #[cfg(not(target_arch = "wasm32"))] use reqwest_retry::RetryTransientMiddleware; -use reqwest_retry::policies::ExponentialBackoff; +pub use reqwest_retry::policies::ExponentialBackoff; use std::future::Future; use std::sync::{ @@ -153,7 +150,6 @@ struct Node { /// API resource groups (namespaces) like `collections`, `documents`, and `operations`. #[derive(Debug)] pub struct Client { - // The Client now holds the stateful Node list. nodes: Vec>>, nearest_node: Option>>, api_key: String, @@ -168,7 +164,7 @@ pub struct Client { #[bon::bon] impl Client { - /// Creates a new `Client` with the given configuration. + /// Creates a new `Client`. /// /// Returns an error if the configuration contains no nodes. Default values: /// - **nearest_node**: None. @@ -181,7 +177,7 @@ impl Client { api_key: impl Into, /// A list of all nodes in the Typesense cluster. nodes: Vec, - /// An optional, preferred node to try first for every request. Ideal for reducing latency. + /// An optional, preferred node to try first for every request. This is for your server-side load balancer. #[builder(into)] nearest_node: Option, #[builder(default = Duration::from_secs(60))] @@ -293,7 +289,6 @@ impl Client { for _ in 0..num_nodes_to_try { let node_arc = self.get_next_node(); let node_url = { - // Lock is held for a very short duration. let node = node_arc.lock().unwrap(); node.url.clone() }; @@ -313,7 +308,7 @@ impl Client { .with(RetryTransientMiddleware::new_with_policy(self.retry_policy)) .build(); - // Create the temporary config on the stack for this attempt. + // Create a temporary config for this attempt. let gen_config = configuration::Configuration { base_path: node_url .to_string() @@ -355,7 +350,7 @@ impl Client { /// ```no_run /// # #[cfg(not(target_family = "wasm"))] /// # { - /// # use typesense::Client; + /// # use typesense::{Client, GetCollectionsParameters}; /// # use reqwest::Url; /// # /// # #[tokio::main] @@ -365,7 +360,7 @@ impl Client { /// # .api_key("xyz") /// # .build() /// # .unwrap(); - /// let all_collections = client.collections().retrieve().await.unwrap(); + /// let all_collections = client.collections().retrieve(GetCollectionsParameters::default()).await.unwrap(); /// # Ok(()) /// # } /// # } @@ -381,9 +376,6 @@ impl Client { /// /// # Type Parameters /// * `T` - The type of the documents in the collection. It must be serializable and deserializable. - /// **This defaults to `serde_json::Value`**, allowing you to perform collection-level - /// operations (like delete, update, retrieve schema) without specifying a type, - /// or to work with schemaless documents. /// /// # Arguments /// * `collection_name` - The name of the collection to interact with. @@ -418,11 +410,11 @@ impl Client { /// # } /// # } /// ``` - pub fn collection_of<'a, T>(&'a self, collection_name: &'a str) -> Collection<'a, T> + pub fn collection_of<'a, T>(&'a self, collection_name: impl Into) -> Collection<'a, T> where T: DeserializeOwned + Serialize + Send + Sync, { - Collection::new(self, collection_name) + Collection::new(self, collection_name.into()) } /// Provides access to API endpoints for a specific collection using schemaless `serde_json::Value` documents. @@ -454,8 +446,11 @@ impl Client { /// # } /// # } /// ``` - pub fn collection<'a>(&'a self, collection_name: &'a str) -> Collection<'a, serde_json::Value> { - Collection::new(self, collection_name) + pub fn collection<'a>( + &'a self, + collection_name: impl Into, + ) -> Collection<'a, serde_json::Value> { + Collection::new(self, collection_name.into()) } /// Provides access to endpoints for managing the collection of API keys. @@ -516,6 +511,41 @@ impl Client { pub fn key(&self, key_id: i64) -> Key<'_> { Key::new(self, key_id) } + + /// Provides access to the multi search endpoint. + /// + /// # Example + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { + /// # use typesense::{Client, models}; + /// # use reqwest::Url; + /// # + /// # #[tokio::main] + /// # async fn main() -> Result<(), Box> { + /// # let client = Client::builder() + /// # .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) + /// # .api_key("xyz") + /// # .build() + /// # .unwrap(); + /// # let search_requests = models::MultiSearchBody { + /// # searches: vec![models::MultiSearchCollectionParameters { + /// # collection: Some("products".to_string()), + /// # q: Some("phone".to_string()), + /// # query_by: Some("name".to_string()), + /// # ..Default::default() + /// # }], + /// # ..Default::default() + /// # }; + /// # let common_params = models::MultiSearchParameters::default(); + /// let results = client.multi_search().perform(search_requests, common_params).await.unwrap(); + /// # Ok(()) + /// # } + /// # } + /// ``` + pub fn multi_search(&self) -> multi_search::MultiSearch<'_> { + multi_search::MultiSearch::new(self) + } } /// A helper function to determine if an error is worth retrying on another node. @@ -528,11 +558,10 @@ where // Server-side errors (5xx) indicate a problem with the node, so we should try another. apis::Error::ResponseError(content) => content.status.is_server_error(), - // Underlying reqwest errors (e.g., connection refused) are retriable on both native and wasm. + // Underlying reqwest errors (e.g., connection refused) are retriable. apis::Error::Reqwest(_) => true, // Network-level errors from middleware are always retriable. - // This match arm is ONLY included when compiling for non-wasm targets. #[cfg(not(target_arch = "wasm32"))] apis::Error::ReqwestMiddleware(_) => true, diff --git a/typesense/src/client/multi_search.rs b/typesense/src/client/multi_search.rs new file mode 100644 index 0000000..4d329a8 --- /dev/null +++ b/typesense/src/client/multi_search.rs @@ -0,0 +1,330 @@ +//! Provides access to the API endpoints for Multi Search. +//! +//! A `MultiSearch` instance is created via the main `client.multi_search()` method. + +use crate::{Client, Error, MultiSearchBody, models::SearchResult}; +use typesense_codegen::{ + apis::{ + configuration::Configuration, + documents_api::{self, MultiSearchParams}, + }, + models as raw_models, +}; + +/// Provides methods for performing multi-search operations across multiple collections. +/// +/// This struct is created by calling `client.multi_search()`. +pub struct MultiSearch<'a> { + pub(super) client: &'a Client, +} + +impl<'a> MultiSearch<'a> { + /// Creates a new `MultiSearch` instance. + pub(super) fn new(client: &'a Client) -> Self { + Self { client } + } + + /// Performs a **federated** multi-search operation, returning a list of search results. + /// + /// This function allows you to send multiple search queries in a single HTTP request, which is + /// efficient for reducing network latency. It is specifically designed for federated searches, + /// where each query in the request runs independently and returns its own corresponding result. + /// + /// The returned `MultiSearchResult` contains a `results` vector where each item maps to a + /// query in the request, in the exact same order. To process these results in a type-safe + /// way, you can use the `MultiSearchResultExt::parse_at` helper method. + /// + /// This is the default multi-search behavior in Typesense. For more details, see the + /// [official Typesense API documentation on federated search](https://typesense.org/docs/latest/api/federated-multi-search.html#federated-search). + /// + /// For **union** searches that merge all hits into a single ranked list, use the + /// `perform_union` method instead. + /// + /// # Example + /// + /// This example demonstrates a federated search across two different collections. + /// + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { + /// # use typesense::{Client, SearchResult, models, prelude::*}; + /// # use reqwest::Url; + /// # use serde::Deserialize; + /// # + /// # // Define the structs for your documents for typed parsing. + /// # #[derive(Deserialize, Debug)] + /// # struct Product { id: String, name: String } + /// # #[derive(Deserialize, Debug)] + /// # struct Brand { id: String, company_name: String } + /// # + /// # #[tokio::main] + /// # async fn main() -> Result<(), Box> { + /// # let client = Client::builder() + /// # .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) + /// # .api_key("xyz") + /// # .build() + /// # .unwrap(); + /// // Define the individual search queries for different collections. + /// let search_requests = models::MultiSearchBody { + /// searches: vec![ + /// // Search #0 targets the 'products' collection + /// models::MultiSearchCollectionParameters { + /// collection: Some("products".to_string()), + /// q: Some("shoe".to_string()), + /// query_by: Some("name".to_string()), + /// ..Default::default() + /// }, + /// // Search #1 targets the 'brands' collection + /// models::MultiSearchCollectionParameters { + /// collection: Some("brands".to_string()), + /// q: Some("nike".to_string()), + /// query_by: Some("company_name".to_string()), + /// ..Default::default() + /// }, + /// ], + /// ..Default::default() + /// }; + /// + /// // Define parameters that will apply to all searches. + /// let common_params = models::MultiSearchParameters::default(); + /// + /// // Perform the federated multi-search. + /// let raw_response = client + /// .multi_search() + /// .perform(search_requests, common_params) + /// .await?; + /// + /// // The raw response contains a vector of results. + /// assert_eq!(raw_response.results.len(), 2); + /// + /// // Use the `parse_at` helper to get strongly-typed results for each search. + /// let typed_products: SearchResult = raw_response.parse_at(0)?; + /// let typed_brands: SearchResult = raw_response.parse_at(1)?; + /// + /// println!("Found {} products.", typed_products.found.unwrap_or(0)); + /// println!("Found {} brands.", typed_brands.found.unwrap_or(0)); + /// # Ok(()) + /// # } + /// # } + /// ``` + /// # Arguments + /// * `search_requests` - A `MultiSearchBody` containing the list of individual search queries. The `union` field is ignored. + /// * `common_search_params` - A `MultiSearchParameters` struct describing search parameters that are common to all searches. + pub async fn perform( + &self, + search_requests: MultiSearchBody, + common_search_params: raw_models::MultiSearchParameters, + ) -> Result< + raw_models::MultiSearchResult, + Error, + > { + let request_body = raw_models::MultiSearchSearchesParameter { + searches: search_requests.searches, + ..Default::default() + }; + let multi_search_params = build_multi_search_params(request_body, common_search_params); + + let raw_result = self + .client + .execute(|config: Configuration| { + let params_for_move: MultiSearchParams = multi_search_params.clone(); + async move { documents_api::multi_search(&config, params_for_move).await } + }) + .await; + + // Now, handle the raw result and parse it into the strong type. + match raw_result { + Ok(json_value) => serde_json::from_value(json_value).map_err(Error::from), + Err(e) => Err(e), + } + } + + /// Performs a multi-search request in **union** mode, returning a single, merged `SearchResult`. + /// + /// This function is ideal for building a federated search experience where results from + /// different collections are displayed together in a single, ranked list. It forces + /// `union: true` in the search request. + /// + /// For more details, see the + /// [official Typesense API documentation on union search](https://typesense.org/docs/latest/api/federated-multi-search.html#union-search). + /// + /// ### Handling Search Results + /// + /// The return type of this function is always `SearchResult` because + /// the search queries can target collections with different document schemas. + /// + /// #### 1. Heterogeneous Documents (Different Schemas) + /// + /// When searching across different collections (e.g., `products` and `brands`), you must + /// inspect the `serde_json::Value` of each document to determine its type before + /// deserializing it into a concrete struct. + /// + /// ```no_run + /// # use typesense::models::SearchResult; + /// # use serde_json::Value; + /// # #[derive(serde::Deserialize)] + /// # struct Product { name: String } + /// # #[derive(serde::Deserialize)] + /// # struct Brand { company_name: String } + /// # async fn run() -> Result<(), Box> { + /// # let search_result: SearchResult = todo!(); + /// for hit in search_result.hits.unwrap_or_default() { + /// if let Some(doc) = hit.document { + /// if doc.get("price").is_some() { + /// let product: Product = serde_json::from_value(doc)?; + /// println!("Found Product: {}", product.name); + /// } else if doc.get("country").is_some() { + /// let brand: Brand = serde_json::from_value(doc)?; + /// println!("Found Brand: {}", brand.company_name); + /// } + /// } + /// } + /// # Ok(()) + /// # } + /// ``` + /// + /// #### 2. Homogeneous Documents (Same Schema) + /// + /// If all search queries target collections that share the **same schema**, you can + /// convert the entire result into a strongly-typed `SearchResult` using the + /// [`SearchResult::try_into_typed`] helper method. This is much more convenient + /// than parsing each hit individually. + /// + /// ```no_run + /// # use typesense::{models::SearchResult, prelude::*}; + /// # use serde_json::Value; + /// # #[derive(serde::Deserialize)] + /// # struct Product { name: String } + /// # async fn run() -> Result<(), Box> { + /// # let client: typesense::Client = todo!(); + /// let value_result: SearchResult = client.multi_search().perform_union(todo!(), todo!()).await?; + /// + /// // Convert the entire result into a strongly-typed one. + /// let typed_result: SearchResult = value_result.try_into_typed()?; + /// + /// if let Some(product) = typed_result.hits.unwrap_or_default().get(0) { + /// println!("Found product: {}", product.document.as_ref().unwrap().name); + /// } + /// # Ok(()) + /// # } + /// ``` + /// + /// # Arguments + /// + /// * `search_requests` - A `MultiSearchBody` containing the list of search queries to perform. + /// * `common_search_params` - A `MultiSearchParameters` which will be applied to all individual searches. + /// + /// # Returns + /// + /// A `Result` containing a `SearchResult` on success, or an `Error` on failure. + pub async fn perform_union( + &self, + search_requests: MultiSearchBody, + common_search_params: raw_models::MultiSearchParameters, + ) -> Result, Error> { + // Explicitly set `union: true` for the request body, overriding any user value. + let request_body = raw_models::MultiSearchSearchesParameter { + union: Some(true), + searches: search_requests.searches, + }; + + let multi_search_params = build_multi_search_params(request_body, common_search_params); + + // Execute the request to get the raw JSON value + let raw_result = self + .client + .execute(|config: Configuration| { + let params_for_move = multi_search_params.clone(); + async move { documents_api::multi_search(&config, params_for_move).await } + }) + .await; + + // Handle the result: parse to raw SearchResult, then convert to generic SearchResult + match raw_result { + Ok(json_value) => { + // A union search returns a single SearchResult object, not a MultiSearchResult. + serde_json::from_value(json_value).map_err(Error::from) + } + Err(e) => Err(e), + } + } +} +// Private helper function to construct the final search parameters object. +// This encapsulates the repetitive mapping logic. +fn build_multi_search_params( + request_body: raw_models::MultiSearchSearchesParameter, + params: raw_models::MultiSearchParameters, +) -> MultiSearchParams { + MultiSearchParams { + multi_search_searches_parameter: Some(request_body), + // Common URL search params + cache_ttl: params.cache_ttl, + conversation: params.conversation, + conversation_id: params.conversation_id, + conversation_model_id: params.conversation_model_id, + drop_tokens_mode: params.drop_tokens_mode, + drop_tokens_threshold: params.drop_tokens_threshold, + enable_overrides: params.enable_overrides, + enable_synonyms: params.enable_synonyms, + enable_typos_for_alpha_numerical_tokens: params.enable_typos_for_alpha_numerical_tokens, + enable_typos_for_numerical_tokens: params.enable_typos_for_numerical_tokens, + exclude_fields: params.exclude_fields, + exhaustive_search: params.exhaustive_search, + facet_by: params.facet_by, + facet_query: params.facet_query, + facet_return_parent: params.facet_return_parent, + facet_strategy: params.facet_strategy, + filter_by: params.filter_by, + filter_curated_hits: params.filter_curated_hits, + group_by: params.group_by, + group_limit: params.group_limit, + group_missing_values: params.group_missing_values, + hidden_hits: params.hidden_hits, + highlight_affix_num_tokens: params.highlight_affix_num_tokens, + highlight_end_tag: params.highlight_end_tag, + highlight_fields: params.highlight_fields, + highlight_full_fields: params.highlight_full_fields, + highlight_start_tag: params.highlight_start_tag, + include_fields: params.include_fields, + infix: params.infix, + limit: params.limit, + max_extra_prefix: params.max_extra_prefix, + max_extra_suffix: params.max_extra_suffix, + max_facet_values: params.max_facet_values, + min_len_1typo: params.min_len_1typo, + min_len_2typo: params.min_len_2typo, + num_typos: params.num_typos, + offset: params.offset, + override_tags: params.override_tags, + page: params.page, + per_page: params.per_page, + pinned_hits: params.pinned_hits, + pre_segmented_query: params.pre_segmented_query, + prefix: params.prefix, + preset: params.preset, + prioritize_exact_match: params.prioritize_exact_match, + prioritize_num_matching_fields: params.prioritize_num_matching_fields, + prioritize_token_position: params.prioritize_token_position, + q: params.q, + query_by: params.query_by, + query_by_weights: params.query_by_weights, + remote_embedding_num_tries: params.remote_embedding_num_tries, + remote_embedding_timeout_ms: params.remote_embedding_timeout_ms, + search_cutoff_ms: params.search_cutoff_ms, + snippet_threshold: params.snippet_threshold, + sort_by: params.sort_by, + stopwords: params.stopwords, + synonym_num_typos: params.synonym_num_typos, + synonym_prefix: params.synonym_prefix, + text_match_type: params.text_match_type, + typo_tokens_threshold: params.typo_tokens_threshold, + use_cache: params.use_cache, + vector_query: params.vector_query, + voice_query: params.voice_query, + enable_analytics: params.enable_analytics, + // enable_highlight_v1: None, + // max_candidates: None, + // max_filter_by_candidates: None, + // split_join_tokens: None, + } +} diff --git a/typesense/src/collection_schema.rs b/typesense/src/collection_schema.rs deleted file mode 100644 index 0951e76..0000000 --- a/typesense/src/collection_schema.rs +++ /dev/null @@ -1,136 +0,0 @@ -//! # Collection -//! -//! In Typesense, a group of related documents is called a collection. A collection -//! is roughly equivalent to a table in a relational database. -//! -use crate::field::Field; - -pub use typesense_codegen::models::CollectionSchema; - -/// Builder for the [CollectionSchema] struct. -#[derive(Debug, Default)] -pub struct CollectionSchemaBuilder { - name: String, - fields: Vec, - default_sorting_field: Option, - token_separators: Option>, - enable_nested_fields: Option, - symbols_to_index: Option>, -} - -impl CollectionSchemaBuilder { - /// Create a builder for [CollectionSchema] - #[inline] - pub fn new(name: impl Into, fields: Vec) -> Self { - Self { - name: name.into(), - fields, - ..Default::default() - } - } - - /// Insert field - #[inline] - pub fn field(mut self, field: Field) -> Self { - self.fields.push(field); - self - } - - /// Set fields - #[inline] - pub fn fields(mut self, fields: &[Field]) -> Self { - self.fields.extend_from_slice(fields); - self - } - - /// Set default sorting field - #[inline] - pub fn default_sorting_field(mut self, default_sorting_field: impl Into) -> Self { - self.default_sorting_field = Some(default_sorting_field.into()); - self - } - - /// Set token separators - #[inline] - pub fn token_separators(mut self, token_separators: Vec) -> Self { - self.token_separators = Some(token_separators); - self - } - - /// Enable nested fields - #[inline] - pub fn enable_nested_fields(mut self, enable_nested_fields: Option) -> Self { - self.enable_nested_fields = enable_nested_fields; - self - } - - /// Set symbols to index - #[inline] - pub fn symbols_to_index(mut self, symbols_to_index: Vec) -> Self { - self.symbols_to_index = Some(symbols_to_index); - self - } - - /// Create a `CollectionSchema` with the current values of the builder, - /// It can fail if any of the required fields is not not defined. - #[inline] - pub fn build(self) -> CollectionSchema { - CollectionSchema { - name: self.name, - fields: self.fields, - default_sorting_field: self.default_sorting_field, - token_separators: self.token_separators, - enable_nested_fields: self.enable_nested_fields, - symbols_to_index: self.symbols_to_index, - ..Default::default() - } - } -} - -#[cfg(test)] -mod test { - use super::*; - use crate::field::*; - use serde_json::json; - - #[test] - fn collection_schema_serializes_as_expected() { - let fields = [ - ("company_name", "string".to_owned(), None), - ("num_employees", "int32".to_owned(), None), - ("country", "string".to_owned(), Some(true)), - ] - .map(|(name, typesense_type, facet)| { - FieldBuilder::new(name, typesense_type).facet(facet).build() - }) - .to_vec(); - - let collection = CollectionSchemaBuilder::new("companies", fields) - .default_sorting_field("num_employees".to_owned()) - .build(); - - let expected = json!( - { - "name": "companies", - "fields": [ - { - "name" : "company_name", - "type" : "string" - }, - { - "name" : "num_employees", - "type" : "int32" - }, - { - "name" : "country", - "type" : "string", - "facet" : true - } - ], - "default_sorting_field": "num_employees" - } - ); - - assert_eq!(serde_json::to_value(&collection).unwrap(), expected) - } -} diff --git a/typesense/src/document.rs b/typesense/src/document.rs deleted file mode 100644 index e26a53a..0000000 --- a/typesense/src/document.rs +++ /dev/null @@ -1,14 +0,0 @@ -//! # Document -//! -//! In Typesense, documents are each one of the JSON elements that are stored in the collections. -//! A document to be indexed in a given collection must conform to the schema of the collection. -//! -use crate::collection_schema::CollectionSchema; -use serde::{Serialize, de::DeserializeOwned}; - -/// Trait that should implement every struct that wants to be represented as a Typesense -/// Document -pub trait Document: DeserializeOwned + Serialize { - /// Collection schema associated with the document. - fn collection_schema() -> CollectionSchema; -} diff --git a/typesense/src/error.rs b/typesense/src/error.rs index 68e9d4f..e6b705c 100644 --- a/typesense/src/error.rs +++ b/typesense/src/error.rs @@ -18,7 +18,6 @@ where { /// Occurs when an operation fails against all configured Typesense nodes. /// - /// This error is only returned when using a client configured with multiple nodes. /// It signifies that the client attempted the operation against each node in turn, /// and every attempt failed. The user should check the health and connectivity /// of all their Typesense nodes. diff --git a/typesense/src/lib.rs b/typesense/src/lib.rs index 47b1e06..599551c 100644 --- a/typesense/src/lib.rs +++ b/typesense/src/lib.rs @@ -3,43 +3,115 @@ //! # Typesense //! -//! Rust client library for Typesense +//! A Rust client library for the Typesense API. +//! +//! This library provides an ergonomic interface for +//! interacting with Typesense. It supports multi-node configuration and WebAssembly. //! //! # Examples //! -//! ``` +//! The following examples demonstrate how to define a collection schema using +//! the Typesense derive macro and create it on the server. +//! +//! --- +//! +//! ### Native (Tokio) +//! +//! This example shows the typical setup for a server-side application using the +//! Tokio runtime. It includes features like connection timeouts and automatic +//! request retries. +//! +//! ```no_run //! #[cfg(not(target_family = "wasm"))] //! { -//! use serde::{Deserialize, Serialize}; -//! use typesense::document::Document; -//! use typesense::Typesense; -//! use typesense::apis::collections_api; -//! use typesense::apis::configuration::{ApiKey, Configuration}; -//! -//! #[derive(Typesense, Serialize, Deserialize)] -//! #[typesense(collection_name = "companies", default_sorting_field = "num_employees")] -//! struct Company { -//! company_name: String, -//! num_employees: i32, -//! #[typesense(facet)] -//! country: String, -//! } +//! use serde::{Deserialize, Serialize}; +//! use typesense::{Client, Typesense, ExponentialBackoff, prelude::*}; +//! use reqwest::Url; +//! use std::time::Duration; +//! +//! /// A struct representing a company document. +//! #[derive(Typesense, Serialize, Deserialize, Debug)] +//! #[typesense( +//! collection_name = "companies", +//! default_sorting_field = "num_employees" +//! )] +//! struct Company { +//! company_name: String, +//! num_employees: i32, +//! #[typesense(facet)] +//! country: String, +//! } +//! +//! #[tokio::main] +//! async fn main() -> Result<(), Box> { +//! let client = Client::builder() +//! .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) +//! .api_key("xyz") +//! .healthcheck_interval(Duration::from_secs(60)) +//! .retry_policy(ExponentialBackoff::builder().build_with_max_retries(3)) +//! .connection_timeout(Duration::from_secs(5)) +//! .build()?; +//! +//! // Create the collection in Typesense +//! let collection = client +//! .collections() +//! .create(Company::collection_schema()) +//! .await?; //! -//! #[tokio::main] -//! async fn main() { -//! let config = Configuration { -//! base_path: "http://localhost:5000".to_owned(), -//! api_key: Some(ApiKey { -//! prefix: None, -//! key: "VerySecretKey".to_owned(), -//! }), -//! ..Default::default() -//! }; -//! -//! let collection = collections_api::create_collection(&config, Company::collection_schema()) -//! .await -//! .unwrap(); +//! println!("Created collection: {:?}", collection); +//! Ok(()) +//! } //! } +//! ``` +//! +//! --- +//! +//! ### WebAssembly (Wasm) +//! +//! This example is tailored for a WebAssembly target. +//! Key difference: Tokio-dependent features like `.retry_policy()` and `.connection_timeout()` +//! are disabled. You can still set them in the client builder but it will do nothing. +//! +//! ```no_run +//! #[cfg(target_family = "wasm")] +//! { +//! use serde::{Deserialize, Serialize}; +//! use typesense::{Client, Typesense, prelude::*}; +//! use reqwest::Url; +//! use std::time::Duration; +//! use wasm_bindgen_futures::spawn_local; +//! +//! /// A struct representing a company document. +//! #[derive(Typesense, Serialize, Deserialize, Debug)] +//! #[typesense( +//! collection_name = "companies", +//! default_sorting_field = "num_employees" +//! )] +//! struct Company { +//! company_name: String, +//! num_employees: i32, +//! #[typesense(facet)] +//! country: String, +//! } +//! +//! fn main() { +//! spawn_local(async { +//! let client = Client::builder() +//! .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) +//! .api_key("xyz") +//! .healthcheck_interval(Duration::from_secs(60)) +//! // .retry_policy(...) <-- disabled in Wasm +//! // .connection_timeout(...) <-- disabled in Wasm +//! .build() +//! .unwrap(); +//! +//! // Create the collection in Typesense +//! match client.collections().create(Company::collection_schema()).await { +//! Ok(collection) => println!("Created collection: {:?}", collection), +//! Err(e) => eprintln!("Error creating collection: {}", e), +//! } +//! }); +//! } //! } //! ``` mod client; @@ -49,7 +121,7 @@ pub mod error; pub mod models; pub mod prelude; -pub use client::Client; +pub use client::{Client, ExponentialBackoff}; pub use error::*; pub use models::*; diff --git a/typesense/src/models/document_index_parameters.rs b/typesense/src/models/document_index_parameters.rs index ae85edd..cee7a4a 100644 --- a/typesense/src/models/document_index_parameters.rs +++ b/typesense/src/models/document_index_parameters.rs @@ -1,9 +1,18 @@ use serde::{Deserialize, Serialize}; -/// Specify -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +/// Parameters for indexing documents into a Typesense collection. +/// +/// These parameters control how Typesense handles special cases such as +/// malformed, invalid, or "dirty" values during indexing. +/// +/// See the official Typesense documentation: +/// +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct DocumentIndexParameters { + /// Controls how Typesense handles "dirty values" (e.g. invalid dates, + /// numbers where a string is expected, values that don't match the schema). /// + /// If `None`, Typesense will use the default behavior (rejecting invalid data). #[serde(rename = "dirty_values", skip_serializing_if = "Option::is_none")] pub dirty_values: Option, } diff --git a/typesense/src/models/mod.rs b/typesense/src/models/mod.rs index 9bfcd7d..b41caf3 100644 --- a/typesense/src/models/mod.rs +++ b/typesense/src/models/mod.rs @@ -3,9 +3,8 @@ mod document_index_parameters; mod multi_search; mod scoped_key_parameters; -pub use document_index_parameters::DocumentIndexParameters; +pub use document_index_parameters::*; pub use scoped_key_parameters::*; -pub use typesense_codegen::apis::operations_api::TakeSnapshotParams; pub use typesense_codegen::models::*; pub use multi_search::MultiSearchBody; diff --git a/typesense/src/models/multi_search.rs b/typesense/src/models/multi_search.rs index 355c181..4efe08c 100644 --- a/typesense/src/models/multi_search.rs +++ b/typesense/src/models/multi_search.rs @@ -1,4 +1,3 @@ -use crate::models; use serde::{Deserialize, Serialize}; use typesense_codegen::models::MultiSearchCollectionParameters; @@ -7,124 +6,9 @@ use typesense_codegen::models::MultiSearchCollectionParameters; /// This struct acts as a container for a list of individual search queries that will be /// sent to the Typesense multi-search endpoint. Each search query is defined in a /// `MultiSearchCollectionParameters` struct within the `searches` vector. -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] pub struct MultiSearchBody { /// A vector of individual search queries to be executed. The order of the search results returned by Typesense will match the order of these queries. #[serde(rename = "searches")] - pub searches: Vec, -} - -impl MultiSearchBody { - /// Creates a new `MultiSearchBody` instance. - pub fn new(searches: Vec) -> MultiSearchBody { - MultiSearchBody { searches } - } -} - -impl MultiSearchBody { - /// Creates a new, empty builder. - pub fn builder() -> Self { - Self::default() - } - - /// Adds a single search query to the multi-search request. - /// - /// # Arguments - /// - /// * `search` - A `MultiSearchCollectionParameters` object representing an - /// individual search query. - pub fn add_search(mut self, search: MultiSearchCollectionParameters) -> Self { - self.searches.push(search); - self - } - - /// Adds multiple search queries to the multi-search request from an iterator. - /// - /// # Arguments - /// - /// * `searches` - An iterator that yields `MultiSearchCollectionParameters` objects. - pub fn add_searches( - mut self, - searches: impl IntoIterator, - ) -> Self { - self.searches.extend(searches); - self - } - - /// Consumes the builder and returns a `MultiSearchBody` object. - pub fn build(self) -> MultiSearchBody { - MultiSearchBody { - searches: self.searches, - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::models::MultiSearchCollectionParameters; - - #[test] - fn test_multi_search_builder_new_is_empty() { - let multi_search_request = MultiSearchBody::builder().build(); - assert!(multi_search_request.searches.is_empty()); - } - - #[test] - fn test_multi_search_builder_add_one_search() { - let search1 = MultiSearchCollectionParameters::builder() - .collection("products") - .q("shoe") - .build(); - - let multi_search_request = MultiSearchBody::builder() - .add_search(search1.clone()) - .build(); - - assert_eq!(multi_search_request.searches.len(), 1); - assert_eq!(multi_search_request.searches[0], search1); - } - - #[test] - fn test_multi_search_builder_add_multiple_searches_chained() { - let search1 = MultiSearchCollectionParameters::builder() - .collection("products") - .q("shoe") - .build(); - let search2 = MultiSearchCollectionParameters::builder() - .collection("brands") - .q("Nike") - .build(); - - let multi_search_request = MultiSearchBody::builder() - .add_search(search1.clone()) - .add_search(search2.clone()) - .build(); - - assert_eq!(multi_search_request.searches.len(), 2); - assert_eq!(multi_search_request.searches[0], search1); - assert_eq!(multi_search_request.searches[1], search2); - } - - #[test] - fn test_multi_search_builder_add_searches_from_iterator() { - let searches_vec = vec![ - MultiSearchCollectionParameters::builder() - .collection("c1") - .build(), - MultiSearchCollectionParameters::builder() - .collection("c2") - .build(), - MultiSearchCollectionParameters::builder() - .collection("c3") - .build(), - ]; - - let multi_search_request = MultiSearchBody::builder() - .add_searches(searches_vec.clone()) - .build(); - - assert_eq!(multi_search_request.searches.len(), 3); - assert_eq!(multi_search_request.searches, searches_vec); - } + pub searches: Vec, } diff --git a/typesense/src/models/scoped_key_parameters.rs b/typesense/src/models/scoped_key_parameters.rs index b423b96..0d2e168 100644 --- a/typesense/src/models/scoped_key_parameters.rs +++ b/typesense/src/models/scoped_key_parameters.rs @@ -15,7 +15,6 @@ pub struct ScopedKeyParameters { pub search_params: Option, /// The number of `multi_search` requests that can be performed using this key. - /// This is an optional parameter to further restrict the key's capabilities. #[serde(skip_serializing_if = "Option::is_none")] pub limit_multi_searches: Option, diff --git a/typesense/src/prelude.rs b/typesense/src/prelude.rs index 1aeb654..9552070 100644 --- a/typesense/src/prelude.rs +++ b/typesense/src/prelude.rs @@ -3,7 +3,7 @@ //! This module re-exports the most commonly used traits and types from the library, //! making them easy to import with a single `use` statement. -pub use crate::traits::{Document, FieldType, MultiSearchResultExt, ToTypesenseField}; +pub use crate::traits::*; // pub use crate::error::Error as TypesenseError; // pub use crate::error::MultiSearchParseError; diff --git a/typesense/src/traits/field_type.rs b/typesense/src/traits/field_type.rs index fd4dee2..9185828 100644 --- a/typesense/src/traits/field_type.rs +++ b/typesense/src/traits/field_type.rs @@ -1,4 +1,3 @@ -use crate::traits::Document; use std::collections::{BTreeMap, HashMap}; /// Type for a field. Currently it is a wrapping to a `String` but it could be extended to a enum pub type FieldType = String; @@ -10,19 +9,6 @@ pub trait ToTypesenseField { fn to_typesense_type() -> &'static str; } -/// Generic implementation for any type that is also a Typesense document. -impl ToTypesenseField for T { - fn to_typesense_type() -> &'static str { - "object" - } -} - -/// Generic implementation for a Vec of any type that is also a Typesense document. -impl ToTypesenseField for Vec { - fn to_typesense_type() -> &'static str { - "object[]" - } -} /// macro used internally to add implementations of ToTypesenseField for several rust types. #[macro_export] macro_rules! impl_to_typesense_field ( diff --git a/typesense/src/traits/mod.rs b/typesense/src/traits/mod.rs index 667128e..05203b4 100644 --- a/typesense/src/traits/mod.rs +++ b/typesense/src/traits/mod.rs @@ -6,4 +6,4 @@ mod multi_search_ext; pub use document::Document; pub use field_type::*; -pub use multi_search_ext::MultiSearchResultExt; +pub use multi_search_ext::{MultiSearchResultExt, UnionSearchResultExt}; diff --git a/typesense/src/traits/multi_search_ext.rs b/typesense/src/traits/multi_search_ext.rs index dff04f2..1200de6 100644 --- a/typesense/src/traits/multi_search_ext.rs +++ b/typesense/src/traits/multi_search_ext.rs @@ -1,4 +1,6 @@ use serde::de::DeserializeOwned; +use serde_json::Value; +use typesense_codegen::models::{self as raw_models, SearchGroupedHit, SearchResultHit}; use crate::{MultiSearchParseError, SearchResult}; @@ -16,3 +18,237 @@ pub trait MultiSearchResultExt { index: usize, ) -> Result, MultiSearchParseError>; } + +/// An extension trait for `typesense_codegen::models::MultiSearchResult` to provide typed parsing. +pub trait UnionSearchResultExt { + /// Parses the result at a specific index from a multi-search response into a strongly-typed `SearchResult`. + /// + /// # Arguments + /// * `index` - The zero-based index of the search result to parse. + /// + /// # Type Parameters + /// * `D` - The concrete document type to deserialize the hits into. + fn try_into_typed(self) -> Result, serde_json::Error>; +} + +fn multi_search_item_to_search_result( + item: &raw_models::MultiSearchResultItem, +) -> Result, serde_json::Error> { + let typed_hits = match &item.hits { + Some(raw_hits) => { + let hits_result: Result>, _> = raw_hits + .into_iter() + .map(|raw_hit| { + // Map each raw hit to a Result, _> + let document: Result, _> = raw_hit + .document + .clone() + .map(|doc_value| serde_json::from_value(doc_value)) + .transpose(); + Ok(SearchResultHit { + document: document?, + highlights: raw_hit.highlights.clone(), + highlight: raw_hit.highlight.clone(), + text_match: raw_hit.text_match, + text_match_info: raw_hit.text_match_info.clone(), + geo_distance_meters: raw_hit.geo_distance_meters.clone(), + vector_distance: raw_hit.vector_distance, + hybrid_search_info: raw_hit.hybrid_search_info.clone(), + search_index: raw_hit.search_index, + }) + }) + .collect(); + + Some(hits_result?) + } + None => None, + }; + // Parse grouped_hits into SearchGroupedHit + let typed_grouped_hits = match &item.grouped_hits { + Some(raw_groups) => { + let groups_result: Result>, _> = raw_groups + .iter() + .map(|raw_group| { + let hits_result: Result>, _> = raw_group + .hits + .iter() + .map(|raw_hit| { + let document: Result, _> = raw_hit + .document + .clone() + .map(|doc_value| serde_json::from_value(doc_value)) + .transpose(); + Ok(SearchResultHit { + document: document?, + highlights: raw_hit.highlights.clone(), + highlight: raw_hit.highlight.clone(), + text_match: raw_hit.text_match, + text_match_info: raw_hit.text_match_info.clone(), + geo_distance_meters: raw_hit.geo_distance_meters.clone(), + vector_distance: raw_hit.vector_distance, + hybrid_search_info: raw_hit.hybrid_search_info.clone(), + search_index: raw_hit.search_index.clone(), + }) + }) + .collect(); + + Ok(SearchGroupedHit { + found: raw_group.found, + group_key: raw_group.group_key.clone(), + hits: hits_result?, + }) + }) + .collect(); + Some(groups_result?) + } + None => None, + }; + + Ok(raw_models::SearchResult { + hits: typed_hits, + grouped_hits: typed_grouped_hits, + facet_counts: item.facet_counts.clone(), + found: item.found, + found_docs: item.found_docs, + out_of: item.out_of, + page: item.page, + search_time_ms: item.search_time_ms, + search_cutoff: item.search_cutoff, + request_params: item.request_params.clone(), + conversation: item.conversation.clone(), + union_request_params: item.union_request_params.clone(), + }) +} + +impl MultiSearchResultExt for raw_models::MultiSearchResult { + fn parse_at( + &self, + index: usize, + ) -> Result, MultiSearchParseError> { + let raw_item = self + .results + .get(index) + .ok_or(MultiSearchParseError::IndexOutOfBounds(index))?; + + if let Some(error_msg) = &raw_item.error { + return Err(MultiSearchParseError::ApiError { + index, + message: error_msg.clone(), + }); + } + + multi_search_item_to_search_result(raw_item) + .map_err(|source| MultiSearchParseError::Deserialization { index, source }) + } +} + +// This impl block specifically targets `SearchResult`. +// The methods inside will only be available on a search result of that exact type. +impl UnionSearchResultExt for SearchResult { + /// Attempts to convert a `SearchResult` into a `SearchResult`. + /// + /// This method is useful after a `perform_union` call where you know all resulting + /// documents share the same schema and can be deserialized into a single concrete type `D`. + /// + /// It iterates through each hit and tries to deserialize its `document` field. If any + /// document fails to deserialize into type `D`, the entire conversion fails. + /// + /// # Type Parameters + /// + /// * `D` - The concrete, `DeserializeOwned` type you want to convert the documents into. + /// + /// # Errors + /// + /// Returns a `serde_json::Error` if any document in the hit list cannot be successfully + /// deserialized into `D`. + fn try_into_typed(self) -> Result, serde_json::Error> { + // This logic is very similar to `from_raw`, but it converts between generic types + // instead of from a raw model. + let typed_hits = match self.hits { + Some(value_hits) => { + let hits_result: Result>, _> = value_hits + .into_iter() + .map(|value_hit| { + // `value_hit` here is `SearchResultHit` + let document: Option = match value_hit.document { + Some(doc_value) => Some(serde_json::from_value(doc_value)?), + None => None, + }; + + Ok(SearchResultHit { + document, + highlights: value_hit.highlights, + highlight: value_hit.highlight, + text_match: value_hit.text_match, + text_match_info: value_hit.text_match_info, + geo_distance_meters: value_hit.geo_distance_meters, + vector_distance: value_hit.vector_distance, + hybrid_search_info: value_hit.hybrid_search_info, + search_index: value_hit.search_index, + }) + }) + .collect(); + + Some(hits_result?) + } + None => None, + }; + + // Parse grouped_hits into SearchGroupedHit + let typed_grouped_hits = match &self.grouped_hits { + Some(raw_groups) => { + let groups_result: Result>, _> = raw_groups + .iter() + .map(|raw_group| { + let hits_result: Result>, _> = raw_group + .hits + .iter() + .map(|raw_hit| { + let document: Result, _> = raw_hit + .document + .clone() + .map(|doc_value| serde_json::from_value(doc_value)) + .transpose(); + Ok(SearchResultHit { + document: document?, + highlights: raw_hit.highlights.clone(), + highlight: raw_hit.highlight.clone(), + text_match: raw_hit.text_match, + text_match_info: raw_hit.text_match_info.clone(), + geo_distance_meters: raw_hit.geo_distance_meters.clone(), + vector_distance: raw_hit.vector_distance, + hybrid_search_info: raw_hit.hybrid_search_info.clone(), + search_index: raw_hit.search_index.clone(), + }) + }) + .collect(); + + Ok(SearchGroupedHit { + found: raw_group.found, + group_key: raw_group.group_key.clone(), + hits: hits_result?, + }) + }) + .collect(); + Some(groups_result?) + } + None => None, + }; + + Ok(SearchResult { + hits: typed_hits, + grouped_hits: typed_grouped_hits, + + found: self.found, + found_docs: self.found_docs, + out_of: self.out_of, + page: self.page, + search_time_ms: self.search_time_ms, + facet_counts: self.facet_counts, + search_cutoff: self.search_cutoff, + request_params: self.request_params, + conversation: self.conversation, + union_request_params: self.union_request_params, + }) + } +} diff --git a/typesense/tests/client/collections_test.rs b/typesense/tests/client/collections_test.rs index 84d3d23..a762e77 100644 --- a/typesense/tests/client/collections_test.rs +++ b/typesense/tests/client/collections_test.rs @@ -2,7 +2,6 @@ use typesense::{ GetCollectionsParameters, models::{CollectionSchema, CollectionUpdateSchema, Field}, }; -use typesense_codegen::apis::collections_api::GetCollectionParams; use super::{get_client, new_id}; @@ -46,7 +45,7 @@ async fn logic_test_collections_and_collection_lifecycle() { // --- 3. Retrieve all collections (via `collections`) --- let retrieve_all_result = client .collections() - .retrieve(&GetCollectionsParameters::default()) + .retrieve(GetCollectionsParameters::default()) .await; assert!( retrieve_all_result.is_ok(), diff --git a/typesense/tests/client/documents_test.rs b/typesense/tests/client/documents_test.rs index 8d94fc9..9bb47a8 100644 --- a/typesense/tests/client/documents_test.rs +++ b/typesense/tests/client/documents_test.rs @@ -136,7 +136,7 @@ async fn run_test_document_lifecycle() { ..Default::default() }; let import_res = documents_client - .import(new_books_jsonl, import_params) + .import_jsonl(new_books_jsonl, import_params) .await; assert!(import_res.is_ok(), "Bulk import failed"); diff --git a/typesense/tests/client/mod.rs b/typesense/tests/client/mod.rs index 6231090..0f7f5aa 100644 --- a/typesense/tests/client/mod.rs +++ b/typesense/tests/client/mod.rs @@ -3,6 +3,7 @@ mod collections_test; mod documents_test; mod keys_test; +mod multi_search_test; use reqwest::Url; use reqwest_retry::policies::ExponentialBackoff; diff --git a/typesense/tests/client/multi_search_test.rs b/typesense/tests/client/multi_search_test.rs new file mode 100644 index 0000000..ea567de --- /dev/null +++ b/typesense/tests/client/multi_search_test.rs @@ -0,0 +1,531 @@ +use serde::Deserialize; +use typesense::{ + models::{ + CollectionSchema, Field, ImportDocumentsParameters, MultiSearchBody, + MultiSearchCollectionParameters, MultiSearchParameters, SearchResult, + }, + prelude::*, +}; + +use super::{get_client, new_id}; + +async fn setup_multi_search_tests( + client: &typesense::Client, + products_collection_name: &str, + brands_collection_name: &str, +) { + // --- Create collections --- + let products_schema = CollectionSchema { + name: products_collection_name.to_string(), + fields: vec![ + Field::new("name".to_string(), "string".to_string()), + Field::new("price".to_string(), "int32".to_string()), + ], + ..Default::default() + }; + client.collections().create(products_schema).await.unwrap(); + + let brands_schema = CollectionSchema { + name: brands_collection_name.to_string(), + fields: vec![ + Field::new("company_name".to_string(), "string".to_string()), + Field::new("country".to_string(), "string".to_string()), + ], + ..Default::default() + }; + client.collections().create(brands_schema).await.unwrap(); + + // --- Index documents --- + let product_docs = r#" + {"id": "p1", "name": "iPhone 15", "price": 999} + {"id": "p2", "name": "MacBook Pro", "price": 1999} + "# + .trim() + .lines() + .map(|s| s.trim()) + .collect::>() + .join("\n"); + + client + .collection(products_collection_name) + .documents() + .import_jsonl( + product_docs, + ImportDocumentsParameters { + action: Some(typesense::models::IndexAction::Create), + ..Default::default() + }, + ) + .await + .unwrap(); + + let brand_docs = r#" + {"id": "b1", "company_name": "Apple Inc.", "country": "USA"} + {"id": "b2", "company_name": "Samsung", "country": "South Korea"} + "# + .trim() + .lines() + .map(|s| s.trim()) + .collect::>() + .join("\n"); + + client + .collection(brands_collection_name) + .documents() + .import_jsonl( + brand_docs, + ImportDocumentsParameters { + action: Some(typesense::models::IndexAction::Create), + ..Default::default() + }, + ) + .await + .unwrap(); +} + +async fn run_test_multi_search_federated() { + let client = get_client(); + let products_collection_name = new_id("products"); + let brands_collection_name = new_id("brands"); + setup_multi_search_tests(&client, &products_collection_name, &brands_collection_name).await; + + let search_requests = MultiSearchBody { + searches: vec![ + MultiSearchCollectionParameters { + q: Some("pro".into()), + query_by: Some("name".into()), + collection: Some(products_collection_name.clone()), + ..Default::default() + }, + MultiSearchCollectionParameters { + q: Some("USA".into()), + query_by: Some("country".into()), + collection: Some(brands_collection_name.clone()), + ..Default::default() + }, + ], + }; + + let common_params = MultiSearchParameters::default(); + + let result = client + .multi_search() + .perform(search_requests, common_params) + .await; + + assert!(result.is_ok(), "Multi-search request failed"); + let response = result.unwrap(); + + assert_eq!( + response.results.len(), + 2, + "Expected 2 sets of search results" + ); + + // --- Assert products result --- + let products_result = &response.results[0]; + assert!( + products_result.error.is_none(), + "First search returned an error" + ); + assert_eq!(products_result.found, Some(1)); + let product_hit = &products_result.hits.as_ref().unwrap()[0]; + let product_doc = product_hit.document.as_ref().unwrap().as_object().unwrap(); + assert_eq!( + product_doc.get("name").unwrap().as_str(), + Some("MacBook Pro") + ); + + // --- Assert brands result --- + let brands_result = &response.results[1]; + assert!( + brands_result.error.is_none(), + "Second search returned an error" + ); + assert_eq!(brands_result.found, Some(1)); + let brand_hit = &brands_result.hits.as_ref().unwrap()[0]; + let brand_doc = brand_hit.document.as_ref().unwrap().as_object().unwrap(); + assert_eq!( + brand_doc.get("company_name").unwrap().as_str(), + Some("Apple Inc.") + ); +} + +async fn run_test_multi_search_with_common_params() { + let client = get_client(); + let products_collection_name = new_id("products_common"); + let brands_collection_name = new_id("brands_common"); + setup_multi_search_tests(&client, &products_collection_name, &brands_collection_name).await; + + // Define individual searches, each with the correct `query_by` for its schema. + let search_requests = MultiSearchBody { + searches: vec![ + MultiSearchCollectionParameters { + collection: Some(products_collection_name.clone()), + q: Some("pro".into()), // This should find "Macbook Pro" + query_by: Some("name".into()), // Specific to the products schema + ..Default::default() + }, + MultiSearchCollectionParameters { + collection: Some(brands_collection_name.clone()), + q: Some("inc".into()), // This should find "Apple Inc." + query_by: Some("company_name".into()), // Specific to the brands schema + ..Default::default() + }, + ], + }; + + let common_params = MultiSearchParameters { + limit: Some(1), + ..Default::default() + }; + + let result = client + .multi_search() + .perform(search_requests, common_params) + .await; + + assert!( + result.is_ok(), + "Multi-search request failed: {:?}", + result.err() + ); + let response = result.unwrap(); + + assert_eq!(response.results.len(), 2); + + // --- Assert products result --- + let products_result = &response.results[0]; + assert!( + products_result.error.is_none(), + "Products search returned an error: {:?}", + products_result.error + ); + assert_eq!(products_result.found, Some(1)); + let product_hit = &products_result.hits.as_ref().unwrap()[0]; + assert_eq!( + product_hit.document.as_ref().unwrap()["name"], + "MacBook Pro" + ); + + // --- Assert brands result --- + let brands_result = &response.results[1]; + assert!( + brands_result.error.is_none(), + "Brands search returned an error: {:?}", + brands_result.error + ); + assert_eq!(brands_result.found, Some(1)); + let brand_hit = &brands_result.hits.as_ref().unwrap()[0]; + assert_eq!( + brand_hit.document.as_ref().unwrap()["company_name"], + "Apple Inc." + ); +} + +#[derive(Debug, Deserialize, PartialEq)] +struct Product { + id: String, + name: String, + price: i32, +} + +#[derive(Debug, Deserialize, PartialEq)] +struct Brand { + id: String, + company_name: String, + country: String, +} + +async fn run_test_multi_search_generic_parsing() { + let client = get_client(); + let products_collection_name = new_id("products_generic"); + let brands_collection_name = new_id("brands_generic"); + setup_multi_search_tests(&client, &products_collection_name, &brands_collection_name).await; + + let search_requests = MultiSearchBody { + searches: vec![ + // Search #0 for products + MultiSearchCollectionParameters { + q: Some("pro".into()), + query_by: Some("name".into()), + collection: Some(products_collection_name.clone()), + ..Default::default() + }, + // Search #1 for brands + MultiSearchCollectionParameters { + q: Some("USA".into()), + query_by: Some("country".into()), + collection: Some(brands_collection_name.clone()), + ..Default::default() + }, + ], + ..Default::default() + }; + + let common_params = MultiSearchParameters::default(); + + // Perform the search and get the raw, untyped response + let raw_response = client + .multi_search() + .perform(search_requests, common_params) + .await + .unwrap(); + + // --- Use the new generic parsing feature --- + + // Parse the first result set (index 0) into SearchResult + let products_result: SearchResult = + raw_response.parse_at(0).expect("Parsing products failed"); + + // Parse the second result set (index 1) into SearchResult + let brands_result: SearchResult = + raw_response.parse_at(1).expect("Parsing brands failed"); + + // --- Assert the strongly-typed results --- + + // Assert products result + assert_eq!(products_result.found, Some(1), "Expected to find 1 product"); + let product_hit = &products_result + .hits + .as_ref() + .unwrap() + .get(0) + .expect("No product hits found"); + let product_doc = product_hit + .document + .as_ref() + .expect("Product hit has no document"); + + assert_eq!(product_doc.name, "MacBook Pro"); + assert_eq!(product_doc.price, 1999); + assert_eq!( + *product_doc, + Product { + id: "p2".to_string(), + name: "MacBook Pro".to_string(), + price: 1999, + } + ); + + // Assert brands result + assert_eq!(brands_result.found, Some(1), "Expected to find 1 brand"); + let brand_hit = &brands_result + .hits + .as_ref() + .unwrap() + .get(0) + .expect("No brand hits found"); + let brand_doc = brand_hit + .document + .as_ref() + .expect("Brand hit has no document"); + + assert_eq!(brand_doc.company_name, "Apple Inc."); + assert_eq!( + *brand_doc, + Brand { + id: "b1".to_string(), + company_name: "Apple Inc.".to_string(), + country: "USA".to_string(), + } + ); +} + +async fn run_test_multi_search_union_heterogeneous() { + let client = get_client(); + let products_collection_name = new_id("products_union"); + let brands_collection_name = new_id("brands_union"); + setup_multi_search_tests(&client, &products_collection_name, &brands_collection_name).await; + + // We will search for "pro" in products and "samsung" in brands. + // This should yield one hit from each collection. + let search_requests = MultiSearchBody { + searches: vec![ + MultiSearchCollectionParameters { + q: Some("pro".into()), + query_by: Some("name".into()), + collection: Some(products_collection_name.clone()), + ..Default::default() + }, + MultiSearchCollectionParameters { + q: Some("samsung".into()), + query_by: Some("company_name".into()), + collection: Some(brands_collection_name.clone()), + ..Default::default() + }, + ], + }; + + let common_params = MultiSearchParameters::default(); + + // Call the new union function + let result = client + .multi_search() + .perform_union(search_requests, common_params) + .await; + + assert!( + result.is_ok(), + "Union multi-search request failed: {:?}", + result.err() + ); + let response = result.unwrap(); + + // In a union search, we expect a single merged result set. + // We found "MacBook Pro" and "Samsung". + assert_eq!(response.found, Some(2)); + let hits = response.hits.expect("Expected to find hits"); + assert_eq!(hits.len(), 2); + + // --- Process the heterogeneous hits --- + // This demonstrates how a user would handle the `serde_json::Value` documents. + let mut product_count = 0; + let mut brand_count = 0; + + for hit in hits { + let document = hit.document.as_ref().unwrap(); + + // Check for a field unique to the Product schema to identify the document type. + if document.get("price").is_some() { + let product: Product = + serde_json::from_value(document.clone()).expect("Failed to parse Product"); + assert_eq!(product.name, "MacBook Pro"); + product_count += 1; + } + // Check for a field unique to the Brand schema. + else if document.get("company_name").is_some() { + let brand: Brand = + serde_json::from_value(document.clone()).expect("Failed to parse Brand"); + assert_eq!(brand.company_name, "Samsung"); + brand_count += 1; + } + } + + // Verify that we correctly identified one of each type from the merged results. + assert_eq!( + product_count, 1, + "Expected to find 1 product in the union result" + ); + assert_eq!( + brand_count, 1, + "Expected to find 1 brand in the union result" + ); +} + +async fn run_test_multi_search_union_homogeneous_and_typed_conversion() { + let client = get_client(); + let products_collection_name = new_id("products_union_homo"); + // We only need one collection for this test, but the setup creates two. + let brands_collection_name = new_id("brands_union_homo_unused"); + setup_multi_search_tests(&client, &products_collection_name, &brands_collection_name).await; + + // Both search queries target the *same* products collection. + let search_requests = MultiSearchBody { + searches: vec![ + // This query should find "iPhone 15" + MultiSearchCollectionParameters { + q: Some("iphone".into()), + query_by: Some("name".into()), + collection: Some(products_collection_name.clone()), + ..Default::default() + }, + // This query should find "MacBook Pro" + MultiSearchCollectionParameters { + q: Some("macbook".into()), + query_by: Some("name".into()), + collection: Some(products_collection_name.clone()), + ..Default::default() + }, + ], + }; + + // 1. Call perform_union, which returns a SearchResult + let value_result = client + .multi_search() + .perform_union(search_requests, MultiSearchParameters::default()) + .await + .expect("Union search failed"); + + // 2. Use the helper to convert it to a SearchResult + let typed_result: SearchResult = value_result + .try_into_typed() + .expect("Conversion to typed result failed"); + + // 3. Assert the strongly-typed result + assert_eq!(typed_result.found, Some(2)); + let mut hits = typed_result.hits.expect("Expected hits"); + + // Sort by price to have a predictable order for assertions. + hits.sort_by_key(|h| h.document.as_ref().unwrap().price); + + // Assert the first hit (iPhone) + let iphone = &hits[0].document.as_ref().unwrap(); + assert_eq!(iphone.name, "iPhone 15"); + assert_eq!(iphone.price, 999); + + // Assert the second hit (MacBook Pro) + let macbook = &hits[1].document.as_ref().unwrap(); + assert_eq!(macbook.name, "MacBook Pro"); + assert_eq!(macbook.price, 1999); +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tokio_test { + use super::*; + + #[tokio::test] + async fn test_multi_search_federated() { + run_test_multi_search_federated().await; + } + #[tokio::test] + async fn test_multi_search_with_common_params() { + run_test_multi_search_with_common_params().await; + } + #[tokio::test] + async fn test_multi_search_generic_parsing() { + run_test_multi_search_generic_parsing().await; + } + #[tokio::test] + async fn test_multi_search_union_heterogeneous() { + run_test_multi_search_union_heterogeneous().await; + } + #[tokio::test] + async fn test_multi_search_union_homogeneous_and_typed_conversion() { + run_test_multi_search_union_homogeneous_and_typed_conversion().await; + } +} + +#[cfg(all(test, target_arch = "wasm32"))] +mod wasm_test { + use super::*; + use wasm_bindgen_test::wasm_bindgen_test; + + wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser); + + #[wasm_bindgen_test] + async fn test_multi_search_federated() { + console_error_panic_hook::set_once(); + run_test_multi_search_federated().await; + } + #[wasm_bindgen_test] + async fn test_multi_search_with_common_params() { + console_error_panic_hook::set_once(); + run_test_multi_search_with_common_params().await; + } + #[wasm_bindgen_test] + async fn test_multi_search_generic_parsing() { + console_error_panic_hook::set_once(); + run_test_multi_search_generic_parsing().await; + } + #[wasm_bindgen_test] + async fn test_multi_search_union_heterogeneous() { + console_error_panic_hook::set_once(); + run_test_multi_search_union_heterogeneous().await; + } + #[wasm_bindgen_test] + async fn test_multi_search_union_homogeneous_and_typed_conversion() { + console_error_panic_hook::set_once(); + run_test_multi_search_union_homogeneous_and_typed_conversion().await; + } +} From f4df267f744d494d1d90b0c19149fd3cad96f200 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Wed, 3 Sep 2025 17:58:24 +0700 Subject: [PATCH 08/41] refactor multi search extension --- typesense/src/traits/multi_search_ext.rs | 274 ++++++++++------------- 1 file changed, 117 insertions(+), 157 deletions(-) diff --git a/typesense/src/traits/multi_search_ext.rs b/typesense/src/traits/multi_search_ext.rs index 1200de6..43a4c11 100644 --- a/typesense/src/traits/multi_search_ext.rs +++ b/typesense/src/traits/multi_search_ext.rs @@ -1,10 +1,10 @@ +use crate::models::{MultiSearchResult, MultiSearchResultItem, SearchGroupedHit, SearchResultHit}; use serde::de::DeserializeOwned; use serde_json::Value; -use typesense_codegen::models::{self as raw_models, SearchGroupedHit, SearchResultHit}; use crate::{MultiSearchParseError, SearchResult}; -/// An extension trait for `typesense_codegen::models::MultiSearchResult` to provide typed parsing. +/// An extension trait for `MultiSearchResult` to provide typed parsing. pub trait MultiSearchResultExt { /// Parses the result at a specific index from a multi-search response into a strongly-typed `SearchResult`. /// @@ -19,92 +19,122 @@ pub trait MultiSearchResultExt { ) -> Result, MultiSearchParseError>; } -/// An extension trait for `typesense_codegen::models::MultiSearchResult` to provide typed parsing. +/// An extension trait for `SearchResult` to provide typed parsing. +/// +/// This is primarily useful when working with results from a **union search**. +/// Since union searches return documents as raw JSON (`serde_json::Value`), +/// this trait allows you to attempt conversion into a concrete typed document +/// model of your choosing. pub trait UnionSearchResultExt { - /// Parses the result at a specific index from a multi-search response into a strongly-typed `SearchResult`. - /// - /// # Arguments - /// * `index` - The zero-based index of the search result to parse. + /// Attempts to convert a `SearchResult` into a `SearchResult`. /// /// # Type Parameters /// * `D` - The concrete document type to deserialize the hits into. + /// + /// # Errors + /// Returns a `serde_json::Error` if any document in the result cannot be + /// successfully deserialized into type `D`. fn try_into_typed(self) -> Result, serde_json::Error>; } +/// Small helpers to convert documents stored as `serde_json::Value` into a concrete `D`. +fn deserialize_opt_document( + doc: Option, +) -> Result, serde_json::Error> { + match doc { + Some(v) => Ok(Some(serde_json::from_value(v)?)), + None => Ok(None), + } +} + +fn convert_hit_ref( + raw_hit: &SearchResultHit, +) -> Result, serde_json::Error> { + Ok(SearchResultHit { + document: deserialize_opt_document(raw_hit.document.clone())?, + highlights: raw_hit.highlights.clone(), + highlight: raw_hit.highlight.clone(), + text_match: raw_hit.text_match, + text_match_info: raw_hit.text_match_info.clone(), + geo_distance_meters: raw_hit.geo_distance_meters.clone(), + vector_distance: raw_hit.vector_distance, + hybrid_search_info: raw_hit.hybrid_search_info.clone(), + search_index: raw_hit.search_index.clone(), + }) +} + +fn convert_group_ref( + raw_group: &SearchGroupedHit, +) -> Result, serde_json::Error> { + let hits = raw_group + .hits + .iter() + .map(convert_hit_ref::) + .collect::, _>>()?; + + Ok(SearchGroupedHit { + found: raw_group.found, + group_key: raw_group.group_key.clone(), + hits, + }) +} + +fn convert_hit_owned( + value_hit: SearchResultHit, +) -> Result, serde_json::Error> { + Ok(SearchResultHit { + document: deserialize_opt_document(value_hit.document)?, + highlights: value_hit.highlights, + highlight: value_hit.highlight, + text_match: value_hit.text_match, + text_match_info: value_hit.text_match_info, + geo_distance_meters: value_hit.geo_distance_meters, + vector_distance: value_hit.vector_distance, + hybrid_search_info: value_hit.hybrid_search_info, + search_index: value_hit.search_index, + }) +} +fn convert_group_owned( + group: SearchGroupedHit, +) -> Result, serde_json::Error> { + let hits = group + .hits + .into_iter() + .map(convert_hit_owned::) + .collect::, _>>()?; + + Ok(SearchGroupedHit { + found: group.found, + group_key: group.group_key, + hits, + }) +} + +/// Convert a single `MultiSearchResultItem` into a strongly-typed `SearchResult`. fn multi_search_item_to_search_result( - item: &raw_models::MultiSearchResultItem, -) -> Result, serde_json::Error> { + item: &MultiSearchResultItem, +) -> Result, serde_json::Error> { let typed_hits = match &item.hits { - Some(raw_hits) => { - let hits_result: Result>, _> = raw_hits - .into_iter() - .map(|raw_hit| { - // Map each raw hit to a Result, _> - let document: Result, _> = raw_hit - .document - .clone() - .map(|doc_value| serde_json::from_value(doc_value)) - .transpose(); - Ok(SearchResultHit { - document: document?, - highlights: raw_hit.highlights.clone(), - highlight: raw_hit.highlight.clone(), - text_match: raw_hit.text_match, - text_match_info: raw_hit.text_match_info.clone(), - geo_distance_meters: raw_hit.geo_distance_meters.clone(), - vector_distance: raw_hit.vector_distance, - hybrid_search_info: raw_hit.hybrid_search_info.clone(), - search_index: raw_hit.search_index, - }) - }) - .collect(); - - Some(hits_result?) - } + Some(raw_hits) => Some( + raw_hits + .iter() + .map(convert_hit_ref::) + .collect::, _>>()?, + ), None => None, }; - // Parse grouped_hits into SearchGroupedHit + let typed_grouped_hits = match &item.grouped_hits { - Some(raw_groups) => { - let groups_result: Result>, _> = raw_groups + Some(raw_groups) => Some( + raw_groups .iter() - .map(|raw_group| { - let hits_result: Result>, _> = raw_group - .hits - .iter() - .map(|raw_hit| { - let document: Result, _> = raw_hit - .document - .clone() - .map(|doc_value| serde_json::from_value(doc_value)) - .transpose(); - Ok(SearchResultHit { - document: document?, - highlights: raw_hit.highlights.clone(), - highlight: raw_hit.highlight.clone(), - text_match: raw_hit.text_match, - text_match_info: raw_hit.text_match_info.clone(), - geo_distance_meters: raw_hit.geo_distance_meters.clone(), - vector_distance: raw_hit.vector_distance, - hybrid_search_info: raw_hit.hybrid_search_info.clone(), - search_index: raw_hit.search_index.clone(), - }) - }) - .collect(); - - Ok(SearchGroupedHit { - found: raw_group.found, - group_key: raw_group.group_key.clone(), - hits: hits_result?, - }) - }) - .collect(); - Some(groups_result?) - } + .map(convert_group_ref::) + .collect::, _>>()?, + ), None => None, }; - Ok(raw_models::SearchResult { + Ok(SearchResult { hits: typed_hits, grouped_hits: typed_grouped_hits, facet_counts: item.facet_counts.clone(), @@ -120,7 +150,8 @@ fn multi_search_item_to_search_result( }) } -impl MultiSearchResultExt for raw_models::MultiSearchResult { +/// Extension to parse an item out of a `MultiSearchResult` into a typed `SearchResult`. +impl MultiSearchResultExt for MultiSearchResult { fn parse_at( &self, index: usize, @@ -142,103 +173,32 @@ impl MultiSearchResultExt for raw_models::MultiSearchResult { } } -// This impl block specifically targets `SearchResult`. -// The methods inside will only be available on a search result of that exact type. +/// Trait for converting a `SearchResult` (union result) into a typed one. impl UnionSearchResultExt for SearchResult { - /// Attempts to convert a `SearchResult` into a `SearchResult`. - /// - /// This method is useful after a `perform_union` call where you know all resulting - /// documents share the same schema and can be deserialized into a single concrete type `D`. - /// - /// It iterates through each hit and tries to deserialize its `document` field. If any - /// document fails to deserialize into type `D`, the entire conversion fails. - /// - /// # Type Parameters - /// - /// * `D` - The concrete, `DeserializeOwned` type you want to convert the documents into. - /// - /// # Errors - /// - /// Returns a `serde_json::Error` if any document in the hit list cannot be successfully - /// deserialized into `D`. fn try_into_typed(self) -> Result, serde_json::Error> { - // This logic is very similar to `from_raw`, but it converts between generic types - // instead of from a raw model. let typed_hits = match self.hits { - Some(value_hits) => { - let hits_result: Result>, _> = value_hits + Some(value_hits) => Some( + value_hits .into_iter() - .map(|value_hit| { - // `value_hit` here is `SearchResultHit` - let document: Option = match value_hit.document { - Some(doc_value) => Some(serde_json::from_value(doc_value)?), - None => None, - }; - - Ok(SearchResultHit { - document, - highlights: value_hit.highlights, - highlight: value_hit.highlight, - text_match: value_hit.text_match, - text_match_info: value_hit.text_match_info, - geo_distance_meters: value_hit.geo_distance_meters, - vector_distance: value_hit.vector_distance, - hybrid_search_info: value_hit.hybrid_search_info, - search_index: value_hit.search_index, - }) - }) - .collect(); - - Some(hits_result?) - } + .map(convert_hit_owned::) + .collect::, _>>()?, + ), None => None, }; - // Parse grouped_hits into SearchGroupedHit - let typed_grouped_hits = match &self.grouped_hits { - Some(raw_groups) => { - let groups_result: Result>, _> = raw_groups - .iter() - .map(|raw_group| { - let hits_result: Result>, _> = raw_group - .hits - .iter() - .map(|raw_hit| { - let document: Result, _> = raw_hit - .document - .clone() - .map(|doc_value| serde_json::from_value(doc_value)) - .transpose(); - Ok(SearchResultHit { - document: document?, - highlights: raw_hit.highlights.clone(), - highlight: raw_hit.highlight.clone(), - text_match: raw_hit.text_match, - text_match_info: raw_hit.text_match_info.clone(), - geo_distance_meters: raw_hit.geo_distance_meters.clone(), - vector_distance: raw_hit.vector_distance, - hybrid_search_info: raw_hit.hybrid_search_info.clone(), - search_index: raw_hit.search_index.clone(), - }) - }) - .collect(); - - Ok(SearchGroupedHit { - found: raw_group.found, - group_key: raw_group.group_key.clone(), - hits: hits_result?, - }) - }) - .collect(); - Some(groups_result?) - } + let typed_grouped_hits = match self.grouped_hits { + Some(raw_groups) => Some( + raw_groups + .into_iter() + .map(convert_group_owned::) + .collect::, _>>()?, + ), None => None, }; Ok(SearchResult { hits: typed_hits, grouped_hits: typed_grouped_hits, - found: self.found, found_docs: self.found_docs, out_of: self.out_of, From 41ce84fd9e5535c64368dfa4d637e38af1a22fd5 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Wed, 3 Sep 2025 18:02:23 +0700 Subject: [PATCH 09/41] fix lint --- typesense/src/client/mod.rs | 2 +- typesense/src/traits/multi_search_ext.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/typesense/src/client/mod.rs b/typesense/src/client/mod.rs index d285786..25dcfb8 100644 --- a/typesense/src/client/mod.rs +++ b/typesense/src/client/mod.rs @@ -275,7 +275,7 @@ impl Client { /// The core execution method that handles multi-node failover and retries. /// This internal method is called by all public API methods. - pub(super) async fn execute<'a, F, Fut, T, E>(&'a self, api_call: F) -> Result> + pub(super) async fn execute(&self, api_call: F) -> Result> where F: Fn(configuration::Configuration) -> Fut, Fut: Future>>, diff --git a/typesense/src/traits/multi_search_ext.rs b/typesense/src/traits/multi_search_ext.rs index 43a4c11..e5d3865 100644 --- a/typesense/src/traits/multi_search_ext.rs +++ b/typesense/src/traits/multi_search_ext.rs @@ -58,7 +58,7 @@ fn convert_hit_ref( geo_distance_meters: raw_hit.geo_distance_meters.clone(), vector_distance: raw_hit.vector_distance, hybrid_search_info: raw_hit.hybrid_search_info.clone(), - search_index: raw_hit.search_index.clone(), + search_index: raw_hit.search_index, }) } From 94e2687c60d34b31a413a4420f5ea3570307cc55 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Wed, 3 Sep 2025 18:05:38 +0700 Subject: [PATCH 10/41] rename folder from `custom-template` to `openapi-generator-template` and remove unused templates --- custom-templates/hyper/api.mustache | 182 ------ custom-templates/hyper/api_mod.mustache | 83 --- custom-templates/hyper/client.mustache | 55 -- custom-templates/hyper/configuration.mustache | 83 --- custom-templates/hyper0x/api.mustache | 181 ------ custom-templates/hyper0x/api_mod.mustache | 64 -- custom-templates/hyper0x/client.mustache | 54 -- .../hyper0x/configuration.mustache | 34 -- custom-templates/reqwest-trait/api.mustache | 558 ------------------ .../reqwest-trait/api_mod.mustache | 236 -------- .../reqwest-trait/configuration.mustache | 120 ---- .../.travis.yml | 0 .../Cargo.mustache | 0 .../README.mustache | 0 .../api_doc.mustache | 0 .../git_push.sh.mustache | 0 .../gitignore.mustache | 0 .../lib.mustache | 0 .../model.mustache | 0 .../model_doc.mustache | 0 .../model_mod.mustache | 0 .../partial_header.mustache | 0 .../request.rs | 0 .../reqwest/api.mustache | 0 .../reqwest/api_mod.mustache | 0 .../reqwest/configuration.mustache | 0 xtask/src/main.rs | 2 +- 27 files changed, 1 insertion(+), 1651 deletions(-) delete mode 100644 custom-templates/hyper/api.mustache delete mode 100644 custom-templates/hyper/api_mod.mustache delete mode 100644 custom-templates/hyper/client.mustache delete mode 100644 custom-templates/hyper/configuration.mustache delete mode 100644 custom-templates/hyper0x/api.mustache delete mode 100644 custom-templates/hyper0x/api_mod.mustache delete mode 100644 custom-templates/hyper0x/client.mustache delete mode 100644 custom-templates/hyper0x/configuration.mustache delete mode 100644 custom-templates/reqwest-trait/api.mustache delete mode 100644 custom-templates/reqwest-trait/api_mod.mustache delete mode 100644 custom-templates/reqwest-trait/configuration.mustache rename {custom-templates => openapi-generator-template}/.travis.yml (100%) rename {custom-templates => openapi-generator-template}/Cargo.mustache (100%) rename {custom-templates => openapi-generator-template}/README.mustache (100%) rename {custom-templates => openapi-generator-template}/api_doc.mustache (100%) rename {custom-templates => openapi-generator-template}/git_push.sh.mustache (100%) rename {custom-templates => openapi-generator-template}/gitignore.mustache (100%) rename {custom-templates => openapi-generator-template}/lib.mustache (100%) rename {custom-templates => openapi-generator-template}/model.mustache (100%) rename {custom-templates => openapi-generator-template}/model_doc.mustache (100%) rename {custom-templates => openapi-generator-template}/model_mod.mustache (100%) rename {custom-templates => openapi-generator-template}/partial_header.mustache (100%) rename {custom-templates => openapi-generator-template}/request.rs (100%) rename {custom-templates => openapi-generator-template}/reqwest/api.mustache (100%) rename {custom-templates => openapi-generator-template}/reqwest/api_mod.mustache (100%) rename {custom-templates => openapi-generator-template}/reqwest/configuration.mustache (100%) diff --git a/custom-templates/hyper/api.mustache b/custom-templates/hyper/api.mustache deleted file mode 100644 index 9c0f7fd..0000000 --- a/custom-templates/hyper/api.mustache +++ /dev/null @@ -1,182 +0,0 @@ -{{>partial_header}} -use std::sync::Arc; -use std::borrow::Borrow; -use std::pin::Pin; -#[allow(unused_imports)] -use std::option::Option; - -use hyper; -use hyper_util::client::legacy::connect::Connect; -use futures::Future; - -use crate::models; -use super::{Error, configuration}; -use super::request as __internal_request; - -pub struct {{{classname}}}Client - where C: Clone + std::marker::Send + Sync + 'static { - configuration: Arc>, -} - -impl {{{classname}}}Client - where C: Clone + std::marker::Send + Sync { - pub fn new(configuration: Arc>) -> {{{classname}}}Client { - {{{classname}}}Client { - configuration, - } - } -} - -pub trait {{{classname}}}: Send + Sync { -{{#operations}} -{{#operation}} - fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isString}}{{^isUuid}}&str{{/isUuid}}{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> Pin> + Send>>; -{{/operation}} -{{/operations}} -} - -impl{{{classname}}} for {{{classname}}}Client - where C: Clone + std::marker::Send + Sync { - {{#operations}} - {{#operation}} - #[allow(unused_mut)] - fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isString}}{{^isUuid}}&str{{/isUuid}}{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> Pin> + Send>> { - let mut req = __internal_request::Request::new(hyper::Method::{{{httpMethod.toUpperCase}}}, "{{{path}}}".to_string()) - {{#hasAuthMethods}} - {{#authMethods}} - {{#isApiKey}} - .with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{ - in_header: {{#isKeyInHeader}}true{{/isKeyInHeader}}{{^isKeyInHeader}}false{{/isKeyInHeader}}, - in_query: {{#isKeyInQuery}}true{{/isKeyInQuery}}{{^isKeyInQuery}}false{{/isKeyInQuery}}, - param_name: "{{{keyParamName}}}".to_owned(), - })) - {{/isApiKey}} - {{#isBasicBasic}} - .with_auth(__internal_request::Auth::Basic) - {{/isBasicBasic}} - {{#isOAuth}} - .with_auth(__internal_request::Auth::Oauth) - {{/isOAuth}} - {{/authMethods}} - {{/hasAuthMethods}} - ; - {{#queryParams}} - {{#required}} - {{^isNullable}} - req = req.with_query_param("{{{baseName}}}".to_string(), {{{paramName}}}{{#isArray}}.join(","){{/isArray}}.to_string()); - {{/isNullable}} - {{#isNullable}} - match {{{paramName}}} { - Some(param_value) => { req = req.with_query_param("{{{baseName}}}".to_string(), param_value{{#isArray}}.join(","){{/isArray}}.to_string()); }, - None => { req = req.with_query_param("{{{baseName}}}".to_string(), "".to_string()); }, - } - {{/isNullable}} - {{/required}} - {{^required}} - if let Some(ref s) = {{{paramName}}} { - {{#isArray}} - let query_value = s.iter().map(|s| s.to_string()).collect::>().join(","); - {{/isArray}} - {{^isArray}} - let query_value = match serde_json::to_string(s) { - Ok(value) => value, - Err(e) => return Box::pin(futures::future::err(Error::Serde(e))), - }; - {{/isArray}} - req = req.with_query_param("{{{baseName}}}".to_string(), query_value); - } - {{/required}} - {{/queryParams}} - {{#pathParams}} - {{#required}} - {{^isNullable}} - req = req.with_path_param("{{{baseName}}}".to_string(), {{{paramName}}}{{#isArray}}.join(","){{/isArray}}.to_string()); - {{/isNullable}} - {{#isNullable}} - match {{{paramName}}} { - Some(param_value) => { req = req.with_path_param("{{{baseName}}}".to_string(), param_value{{#isArray}}.join(","){{/isArray}}.to_string()); }, - None => { req = req.with_path_param("{{{baseName}}}".to_string(), "".to_string()); }, - } - {{/isNullable}} - {{/required}} - {{^required}} - if let Some(param_value) = {{{paramName}}} { - req = req.with_path_param("{{{baseName}}}".to_string(), param_value{{#isArray}}.join(","){{/isArray}}.to_string()); - } - {{/required}} - {{/pathParams}} - {{#hasHeaderParams}} - {{#headerParams}} - {{#required}} - {{^isNullable}} - req = req.with_header_param("{{{baseName}}}".to_string(), {{{paramName}}}{{#isArray}}.join(","){{/isArray}}.to_string()); - {{/isNullable}} - {{#isNullable}} - match {{{paramName}}} { - Some(param_value) => { req = req.with_header_param("{{{baseName}}}".to_string(), param_value{{#isArray}}.join(","){{/isArray}}.to_string()); }, - None => { req = req.with_header_param("{{{baseName}}}".to_string(), "".to_string()); }, - } - {{/isNullable}} - {{/required}} - {{^required}} - if let Some(param_value) = {{{paramName}}} { - req = req.with_header_param("{{{baseName}}}".to_string(), param_value{{#isArray}}.join(","){{/isArray}}.to_string()); - } - {{/required}} - {{/headerParams}} - {{/hasHeaderParams}} - {{#hasFormParams}} - {{#formParams}} - {{#isFile}} - {{#required}} - {{^isNullable}} - req = req.with_form_param("{{{baseName}}}".to_string(), unimplemented!()); - {{/isNullable}} - {{#isNullable}} - match {{{paramName}}} { - Some(param_value) => { req = req.with_form_param("{{{baseName}}}".to_string(), unimplemented!()); }, - None => { req = req.with_form_param("{{{baseName}}}".to_string(), unimplemented!()); }, - } - {{/isNullable}} - {{/required}} - {{^required}} - if let Some(param_value) = {{{paramName}}} { - req = req.with_form_param("{{{baseName}}}".to_string(), unimplemented!()); - } - {{/required}} - {{/isFile}} - {{^isFile}} - {{#required}} - {{^isNullable}} - req = req.with_form_param("{{{baseName}}}".to_string(), {{{paramName}}}{{#isArray}}.join(","){{/isArray}}.to_string()); - {{/isNullable}} - {{#isNullable}} - match {{{paramName}}} { - Some(param_value) => { req = req.with_form_param("{{{baseName}}}".to_string(), param_value{{#isArray}}.join(","){{/isArray}}.to_string()); }, - None => { req = req.with_form_param("{{{baseName}}}".to_string(), "".to_string()); }, - } - {{/isNullable}} - {{/required}} - {{^required}} - if let Some(param_value) = {{{paramName}}} { - req = req.with_form_param("{{{baseName}}}".to_string(), param_value{{#isArray}}.join(","){{/isArray}}.to_string()); - } - {{/required}} - {{/isFile}} - {{/formParams}} - {{/hasFormParams}} - {{#hasBodyParam}} - {{#bodyParams}} - req = req.with_body_param({{{paramName}}}); - {{/bodyParams}} - {{/hasBodyParam}} - {{^returnType}} - req = req.returns_nothing(); - {{/returnType}} - - req.execute(self.configuration.borrow()) - } - -{{/operation}} -{{/operations}} -} diff --git a/custom-templates/hyper/api_mod.mustache b/custom-templates/hyper/api_mod.mustache deleted file mode 100644 index 67baa44..0000000 --- a/custom-templates/hyper/api_mod.mustache +++ /dev/null @@ -1,83 +0,0 @@ -use std::fmt; -use std::fmt::Debug; - -use hyper; -use hyper::http; -use hyper_util::client::legacy::connect::Connect; -use serde_json; - -#[derive(Debug)] -pub enum Error { - Api(ApiError), - Header(http::header::InvalidHeaderValue), - Http(http::Error), - Hyper(hyper::Error), - HyperClient(hyper_util::client::legacy::Error), - Serde(serde_json::Error), - UriError(http::uri::InvalidUri), -} - -pub struct ApiError { - pub code: hyper::StatusCode, - pub body: hyper::body::Incoming, -} - -impl Debug for ApiError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("ApiError") - .field("code", &self.code) - .field("body", &"hyper::body::Incoming") - .finish() - } -} - -impl From<(hyper::StatusCode, hyper::body::Incoming)> for Error { - fn from(e: (hyper::StatusCode, hyper::body::Incoming)) -> Self { - Error::Api(ApiError { - code: e.0, - body: e.1, - }) - } -} - -impl From for Error { - fn from(e: http::Error) -> Self { - Error::Http(e) - } -} - -impl From for Error { - fn from(e: hyper_util::client::legacy::Error) -> Self { - Error::HyperClient(e) - } -} - -impl From for Error { - fn from(e: hyper::Error) -> Self { - Error::Hyper(e) - } -} - -impl From for Error { - fn from(e: serde_json::Error) -> Self { - Error::Serde(e) - } -} - -mod request; - -{{#apiInfo}} -{{#apis}} -mod {{{classFilename}}}; -{{#operations}} -{{#operation}} -{{#-last}} -pub use self::{{{classFilename}}}::{ {{{classname}}}, {{{classname}}}Client }; -{{/-last}} -{{/operation}} -{{/operations}} -{{/apis}} -{{/apiInfo}} - -pub mod configuration; -pub mod client; diff --git a/custom-templates/hyper/client.mustache b/custom-templates/hyper/client.mustache deleted file mode 100644 index d54e334..0000000 --- a/custom-templates/hyper/client.mustache +++ /dev/null @@ -1,55 +0,0 @@ -use std::sync::Arc; - -use hyper; -use hyper_util::client::legacy::connect::Connect; -use super::configuration::Configuration; - -pub struct APIClient { -{{#apiInfo}} -{{#apis}} -{{#operations}} -{{#operation}} - {{#-last}} - {{{classFilename}}}: Box, - {{/-last}} -{{/operation}} -{{/operations}} -{{/apis}} -{{/apiInfo}} -} - -impl APIClient { - pub fn new(configuration: Configuration) -> APIClient - where C: Clone + std::marker::Send + Sync + 'static { - let rc = Arc::new(configuration); - - APIClient { -{{#apiInfo}} -{{#apis}} -{{#operations}} -{{#operation}} - {{#-last}} - {{{classFilename}}}: Box::new(crate::apis::{{{classname}}}Client::new(rc.clone())), - {{/-last}} -{{/operation}} -{{/operations}} -{{/apis}} -{{/apiInfo}} - } - } - -{{#apiInfo}} -{{#apis}} -{{#operations}} -{{#operation}} -{{#-last}} - pub fn {{{classFilename}}}(&self) -> &dyn crate::apis::{{{classname}}}{ - self.{{{classFilename}}}.as_ref() - } - -{{/-last}} -{{/operation}} -{{/operations}} -{{/apis}} -{{/apiInfo}} -} diff --git a/custom-templates/hyper/configuration.mustache b/custom-templates/hyper/configuration.mustache deleted file mode 100644 index 43a48ff..0000000 --- a/custom-templates/hyper/configuration.mustache +++ /dev/null @@ -1,83 +0,0 @@ -{{>partial_header}} -use hyper; -use hyper_util::client::legacy::Client; -use hyper_util::client::legacy::connect::Connect; -use hyper_util::client::legacy::connect::HttpConnector; -use hyper_util::rt::TokioExecutor; - -pub struct Configuration - where C: Clone + std::marker::Send + Sync + 'static { - pub base_path: String, - pub user_agent: Option, - pub client: Client, - pub basic_auth: Option, - pub oauth_access_token: Option, - pub api_key: Option, - // TODO: take an oauth2 token source, similar to the go one -} - -pub type BasicAuth = (String, Option); - -pub struct ApiKey { - pub prefix: Option, - pub key: String, -} - -impl Configuration { - /// Construct a default [`Configuration`](Self) with a hyper client using a default - /// [`HttpConnector`](hyper_util::client::legacy::connect::HttpConnector). - /// - /// Use [`with_client`](Configuration::with_client) to construct a Configuration with a - /// custom hyper client. - /// - /// # Example - /// - /// ``` - /// # use {{externCrateName}}::apis::configuration::Configuration; - /// let api_config = Configuration { - /// basic_auth: Some(("user".into(), None)), - /// ..Configuration::new() - /// }; - /// ``` - pub fn new() -> Configuration { - Configuration::default() - } -} - -impl Configuration - where C: Clone + std::marker::Send + Sync { - - /// Construct a new Configuration with a custom hyper client. - /// - /// # Example - /// - /// ``` - /// # use core::time::Duration; - /// # use {{externCrateName}}::apis::configuration::Configuration; - /// use hyper_util::client::legacy::Client; - /// use hyper_util::rt::TokioExecutor; - /// - /// let client = Client::builder(TokioExecutor::new()) - /// .pool_idle_timeout(Duration::from_secs(30)) - /// .build_http(); - /// - /// let api_config = Configuration::with_client(client); - /// ``` - pub fn with_client(client: Client) -> Configuration { - Configuration { - base_path: "{{{basePath}}}".to_owned(), - user_agent: {{#httpUserAgent}}Some("{{{.}}}".to_owned()){{/httpUserAgent}}{{^httpUserAgent}}Some("OpenAPI-Generator/{{{version}}}/rust".to_owned()){{/httpUserAgent}}, - client, - basic_auth: None, - oauth_access_token: None, - api_key: None, - } - } -} - -impl Default for Configuration { - fn default() -> Self { - let client = Client::builder(TokioExecutor::new()).build_http(); - Configuration::with_client(client) - } -} diff --git a/custom-templates/hyper0x/api.mustache b/custom-templates/hyper0x/api.mustache deleted file mode 100644 index fe1a65c..0000000 --- a/custom-templates/hyper0x/api.mustache +++ /dev/null @@ -1,181 +0,0 @@ -{{>partial_header}} -use std::rc::Rc; -use std::borrow::Borrow; -use std::pin::Pin; -#[allow(unused_imports)] -use std::option::Option; - -use hyper; -use futures::Future; - -use crate::models; -use super::{Error, configuration}; -use super::request as __internal_request; - -pub struct {{{classname}}}Client - where C: Clone + std::marker::Send + Sync + 'static { - configuration: Rc>, -} - -impl {{{classname}}}Client - where C: Clone + std::marker::Send + Sync { - pub fn new(configuration: Rc>) -> {{{classname}}}Client { - {{{classname}}}Client { - configuration, - } - } -} - -pub trait {{{classname}}} { -{{#operations}} -{{#operation}} - fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isString}}{{^isUuid}}&str{{/isUuid}}{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> Pin>>>; -{{/operation}} -{{/operations}} -} - -impl{{{classname}}} for {{{classname}}}Client - where C: Clone + std::marker::Send + Sync { - {{#operations}} - {{#operation}} - #[allow(unused_mut)] - fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isString}}{{^isUuid}}&str{{/isUuid}}{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> Pin>>> { - let mut req = __internal_request::Request::new(hyper::Method::{{{httpMethod.toUpperCase}}}, "{{{path}}}".to_string()) - {{#hasAuthMethods}} - {{#authMethods}} - {{#isApiKey}} - .with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{ - in_header: {{#isKeyInHeader}}true{{/isKeyInHeader}}{{^isKeyInHeader}}false{{/isKeyInHeader}}, - in_query: {{#isKeyInQuery}}true{{/isKeyInQuery}}{{^isKeyInQuery}}false{{/isKeyInQuery}}, - param_name: "{{{keyParamName}}}".to_owned(), - })) - {{/isApiKey}} - {{#isBasicBasic}} - .with_auth(__internal_request::Auth::Basic) - {{/isBasicBasic}} - {{#isOAuth}} - .with_auth(__internal_request::Auth::Oauth) - {{/isOAuth}} - {{/authMethods}} - {{/hasAuthMethods}} - ; - {{#queryParams}} - {{#required}} - {{^isNullable}} - req = req.with_query_param("{{{baseName}}}".to_string(), {{{paramName}}}{{#isArray}}.join(","){{/isArray}}.to_string()); - {{/isNullable}} - {{#isNullable}} - match {{{paramName}}} { - Some(param_value) => { req = req.with_query_param("{{{baseName}}}".to_string(), param_value{{#isArray}}.join(","){{/isArray}}.to_string()); }, - None => { req = req.with_query_param("{{{baseName}}}".to_string(), "".to_string()); }, - } - {{/isNullable}} - {{/required}} - {{^required}} - if let Some(ref s) = {{{paramName}}} { - {{#isArray}} - let query_value = s.iter().map(|s| s.to_string()).collect::>().join(","); - {{/isArray}} - {{^isArray}} - let query_value = match serde_json::to_string(s) { - Ok(value) => value, - Err(e) => return Box::pin(futures::future::err(Error::Serde(e))), - }; - {{/isArray}} - req = req.with_query_param("{{{baseName}}}".to_string(), query_value); - } - {{/required}} - {{/queryParams}} - {{#pathParams}} - {{#required}} - {{^isNullable}} - req = req.with_path_param("{{{baseName}}}".to_string(), {{{paramName}}}{{#isArray}}.join(","){{/isArray}}.to_string()); - {{/isNullable}} - {{#isNullable}} - match {{{paramName}}} { - Some(param_value) => { req = req.with_path_param("{{{baseName}}}".to_string(), param_value{{#isArray}}.join(","){{/isArray}}.to_string()); }, - None => { req = req.with_path_param("{{{baseName}}}".to_string(), "".to_string()); }, - } - {{/isNullable}} - {{/required}} - {{^required}} - if let Some(param_value) = {{{paramName}}} { - req = req.with_path_param("{{{baseName}}}".to_string(), param_value{{#isArray}}.join(","){{/isArray}}.to_string()); - } - {{/required}} - {{/pathParams}} - {{#hasHeaderParams}} - {{#headerParams}} - {{#required}} - {{^isNullable}} - req = req.with_header_param("{{{baseName}}}".to_string(), {{{paramName}}}{{#isArray}}.join(","){{/isArray}}.to_string()); - {{/isNullable}} - {{#isNullable}} - match {{{paramName}}} { - Some(param_value) => { req = req.with_header_param("{{{baseName}}}".to_string(), param_value{{#isArray}}.join(","){{/isArray}}.to_string()); }, - None => { req = req.with_header_param("{{{baseName}}}".to_string(), "".to_string()); }, - } - {{/isNullable}} - {{/required}} - {{^required}} - if let Some(param_value) = {{{paramName}}} { - req = req.with_header_param("{{{baseName}}}".to_string(), param_value{{#isArray}}.join(","){{/isArray}}.to_string()); - } - {{/required}} - {{/headerParams}} - {{/hasHeaderParams}} - {{#hasFormParams}} - {{#formParams}} - {{#isFile}} - {{#required}} - {{^isNullable}} - req = req.with_form_param("{{{baseName}}}".to_string(), unimplemented!()); - {{/isNullable}} - {{#isNullable}} - match {{{paramName}}} { - Some(param_value) => { req = req.with_form_param("{{{baseName}}}".to_string(), unimplemented!()); }, - None => { req = req.with_form_param("{{{baseName}}}".to_string(), unimplemented!()); }, - } - {{/isNullable}} - {{/required}} - {{^required}} - if let Some(param_value) = {{{paramName}}} { - req = req.with_form_param("{{{baseName}}}".to_string(), unimplemented!()); - } - {{/required}} - {{/isFile}} - {{^isFile}} - {{#required}} - {{^isNullable}} - req = req.with_form_param("{{{baseName}}}".to_string(), {{{paramName}}}{{#isArray}}.join(","){{/isArray}}.to_string()); - {{/isNullable}} - {{#isNullable}} - match {{{paramName}}} { - Some(param_value) => { req = req.with_form_param("{{{baseName}}}".to_string(), param_value{{#isArray}}.join(","){{/isArray}}.to_string()); }, - None => { req = req.with_form_param("{{{baseName}}}".to_string(), "".to_string()); }, - } - {{/isNullable}} - {{/required}} - {{^required}} - if let Some(param_value) = {{{paramName}}} { - req = req.with_form_param("{{{baseName}}}".to_string(), param_value{{#isArray}}.join(","){{/isArray}}.to_string()); - } - {{/required}} - {{/isFile}} - {{/formParams}} - {{/hasFormParams}} - {{#hasBodyParam}} - {{#bodyParams}} - req = req.with_body_param({{{paramName}}}); - {{/bodyParams}} - {{/hasBodyParam}} - {{^returnType}} - req = req.returns_nothing(); - {{/returnType}} - - req.execute(self.configuration.borrow()) - } - -{{/operation}} -{{/operations}} -} diff --git a/custom-templates/hyper0x/api_mod.mustache b/custom-templates/hyper0x/api_mod.mustache deleted file mode 100644 index 51a42ef..0000000 --- a/custom-templates/hyper0x/api_mod.mustache +++ /dev/null @@ -1,64 +0,0 @@ -use http; -use hyper; -use serde_json; - -#[derive(Debug)] -pub enum Error { - Api(ApiError), - Header(hyper::http::header::InvalidHeaderValue), - Http(http::Error), - Hyper(hyper::Error), - Serde(serde_json::Error), - UriError(http::uri::InvalidUri), -} - -#[derive(Debug)] -pub struct ApiError { - pub code: hyper::StatusCode, - pub body: hyper::body::Body, -} - -impl From<(hyper::StatusCode, hyper::body::Body)> for Error { - fn from(e: (hyper::StatusCode, hyper::body::Body)) -> Self { - Error::Api(ApiError { - code: e.0, - body: e.1, - }) - } -} - -impl From for Error { - fn from(e: http::Error) -> Self { - Error::Http(e) - } -} - -impl From for Error { - fn from(e: hyper::Error) -> Self { - Error::Hyper(e) - } -} - -impl From for Error { - fn from(e: serde_json::Error) -> Self { - Error::Serde(e) - } -} - -mod request; - -{{#apiInfo}} -{{#apis}} -mod {{{classFilename}}}; -{{#operations}} -{{#operation}} -{{#-last}} -pub use self::{{{classFilename}}}::{ {{{classname}}}, {{{classname}}}Client }; -{{/-last}} -{{/operation}} -{{/operations}} -{{/apis}} -{{/apiInfo}} - -pub mod configuration; -pub mod client; diff --git a/custom-templates/hyper0x/client.mustache b/custom-templates/hyper0x/client.mustache deleted file mode 100644 index 25124d9..0000000 --- a/custom-templates/hyper0x/client.mustache +++ /dev/null @@ -1,54 +0,0 @@ -use std::rc::Rc; - -use hyper; -use super::configuration::Configuration; - -pub struct APIClient { -{{#apiInfo}} -{{#apis}} -{{#operations}} -{{#operation}} - {{#-last}} - {{{classFilename}}}: Box, - {{/-last}} -{{/operation}} -{{/operations}} -{{/apis}} -{{/apiInfo}} -} - -impl APIClient { - pub fn new(configuration: Configuration) -> APIClient - where C: Clone + std::marker::Send + Sync + 'static { - let rc = Rc::new(configuration); - - APIClient { -{{#apiInfo}} -{{#apis}} -{{#operations}} -{{#operation}} - {{#-last}} - {{{classFilename}}}: Box::new(crate::apis::{{{classname}}}Client::new(rc.clone())), - {{/-last}} -{{/operation}} -{{/operations}} -{{/apis}} -{{/apiInfo}} - } - } - -{{#apiInfo}} -{{#apis}} -{{#operations}} -{{#operation}} -{{#-last}} - pub fn {{{classFilename}}}(&self) -> &dyn crate::apis::{{{classname}}}{ - self.{{{classFilename}}}.as_ref() - } - -{{/-last}} -{{/operation}} -{{/operations}} -{{/apis}} -{{/apiInfo}} -} diff --git a/custom-templates/hyper0x/configuration.mustache b/custom-templates/hyper0x/configuration.mustache deleted file mode 100644 index ee6f407..0000000 --- a/custom-templates/hyper0x/configuration.mustache +++ /dev/null @@ -1,34 +0,0 @@ -{{>partial_header}} -use hyper; - -pub struct Configuration - where C: Clone + std::marker::Send + Sync + 'static { - pub base_path: String, - pub user_agent: Option, - pub client: hyper::client::Client, - pub basic_auth: Option, - pub oauth_access_token: Option, - pub api_key: Option, - // TODO: take an oauth2 token source, similar to the go one -} - -pub type BasicAuth = (String, Option); - -pub struct ApiKey { - pub prefix: Option, - pub key: String, -} - -impl Configuration - where C: Clone + std::marker::Send + Sync { - pub fn new(client: hyper::client::Client) -> Configuration { - Configuration { - base_path: "{{{basePath}}}".to_owned(), - user_agent: {{#httpUserAgent}}Some("{{{.}}}".to_owned()){{/httpUserAgent}}{{^httpUserAgent}}Some("OpenAPI-Generator/{{{version}}}/rust".to_owned()){{/httpUserAgent}}, - client, - basic_auth: None, - oauth_access_token: None, - api_key: None, - } - } -} diff --git a/custom-templates/reqwest-trait/api.mustache b/custom-templates/reqwest-trait/api.mustache deleted file mode 100644 index ae7ea7d..0000000 --- a/custom-templates/reqwest-trait/api.mustache +++ /dev/null @@ -1,558 +0,0 @@ -{{>partial_header}} - -use async_trait::async_trait; -{{#mockall}} -#[cfg(feature = "mockall")] -use mockall::automock; -{{/mockall}} -use reqwest; -use std::sync::Arc; -use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration}; -use crate::apis::ContentType; - -{{#mockall}} -#[cfg_attr(feature = "mockall", automock)] -{{/mockall}} -#[async_trait] -pub trait {{{classname}}}: Send + Sync { -{{#operations}} -{{#operation}} - - /// {{{httpMethod}}} {{{path}}} - {{^notes.empty}} - /// - /// {{{notes}}} - {{/notes.empty}} -{{#vendorExtensions.x-group-parameters}} - async fn {{{operationId}}}(&self, {{#allParams}}{{#-first}} params: {{{operationIdCamelCase}}}Params {{/-first}}{{/allParams}}{{! - ### Function return type - }}) -> Result<{{! - ### Multi response support - }}{{#supportMultipleResponses}}ResponseContent<{{{operationIdCamelCase}}}Success>{{/supportMultipleResponses}}{{! - ### Regular return type - }}{{^supportMultipleResponses}}{{^returnType}}(){{/returnType}}{{{returnType}}}{{/supportMultipleResponses}}{{! - ### Error Type - }}, Error<{{{operationIdCamelCase}}}Error>>; -{{/vendorExtensions.x-group-parameters}} -{{^vendorExtensions.x-group-parameters}} - async fn {{{operationId}}}{{! - ### Lifetimes - }}<{{#allParams}}'{{#lambda.lifetimeName}}{{{paramName}}}{{/lambda.lifetimeName}}{{^-last}}, {{/-last}}{{/allParams}}>{{! - ### Function parameter names - }}(&self, {{#allParams}}{{{paramName}}}: {{! - ### Option Start - }}{{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{! - ### &str and Vec<&str> - }}{{#isString}}{{#isArray}}Vec<{{/isArray}}{{^isUuid}}&'{{#lambda.lifetimeName}}{{{paramName}}}{{/lambda.lifetimeName}} str{{/isUuid}}{{#isArray}}>{{/isArray}}{{/isString}}{{! - ### UUIDs - }}{{#isUuid}}{{#isArray}}Vec<{{/isArray}}&str{{#isArray}}>{{/isArray}}{{/isUuid}}{{! - ### Models and primative types - }}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{! - ### Option End - }}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{! - ### Comma for next arguement - }}{{^-last}}, {{/-last}}{{/allParams}}{{! - ### Function return type - }}) -> Result<{{! - ### Multi response support - }}{{#supportMultipleResponses}}ResponseContent<{{{operationIdCamelCase}}}Success>{{/supportMultipleResponses}}{{! - ### Regular return type - }}{{^supportMultipleResponses}}{{^returnType}}(){{/returnType}}{{{returnType}}}{{/supportMultipleResponses}}{{! - ### Error Type - }}, Error<{{{operationIdCamelCase}}}Error>>; -{{/vendorExtensions.x-group-parameters}} -{{/operation}} -{{/operations}} -} - -pub struct {{{classname}}}Client { - configuration: Arc -} - -impl {{classname}}Client { - pub fn new(configuration: Arc) -> Self { - Self { configuration } - } -} - - -{{#operations}} -{{#operation}} -{{#vendorExtensions.x-group-parameters}} -{{#allParams}} -{{#-first}} -/// struct for passing parameters to the method [`{{operationId}}`] -#[derive(Clone, Debug)] -{{#useBonBuilder}} -#[cfg_attr(feature = "bon", derive(::bon::Builder))] -{{/useBonBuilder}} -pub struct {{{operationIdCamelCase}}}Params { -{{/-first}} - {{#description}} - /// {{{.}}} - {{/description}} - pub {{{paramName}}}: {{! - ### Option Start - }}{{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{! - ### &str and Vec<&str> - }}{{^isUuid}}{{#isString}}{{#isArray}}Vec<{{/isArray}}String{{#isArray}}>{{/isArray}}{{/isString}}{{/isUuid}}{{! - ### UUIDs - }}{{#isUuid}}{{#isArray}}Vec<{{/isArray}}String{{#isArray}}>{{/isArray}}{{/isUuid}}{{! - ### Models and primative types - }}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{! - ### Option End - }}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{! - ### Comma for next field - }}{{^-last}},{{/-last}} -{{#-last}} -} - -{{/-last}} -{{/allParams}} -{{/vendorExtensions.x-group-parameters}} -{{/operation}} -{{/operations}} - -#[async_trait] -impl {{classname}} for {{classname}}Client { - {{#operations}} - {{#operation}} - {{#description}} - /// {{{.}}} - {{/description}} - {{#notes}} - /// {{{.}}} - {{/notes}} - {{#vendorExtensions.x-group-parameters}} - async fn {{{operationId}}}(&self, {{#allParams}}{{#-first}} params: {{{operationIdCamelCase}}}Params {{/-first}}{{/allParams}}{{! - ### Function return type - }}) -> Result<{{! - ### Multi response support - }}{{#supportMultipleResponses}}ResponseContent<{{{operationIdCamelCase}}}Success>{{/supportMultipleResponses}}{{! - ### Regular return type - }}{{^supportMultipleResponses}}{{^returnType}}(){{/returnType}}{{{returnType}}}{{/supportMultipleResponses}}{{! - ### Error Type - }}, Error<{{{operationIdCamelCase}}}Error>> { - {{#allParams}}{{#-first}} - let {{{operationIdCamelCase}}}Params { - {{#allParams}} - {{{paramName}}}, - {{/allParams}} - } = params; - {{/-first}}{{/allParams}} - - {{/vendorExtensions.x-group-parameters}} - {{^vendorExtensions.x-group-parameters}} - async fn {{{operationId}}}{{! - ### Lifetimes - }}<{{#allParams}}'{{#lambda.lifetimeName}}{{{paramName}}}{{/lambda.lifetimeName}}{{^-last}}, {{/-last}}{{/allParams}}>{{! - ### Function parameter names - }}(&self, {{#allParams}}{{{paramName}}}: {{! - ### Option Start - }}{{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{! - ### &str and Vec<&str> - }}{{#isString}}{{#isArray}}Vec<{{/isArray}}{{^isUuid}}&'{{#lambda.lifetimeName}}{{{paramName}}}{{/lambda.lifetimeName}} str{{/isUuid}}{{#isArray}}>{{/isArray}}{{/isString}}{{! - ### UUIDs - }}{{#isUuid}}{{#isArray}}Vec<{{/isArray}}&str{{#isArray}}>{{/isArray}}{{/isUuid}}{{! - ### Models and primative types - }}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{! - ### Option End - }}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{! - ### Comma for next arguement - }}{{^-last}}, {{/-last}}{{/allParams}}{{! - ### Function return type - }}) -> Result<{{! - ### Multi response support - }}{{#supportMultipleResponses}}ResponseContent<{{{operationIdCamelCase}}}Success>{{/supportMultipleResponses}}{{! - ### Regular return type - }}{{^supportMultipleResponses}}{{^returnType}}(){{/returnType}}{{{returnType}}}{{/supportMultipleResponses}}{{! - ### Regular return type - }}, Error<{{{operationIdCamelCase}}}Error>> { - {{/vendorExtensions.x-group-parameters}} - let local_var_configuration = &self.configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!("{}{{{path}}}", local_var_configuration.base_path{{#pathParams}}, {{{baseName}}}={{#isString}}crate::apis::urlencode({{/isString}}{{{paramName}}}{{^required}}.unwrap(){{/required}}{{#required}}{{#isNullable}}.unwrap(){{/isNullable}}{{/required}}{{#isArray}}.join(",").as_ref(){{/isArray}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}.to_string(){{/isContainer}}{{/isPrimitiveType}}{{/isUuid}}{{/isString}}{{#isString}}){{/isString}}{{/pathParams}}); - let mut local_var_req_builder = local_var_client.request(reqwest::Method::{{{httpMethod}}}, local_var_uri_str.as_str()); - - {{#queryParams}} - {{#required}} - {{#isArray}} - local_var_req_builder = match "{{collectionFormat}}" { - "multi" => local_var_req_builder.query(&{{{paramName}}}.into_iter().map(|p| ("{{{baseName}}}".to_owned(), p.to_string())).collect::>()), - _ => local_var_req_builder.query(&[("{{{baseName}}}", &{{{paramName}}}.into_iter().map(|p| p.to_string()).collect::>().join(",").to_string())]), - }; - {{/isArray}} - {{^isArray}} - {{^isNullable}} - local_var_req_builder = local_var_req_builder.query(&[("{{{baseName}}}", &{{{paramName}}}.to_string())]); - {{/isNullable}} - {{#isNullable}} - {{#isDeepObject}} - {{^isExplode}} - if let Some(ref param_value) = {{{paramName}}} { - let params = crate::apis::parse_deep_object("{{{baseName}}}", &serde_json::to_value(param_value)?); - local_var_req_builder = local_var_req_builder.query(¶ms); - } - {{/isExplode}} - {{#isExplode}} - {{#isModel}} - if let Some(ref param_value) = {{{paramName}}} { - local_var_req_builder = local_var_req_builder.query(¶m_value); - } - {{/isModel}} - {{#isMap}} - if let Some(ref param_value) = {{{paramName}}} { - let mut query_params = Vec::with_capacity(param_value.len()); - for (key, value) in param_value.iter() { - query_params.push((key.to_string(), serde_json::to_string(value)?)); - } - local_var_req_builder = local_var_req_builder.query(&query_params); - } - {{/isMap}} - {{/isExplode}} - {{/isDeepObject}} - {{^isDeepObject}} - {{#isObject}} - if let Some(ref param_value) = {{{paramName}}} { - local_var_req_builder = local_var_req_builder.query(&[("{{{baseName}}}", &serde_json::to_value(param_value)?)]); - }; - {{/isObject}} - {{#isModel}} - if let Some(ref param_value) = {{{paramName}}} { - local_var_req_builder = local_var_req_builder.query(&[("{{{baseName}}}", &serde_json::to_value(param_value)?)]); - }; - {{/isModel}} - {{^isObject}} - {{^isModel}} - if let Some(ref param_value) = {{{paramName}}} { - local_var_req_builder = local_var_req_builder.query(&[("{{{baseName}}}", ¶m_value.to_string())]); - }; - {{/isModel}} - {{/isObject}} - {{/isDeepObject}} - {{/isNullable}} - {{/isArray}} - {{/required}} - {{^required}} - if let Some(ref param_value) = {{{paramName}}} { - {{#isArray}} - local_var_req_builder = match "{{collectionFormat}}" { - "multi" => local_var_req_builder.query(¶m_value.into_iter().map(|p| ("{{{baseName}}}".to_owned(), p.to_string())).collect::>()), - _ => local_var_req_builder.query(&[("{{{baseName}}}", ¶m_value.into_iter().map(|p| p.to_string()).collect::>().join(",").to_string())]), - }; - {{/isArray}} - {{#isDeepObject}} - {{^isExplode}} - let params = crate::apis::parse_deep_object("{{{baseName}}}", &serde_json::to_value(param_value)?); - local_var_req_builder = local_var_req_builder.query(¶ms); - {{/isExplode}} - {{#isExplode}} - {{#isModel}} - local_var_req_builder = local_var_req_builder.query(¶m_value); - {{/isModel}} - {{#isMap}} - let mut query_params = Vec::with_capacity(param_value.len()); - for (key, value) in param_value.iter() { - query_params.push((key.to_string(), serde_json::to_string(value)?)); - } - local_var_req_builder = local_var_req_builder.query(&query_params); - {{/isMap}} - {{/isExplode}} - {{/isDeepObject}} - {{^isDeepObject}} - {{#isObject}} - local_var_req_builder = local_var_req_builder.query(&[("{{{baseName}}}", &serde_json::to_value(param_value)?)]); - {{/isObject}} - {{#isModel}} - local_var_req_builder = local_var_req_builder.query(&[("{{{baseName}}}", &serde_json::to_value(param_value)?)]); - {{/isModel}} - {{^isObject}} - {{^isModel}} - local_var_req_builder = local_var_req_builder.query(&[("{{{baseName}}}", ¶m_value.to_string())]); - {{/isModel}} - {{/isObject}} - {{/isDeepObject}} - } - {{/required}} - {{/queryParams}} - {{#hasAuthMethods}} - {{#authMethods}} - {{#isApiKey}} - {{#isKeyInQuery}} - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = local_var_apikey.key.clone(); - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key, - }; - local_var_req_builder = local_var_req_builder.query(&[("{{{keyParamName}}}", local_var_value)]); - } - {{/isKeyInQuery}} - {{/isApiKey}} - {{/authMethods}} - {{/hasAuthMethods}} - {{#hasAuthMethods}} - {{#withAWSV4Signature}} - if let Some(ref local_var_aws_v4_key) = local_var_configuration.aws_v4_key { - let local_var_new_headers = match local_var_aws_v4_key.sign( - &local_var_uri_str, - "{{{httpMethod}}}", - {{#hasBodyParam}} - {{#bodyParams}} - &serde_json::to_string(&{{{paramName}}}).expect("param should serialize to string"), - {{/bodyParams}} - {{/hasBodyParam}} - {{^hasBodyParam}} - "", - {{/hasBodyParam}} - ) { - Ok(new_headers) => new_headers, - Err(err) => return Err(Error::AWSV4SignatureError(err)), - }; - for (local_var_name, local_var_value) in local_var_new_headers.iter() { - local_var_req_builder = local_var_req_builder.header(local_var_name.as_str(), local_var_value.as_str()); - } - } - {{/withAWSV4Signature}} - {{/hasAuthMethods}} - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); - } - {{#hasHeaderParams}} - {{#headerParams}} - {{#required}} - {{^isNullable}} - local_var_req_builder = local_var_req_builder.header("{{{baseName}}}", {{{paramName}}}{{#isArray}}.join(","){{/isArray}}.to_string()); - {{/isNullable}} - {{#isNullable}} - match {{{paramName}}} { - Some(local_var_param_value) => { local_var_req_builder = local_var_req_builder.header("{{{baseName}}}", local_var_param_value{{#isArray}}.join(","){{/isArray}}.to_string()); }, - None => { local_var_req_builder = local_var_req_builder.header("{{{baseName}}}", ""); }, - } - {{/isNullable}} - {{/required}} - {{^required}} - if let Some(local_var_param_value) = {{{paramName}}} { - local_var_req_builder = local_var_req_builder.header("{{{baseName}}}", local_var_param_value{{#isArray}}.join(","){{/isArray}}.to_string()); - } - {{/required}} - {{/headerParams}} - {{/hasHeaderParams}} - {{#hasAuthMethods}} - {{#authMethods}} - {{#supportTokenSource}} - // Obtain a token from source provider. - // Tokens can be Id or access tokens depending on the provider type and configuration. - let token = local_var_configuration.token_source.token().await.map_err(Error::TokenSource)?; - // The token format is the responsibility of the provider, thus we just set the authorization header with whatever is given. - local_var_req_builder = local_var_req_builder.header(reqwest::header::AUTHORIZATION, token); - {{/supportTokenSource}} - {{^supportTokenSource}} - {{#isApiKey}} - {{#isKeyInHeader}} - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = local_var_apikey.key.clone(); - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key, - }; - local_var_req_builder = local_var_req_builder.header("{{{keyParamName}}}", local_var_value); - }; - {{/isKeyInHeader}} - {{/isApiKey}} - {{#isBasic}} - {{#isBasicBasic}} - if let Some(ref local_var_auth_conf) = local_var_configuration.basic_auth { - local_var_req_builder = local_var_req_builder.basic_auth(local_var_auth_conf.0.to_owned(), local_var_auth_conf.1.to_owned()); - }; - {{/isBasicBasic}} - {{#isBasicBearer}} - if let Some(ref local_var_token) = local_var_configuration.bearer_access_token { - local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned()); - }; - {{/isBasicBearer}} - {{/isBasic}} - {{#isOAuth}} - if let Some(ref local_var_token) = local_var_configuration.oauth_access_token { - local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned()); - }; - {{/isOAuth}} - {{/supportTokenSource}} - {{/authMethods}} - {{/hasAuthMethods}} - {{#isMultipart}} - {{#hasFormParams}} - let mut local_var_form = reqwest::multipart::Form::new(); - {{#formParams}} - {{#isFile}} - // TODO: support file upload for '{{{baseName}}}' parameter - {{/isFile}} - {{^isFile}} - {{#required}} - {{^isNullable}} - local_var_form = local_var_form.text("{{{baseName}}}", {{{paramName}}}{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); - {{/isNullable}} - {{#isNullable}} - match {{{paramName}}} { - Some(local_var_param_value) => { local_var_form = local_var_form.text("{{{baseName}}}", local_var_param_value{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); }, - None => { local_var_form = local_var_form.text("{{{baseName}}}", ""); }, - } - {{/isNullable}} - {{/required}} - {{^required}} - if let Some(local_var_param_value) = {{{paramName}}} { - local_var_form = local_var_form.text("{{{baseName}}}", local_var_param_value{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); - } - {{/required}} - {{/isFile}} - {{/formParams}} - local_var_req_builder = local_var_req_builder.multipart(local_var_form); - {{/hasFormParams}} - {{/isMultipart}} - {{^isMultipart}} - {{#hasFormParams}} - let mut local_var_form_params = std::collections::HashMap::new(); - {{#formParams}} - {{#isFile}} - {{#required}} - {{^isNullable}} - local_var_form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); - {{/isNullable}} - {{#isNullable}} - match {{{paramName}}} { - Some(local_var_param_value) => { local_var_form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); }, - None => { unimplemented!("Required nullable file form param not supported with x-www-form-urlencoded content"); }, - } - {{/isNullable}} - {{/required}} - {{^required}} - if let Some(local_var_param_value) = {{{paramName}}} { - local_var_form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); - } - {{/required}} - {{/isFile}} - {{^isFile}} - {{#required}} - {{^isNullable}} - local_var_form_params.insert("{{{baseName}}}", {{{paramName}}}{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); - {{/isNullable}} - {{#isNullable}} - match {{{paramName}}} { - Some(local_var_param_value) => { local_var_form_params.insert("{{{baseName}}}", local_var_param_value{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); }, - None => { local_var_form_params.insert("{{{baseName}}}", ""); }, - } - {{/isNullable}} - {{/required}} - {{^required}} - if let Some(local_var_param_value) = {{{paramName}}} { - local_var_form_params.insert("{{{baseName}}}", local_var_param_value{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); - } - {{/required}} - {{/isFile}} - {{/formParams}} - local_var_req_builder = local_var_req_builder.form(&local_var_form_params); - {{/hasFormParams}} - {{/isMultipart}} - {{#hasBodyParam}} - {{#bodyParams}} - local_var_req_builder = local_var_req_builder.json(&{{{paramName}}}); - {{/bodyParams}} - {{/hasBodyParam}} - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - {{^supportMultipleResponses}} - {{#returnType}} - let local_var_content_type = local_var_resp - .headers() - .get("content-type") - .and_then(|v| v.to_str().ok()) - .unwrap_or("application/octet-stream"); - let local_var_content_type = super::ContentType::from(local_var_content_type); - {{/returnType}} - {{/supportMultipleResponses}} - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - {{^supportMultipleResponses}} - {{^returnType}} - Ok(()) - {{/returnType}} - {{#returnType}} - match local_var_content_type { - ContentType::Json => serde_json::from_str(&local_var_content).map_err(Error::from), - {{#vendorExtensions.x-supports-plain-text}} - ContentType::Text => return Ok(local_var_content), - {{/vendorExtensions.x-supports-plain-text}} - {{^vendorExtensions.x-supports-plain-text}} - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `{{returnType}}`"))), - {{/vendorExtensions.x-supports-plain-text}} - ContentType::Unsupported(local_var_unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{local_var_unknown_type}` content type response that cannot be converted to `{{returnType}}`")))), - } - {{/returnType}} - {{/supportMultipleResponses}} - {{#supportMultipleResponses}} - let local_var_entity: Option<{{{operationIdCamelCase}}}Success> = serde_json::from_str(&local_var_content).ok(); - let local_var_result = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; - Ok(local_var_result) - {{/supportMultipleResponses}} - } else { - let local_var_entity: Option<{{{operationIdCamelCase}}}Error> = serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; - Err(Error::ResponseError(local_var_error)) - } - } - - {{/operation}} - {{/operations}} -} - -{{#supportMultipleResponses}} -{{#operations}} -{{#operation}} -/// struct for typed successes of method [`{{operationId}}`] -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub enum {{{operationIdCamelCase}}}Success { - {{#responses}} - {{#is2xx}} - Status{{code}}({{#isEnum}}{{{enumName}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}), - {{/is2xx}} - {{#is3xx}} - Status{{code}}({{#isEnum}}{{{enumName}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}), - {{/is3xx}} - {{/responses}} - UnknownValue(serde_json::Value), -} - -{{/operation}} -{{/operations}} -{{/supportMultipleResponses}} -{{#operations}} -{{#operation}} -/// struct for typed errors of method [`{{operationId}}`] -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub enum {{{operationIdCamelCase}}}Error { - {{#responses}} - {{#is4xx}} - Status{{code}}({{#isEnum}}{{{enumName}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}), - {{/is4xx}} - {{#is5xx}} - Status{{code}}({{#isEnum}}{{{enumName}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}), - {{/is5xx}} - {{#isDefault}} - DefaultResponse({{#isEnum}}{{{enumName}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}), - {{/isDefault}} - {{/responses}} - UnknownValue(serde_json::Value), -} - -{{/operation}} -{{/operations}} diff --git a/custom-templates/reqwest-trait/api_mod.mustache b/custom-templates/reqwest-trait/api_mod.mustache deleted file mode 100644 index 41a4ba0..0000000 --- a/custom-templates/reqwest-trait/api_mod.mustache +++ /dev/null @@ -1,236 +0,0 @@ -use std::error; -use std::fmt; -{{#withAWSV4Signature}} -use aws_sigv4; -{{/withAWSV4Signature}} - -#[derive(Debug, Clone)] -pub struct ResponseContent { - pub status: reqwest::StatusCode, - pub content: String, - pub entity: Option, -} - -#[derive(Debug)] -pub enum Error { - Reqwest(reqwest::Error), - {{#supportMiddleware}} - ReqwestMiddleware(reqwest_middleware::Error), - {{/supportMiddleware}} - Serde(serde_json::Error), - Io(std::io::Error), - ResponseError(ResponseContent), - {{#withAWSV4Signature}} - AWSV4SignatureError(aws_sigv4::http_request::Error), - {{/withAWSV4Signature}} - {{#supportTokenSource}} - TokenSource(Box), - {{/supportTokenSource}} -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let (module, e) = match self { - Error::Reqwest(e) => ("reqwest", e.to_string()), - {{#supportMiddleware}} - Error::ReqwestMiddleware(e) => ("reqwest-middleware", e.to_string()), - {{/supportMiddleware}} - Error::Serde(e) => ("serde", e.to_string()), - Error::Io(e) => ("IO", e.to_string()), - Error::ResponseError(e) => ("response", format!("status code {}", e.status)), - {{#withAWSV4Signature}} - Error::AWSV4SignatureError(e) => ("aws v4 signature", e.to_string()), - {{/withAWSV4Signature}} - {{#supportTokenSource}} - Error::TokenSource(e) => ("token source failure", e.to_string()), - {{/supportTokenSource}} - }; - write!(f, "error in {}: {}", module, e) - } -} - -impl error::Error for Error { - fn source(&self) -> Option<&(dyn error::Error + 'static)> { - Some(match self { - Error::Reqwest(e) => e, - {{#supportMiddleware}} - Error::ReqwestMiddleware(e) => e, - {{/supportMiddleware}} - Error::Serde(e) => e, - Error::Io(e) => e, - Error::ResponseError(_) => return None, - {{#withAWSV4Signature}} - Error::AWSV4SignatureError(_) => return None, - {{/withAWSV4Signature}} - {{#supportTokenSource}} - Error::TokenSource(e) => &**e, - {{/supportTokenSource}} - }) - } -} - -impl From for Error { - fn from(e: reqwest::Error) -> Self { - Error::Reqwest(e) - } -} - -{{#supportMiddleware}} -impl From for Error { - fn from(e: reqwest_middleware::Error) -> Self { - Error::ReqwestMiddleware(e) - } -} - -{{/supportMiddleware}} -impl From for Error { - fn from(e: serde_json::Error) -> Self { - Error::Serde(e) - } -} - -impl From for Error { - fn from(e: std::io::Error) -> Self { - Error::Io(e) - } -} - -pub fn urlencode>(s: T) -> String { - ::url::form_urlencoded::byte_serialize(s.as_ref().as_bytes()).collect() -} - -pub fn parse_deep_object(prefix: &str, value: &serde_json::Value) -> Vec<(String, String)> { - if let serde_json::Value::Object(object) = value { - let mut params = vec![]; - - for (key, value) in object { - match value { - serde_json::Value::Object(_) => params.append(&mut parse_deep_object( - &format!("{}[{}]", prefix, key), - value, - )), - serde_json::Value::Array(array) => { - for (i, value) in array.iter().enumerate() { - params.append(&mut parse_deep_object( - &format!("{}[{}][{}]", prefix, key, i), - value, - )); - } - }, - serde_json::Value::String(s) => params.push((format!("{}[{}]", prefix, key), s.clone())), - _ => params.push((format!("{}[{}]", prefix, key), value.to_string())), - } - } - - return params; - } - - unimplemented!("Only objects are supported with style=deepObject") -} - -/// Internal use only -/// A content type supported by this client. -#[allow(dead_code)] -enum ContentType { - Json, - Text, - Unsupported(String) -} - -impl From<&str> for ContentType { - fn from(content_type: &str) -> Self { - if content_type.starts_with("application") && content_type.contains("json") { - return Self::Json; - } else if content_type.starts_with("text/plain") { - return Self::Text; - } else { - return Self::Unsupported(content_type.to_string()); - } - } -} - -{{#apiInfo}} -{{#apis}} -pub mod {{{classFilename}}}; -{{/apis}} -{{/apiInfo}} - -pub mod configuration; - -{{#topLevelApiClient}} -use std::sync::Arc; - -pub trait Api { - {{#apiInfo}} - {{#apis}} - fn {{{classFilename}}}(&self) -> &dyn {{{classFilename}}}::{{classname}}; - {{/apis}} - {{/apiInfo}} -} - -pub struct ApiClient { - {{#apiInfo}} - {{#apis}} - {{{classFilename}}}: Box, - {{/apis}} - {{/apiInfo}} -} - -impl ApiClient { - pub fn new(configuration: Arc) -> Self { - Self { - {{#apiInfo}} - {{#apis}} - {{{classFilename}}}: Box::new({{{classFilename}}}::{{classname}}Client::new(configuration.clone())), - {{/apis}} - {{/apiInfo}} - } - } -} - -impl Api for ApiClient { - {{#apiInfo}} - {{#apis}} - fn {{{classFilename}}}(&self) -> &dyn {{{classFilename}}}::{{classname}} { - self.{{{classFilename}}}.as_ref() - } - {{/apis}} - {{/apiInfo}} -} - -{{#mockall}} -#[cfg(feature = "mockall")] -pub struct MockApiClient { - {{#apiInfo}} - {{#apis}} - pub {{{classFilename}}}_mock: {{{classFilename}}}::Mock{{classname}}, - {{/apis}} - {{/apiInfo}} -} - -#[cfg(feature = "mockall")] -impl MockApiClient { - pub fn new() -> Self { - Self { - {{#apiInfo}} - {{#apis}} - {{{classFilename}}}_mock: {{{classFilename}}}::Mock{{classname}}::new(), - {{/apis}} - {{/apiInfo}} - } - } -} - -#[cfg(feature = "mockall")] -impl Api for MockApiClient { - {{#apiInfo}} - {{#apis}} - fn {{{classFilename}}}(&self) -> &dyn {{{classFilename}}}::{{classname}} { - &self.{{{classFilename}}}_mock - } - {{/apis}} - {{/apiInfo}} -} -{{/mockall}} - -{{/topLevelApiClient}} diff --git a/custom-templates/reqwest-trait/configuration.mustache b/custom-templates/reqwest-trait/configuration.mustache deleted file mode 100644 index 2536069..0000000 --- a/custom-templates/reqwest-trait/configuration.mustache +++ /dev/null @@ -1,120 +0,0 @@ -{{>partial_header}} - -{{#withAWSV4Signature}} -use std::time::SystemTime; -use aws_sigv4::http_request::{sign, SigningSettings, SigningParams, SignableRequest}; -use http; -use secrecy::{SecretString, ExposeSecret}; -{{/withAWSV4Signature}} -{{#supportTokenSource}} -use std::sync::Arc; -use google_cloud_token::TokenSource; -use async_trait::async_trait; -{{/supportTokenSource}} - -#[derive(Debug, Clone)] -pub struct Configuration { - pub base_path: String, - pub user_agent: Option, - pub client: {{#supportMiddleware}}reqwest_middleware::ClientWithMiddleware{{/supportMiddleware}}{{^supportMiddleware}}reqwest::Client{{/supportMiddleware}}, - {{^supportTokenSource}} - pub basic_auth: Option, - pub oauth_access_token: Option, - pub bearer_access_token: Option, - pub api_key: Option, - {{/supportTokenSource}} - {{#withAWSV4Signature}} - pub aws_v4_key: Option, - {{/withAWSV4Signature}} - {{#supportTokenSource}} - pub token_source: Arc, - {{/supportTokenSource}} -} -{{^supportTokenSource}} - -pub type BasicAuth = (String, Option); - -#[derive(Debug, Clone)] -pub struct ApiKey { - pub prefix: Option, - pub key: String, -} -{{/supportTokenSource}} - -{{#withAWSV4Signature}} -#[derive(Debug, Clone)] -pub struct AWSv4Key { - pub access_key: String, - pub secret_key: SecretString, - pub region: String, - pub service: String, -} - -impl AWSv4Key { - pub fn sign(&self, uri: &str, method: &str, body: &str) -> Result, aws_sigv4::http_request::Error> { - let request = http::Request::builder() - .uri(uri) - .method(method) - .body(body).unwrap(); - let signing_settings = SigningSettings::default(); - let signing_params = SigningParams::builder() - .access_key(self.access_key.as_str()) - .secret_key(self.secret_key.expose_secret().as_str()) - .region(self.region.as_str()) - .service_name(self.service.as_str()) - .time(SystemTime::now()) - .settings(signing_settings) - .build() - .unwrap(); - let signable_request = SignableRequest::from(&request); - let (mut signing_instructions, _signature) = sign(signable_request, &signing_params)?.into_parts(); - let mut additional_headers = Vec::<(String, String)>::new(); - if let Some(new_headers) = signing_instructions.take_headers() { - for (name, value) in new_headers.into_iter() { - additional_headers.push((name.expect("header should have name").to_string(), - value.to_str().expect("header value should be a string").to_string())); - } - } - Ok(additional_headers) - } -} -{{/withAWSV4Signature}} - -impl Configuration { - pub fn new() -> Configuration { - Configuration::default() - } -} - -impl Default for Configuration { - fn default() -> Self { - Configuration { - base_path: "{{{basePath}}}".to_owned(), - user_agent: {{#httpUserAgent}}Some("{{{.}}}".to_owned()){{/httpUserAgent}}{{^httpUserAgent}}Some("OpenAPI-Generator/{{{version}}}/rust".to_owned()){{/httpUserAgent}}, - client: {{#supportMiddleware}}reqwest_middleware::ClientBuilder::new(reqwest::Client::new()).build(){{/supportMiddleware}}{{^supportMiddleware}}reqwest::Client::new(){{/supportMiddleware}}, - {{^supportTokenSource}} - basic_auth: None, - oauth_access_token: None, - bearer_access_token: None, - api_key: None, - {{/supportTokenSource}} - {{#withAWSV4Signature}} - aws_v4_key: None, - {{/withAWSV4Signature}} - {{#supportTokenSource}} - token_source: Arc::new(NoopTokenSource{}), - {{/supportTokenSource}} - } - } -} -{{#supportTokenSource}} -#[derive(Debug)] -struct NoopTokenSource{} - -#[async_trait] -impl TokenSource for NoopTokenSource { - async fn token(&self) -> Result> { - panic!("This is dummy token source. You can use TokenSourceProvider from 'google_cloud_auth' crate, or any other compatible crate.") - } -} -{{/supportTokenSource}} diff --git a/custom-templates/.travis.yml b/openapi-generator-template/.travis.yml similarity index 100% rename from custom-templates/.travis.yml rename to openapi-generator-template/.travis.yml diff --git a/custom-templates/Cargo.mustache b/openapi-generator-template/Cargo.mustache similarity index 100% rename from custom-templates/Cargo.mustache rename to openapi-generator-template/Cargo.mustache diff --git a/custom-templates/README.mustache b/openapi-generator-template/README.mustache similarity index 100% rename from custom-templates/README.mustache rename to openapi-generator-template/README.mustache diff --git a/custom-templates/api_doc.mustache b/openapi-generator-template/api_doc.mustache similarity index 100% rename from custom-templates/api_doc.mustache rename to openapi-generator-template/api_doc.mustache diff --git a/custom-templates/git_push.sh.mustache b/openapi-generator-template/git_push.sh.mustache similarity index 100% rename from custom-templates/git_push.sh.mustache rename to openapi-generator-template/git_push.sh.mustache diff --git a/custom-templates/gitignore.mustache b/openapi-generator-template/gitignore.mustache similarity index 100% rename from custom-templates/gitignore.mustache rename to openapi-generator-template/gitignore.mustache diff --git a/custom-templates/lib.mustache b/openapi-generator-template/lib.mustache similarity index 100% rename from custom-templates/lib.mustache rename to openapi-generator-template/lib.mustache diff --git a/custom-templates/model.mustache b/openapi-generator-template/model.mustache similarity index 100% rename from custom-templates/model.mustache rename to openapi-generator-template/model.mustache diff --git a/custom-templates/model_doc.mustache b/openapi-generator-template/model_doc.mustache similarity index 100% rename from custom-templates/model_doc.mustache rename to openapi-generator-template/model_doc.mustache diff --git a/custom-templates/model_mod.mustache b/openapi-generator-template/model_mod.mustache similarity index 100% rename from custom-templates/model_mod.mustache rename to openapi-generator-template/model_mod.mustache diff --git a/custom-templates/partial_header.mustache b/openapi-generator-template/partial_header.mustache similarity index 100% rename from custom-templates/partial_header.mustache rename to openapi-generator-template/partial_header.mustache diff --git a/custom-templates/request.rs b/openapi-generator-template/request.rs similarity index 100% rename from custom-templates/request.rs rename to openapi-generator-template/request.rs diff --git a/custom-templates/reqwest/api.mustache b/openapi-generator-template/reqwest/api.mustache similarity index 100% rename from custom-templates/reqwest/api.mustache rename to openapi-generator-template/reqwest/api.mustache diff --git a/custom-templates/reqwest/api_mod.mustache b/openapi-generator-template/reqwest/api_mod.mustache similarity index 100% rename from custom-templates/reqwest/api_mod.mustache rename to openapi-generator-template/reqwest/api_mod.mustache diff --git a/custom-templates/reqwest/configuration.mustache b/openapi-generator-template/reqwest/configuration.mustache similarity index 100% rename from custom-templates/reqwest/configuration.mustache rename to openapi-generator-template/reqwest/configuration.mustache diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 0552300..9b3ab05 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -12,7 +12,7 @@ const SPEC_URL: &str = // Input spec file, expected in the project root. const INPUT_SPEC_FILE: &str = "openapi.yml"; const OUTPUT_PREPROCESSED_FILE: &str = "./preprocessed_openapi.yml"; -const CUSTOM_TEMPLATES_DIR: &str = "custom-templates"; // Directory containing our custom templates +const CUSTOM_TEMPLATES_DIR: &str = "openapi-generator-template"; // Directory containing our custom templates // Output directory for the generated code. const OUTPUT_DIR: &str = "typesense_codegen"; From 634ca79fd8191dbb2b39cebb2311ee2b157ae326 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Wed, 3 Sep 2025 18:11:48 +0700 Subject: [PATCH 11/41] refactor: `to_owned` instead of `to_string` --- typesense/src/client/mod.rs | 20 ++++----- typesense/src/client/multi_search.rs | 12 ++--- typesense/tests/client/client_test.rs | 2 +- typesense/tests/client/collections_test.rs | 14 +++--- typesense/tests/client/documents_test.rs | 50 ++++++++++----------- typesense/tests/client/keys_test.rs | 10 ++--- typesense/tests/client/multi_search_test.rs | 22 ++++----- 7 files changed, 65 insertions(+), 65 deletions(-) diff --git a/typesense/src/client/mod.rs b/typesense/src/client/mod.rs index 25dcfb8..06056da 100644 --- a/typesense/src/client/mod.rs +++ b/typesense/src/client/mod.rs @@ -39,8 +39,8 @@ //! //! // Search for a document //! let search_params = models::SearchParameters { -//! q: Some("phone".to_string()), -//! query_by: Some("name".to_string()), +//! q: Some("phone".to_owned()), +//! query_by: Some("name".to_owned()), //! ..Default::default() //! }; //! @@ -92,8 +92,8 @@ //! //! // Search for a document //! let search_params = models::SearchParameters { -//! q: Some("phone".to_string()), -//! query_by: Some("name".to_string()), +//! q: Some("phone".to_owned()), +//! query_by: Some("name".to_owned()), //! ..Default::default() //! }; //! @@ -470,9 +470,9 @@ impl Client { /// # .build() /// # .unwrap(); /// # let schema = models::ApiKeySchema { - /// # description: "Search-only key.".to_string(), - /// # actions: vec!["documents:search".to_string()], - /// # collections: vec!["*".to_string()], + /// # description: "Search-only key.".to_owned(), + /// # actions: vec!["documents:search".to_owned()], + /// # collections: vec!["*".to_owned()], /// # ..Default::default() /// # }; /// let new_key = client.keys().create(schema).await.unwrap(); @@ -530,9 +530,9 @@ impl Client { /// # .unwrap(); /// # let search_requests = models::MultiSearchBody { /// # searches: vec![models::MultiSearchCollectionParameters { - /// # collection: Some("products".to_string()), - /// # q: Some("phone".to_string()), - /// # query_by: Some("name".to_string()), + /// # collection: Some("products".to_owned()), + /// # q: Some("phone".to_owned()), + /// # query_by: Some("name".to_owned()), /// # ..Default::default() /// # }], /// # ..Default::default() diff --git a/typesense/src/client/multi_search.rs b/typesense/src/client/multi_search.rs index 4d329a8..9041035 100644 --- a/typesense/src/client/multi_search.rs +++ b/typesense/src/client/multi_search.rs @@ -69,16 +69,16 @@ impl<'a> MultiSearch<'a> { /// searches: vec![ /// // Search #0 targets the 'products' collection /// models::MultiSearchCollectionParameters { - /// collection: Some("products".to_string()), - /// q: Some("shoe".to_string()), - /// query_by: Some("name".to_string()), + /// collection: Some("products".to_owned()), + /// q: Some("shoe".to_owned()), + /// query_by: Some("name".to_owned()), /// ..Default::default() /// }, /// // Search #1 targets the 'brands' collection /// models::MultiSearchCollectionParameters { - /// collection: Some("brands".to_string()), - /// q: Some("nike".to_string()), - /// query_by: Some("company_name".to_string()), + /// collection: Some("brands".to_owned()), + /// q: Some("nike".to_owned()), + /// query_by: Some("company_name".to_owned()), /// ..Default::default() /// }, /// ], diff --git a/typesense/tests/client/client_test.rs b/typesense/tests/client/client_test.rs index 931d3aa..d996d9e 100644 --- a/typesense/tests/client/client_test.rs +++ b/typesense/tests/client/client_test.rs @@ -11,7 +11,7 @@ use wiremock::{Mock, MockServer, ResponseTemplate}; // Helper to create a mock Typesense server for a successful collection retrieval. async fn setup_mock_server_ok(server: &MockServer, collection_name: &str) { let response_body = CollectionResponse { - name: collection_name.to_string(), + name: collection_name.to_owned(), ..Default::default() }; diff --git a/typesense/tests/client/collections_test.rs b/typesense/tests/client/collections_test.rs index a762e77..eab99a9 100644 --- a/typesense/tests/client/collections_test.rs +++ b/typesense/tests/client/collections_test.rs @@ -14,13 +14,13 @@ async fn logic_test_collections_and_collection_lifecycle() { name: collection_name.clone(), fields: vec![ Field { - name: "name".to_string(), - r#type: "string".to_string(), + name: "name".to_owned(), + r#type: "string".to_owned(), ..Default::default() }, Field { - name: "price".to_string(), - r#type: "int32".to_string(), + name: "price".to_owned(), + r#type: "int32".to_owned(), ..Default::default() }, ], @@ -65,14 +65,14 @@ async fn logic_test_collections_and_collection_lifecycle() { fields: vec![ // Add a new field Field { - name: "description".to_string(), - r#type: "string".to_string(), + name: "description".to_owned(), + r#type: "string".to_owned(), optional: Some(true), ..Default::default() }, // Drop an existing field Field { - name: "price".to_string(), + name: "price".to_owned(), drop: Some(true), ..Default::default() }, diff --git a/typesense/tests/client/documents_test.rs b/typesense/tests/client/documents_test.rs index 9bb47a8..63c37bf 100644 --- a/typesense/tests/client/documents_test.rs +++ b/typesense/tests/client/documents_test.rs @@ -17,19 +17,19 @@ async fn run_test_document_lifecycle() { name: collection_name.clone(), fields: vec![ Field { - name: "title".to_string(), - r#type: "string".to_string(), + name: "title".to_owned(), + r#type: "string".to_owned(), ..Default::default() }, Field { - name: "author".to_string(), - r#type: "string".to_string(), + name: "author".to_owned(), + r#type: "string".to_owned(), facet: Some(true), ..Default::default() }, Field { - name: "publication_year".to_string(), - r#type: "int32".to_string(), + name: "publication_year".to_owned(), + r#type: "int32".to_owned(), ..Default::default() }, ], @@ -142,8 +142,8 @@ async fn run_test_document_lifecycle() { // --- 11. Verify Import via Search --- let search_after_import_params = SearchParameters { - q: Some("*".to_string()), - query_by: Some("title".to_string()), + q: Some("*".to_owned()), + query_by: Some("title".to_owned()), ..Default::default() }; let search_after_import_res = documents_client.search(search_after_import_params).await; @@ -153,7 +153,7 @@ async fn run_test_document_lifecycle() { // --- 12. Bulk Update (via `documents().update()`) --- let bulk_update_params = UpdateDocumentsParameters { - filter_by: Some("publication_year:<1960".to_string()), + filter_by: Some("publication_year:<1960".to_owned()), }; let bulk_update_payload = json!({ "author": "Sci-Fi Pioneer" }); let bulk_update_res = documents_client @@ -165,7 +165,7 @@ async fn run_test_document_lifecycle() { // --- 13. Export documents (via `documents().export()`) --- let export_params = ExportDocumentsParameters { - filter_by: Some("author:\"Sci-Fi Pioneer\"".to_string()), + filter_by: Some("author:\"Sci-Fi Pioneer\"".to_owned()), ..Default::default() }; let export_res = documents_client.export(export_params).await; @@ -181,7 +181,7 @@ async fn run_test_document_lifecycle() { // --- 14. Bulk Delete --- let delete_params = DeleteDocumentsParameters { - filter_by: "publication_year:>1960".to_string(), + filter_by: "publication_year:>1960".to_owned(), ..Default::default() }; let bulk_delete_res = documents_client.delete(delete_params).await; @@ -212,24 +212,24 @@ async fn run_test_generic_document_lifecycle() { name: collection_name.clone(), fields: vec![ Field { - name: "title".to_string(), - r#type: "string".to_string(), + name: "title".to_owned(), + r#type: "string".to_owned(), ..Default::default() }, Field { - name: "author".to_string(), - r#type: "string".to_string(), + name: "author".to_owned(), + r#type: "string".to_owned(), facet: Some(true), ..Default::default() }, Field { - name: "publication_year".to_string(), - r#type: "int32".to_string(), + name: "publication_year".to_owned(), + r#type: "int32".to_owned(), ..Default::default() }, Field { - name: "in_stock".to_string(), - r#type: "bool".to_string(), + name: "in_stock".to_owned(), + r#type: "bool".to_owned(), optional: Some(true), ..Default::default() }, @@ -248,16 +248,16 @@ async fn run_test_generic_document_lifecycle() { let book_1 = Book { id: new_id("book_1"), - title: "Dune".to_string(), - author: "Frank Herbert".to_string(), + title: "Dune".to_owned(), + author: "Frank Herbert".to_owned(), publication_year: 1965, in_stock: Some(true), }; let book_2 = Book { id: new_id("book_2"), - title: "Foundation".to_string(), - author: "Isaac Asimov".to_string(), + title: "Foundation".to_owned(), + author: "Isaac Asimov".to_owned(), publication_year: 1951, in_stock: Some(false), }; @@ -280,8 +280,8 @@ async fn run_test_generic_document_lifecycle() { // --- 5. Search for documents with strongly-typed results --- let search_params = SearchParameters { - q: Some("dune".to_string()), - query_by: Some("title".to_string()), + q: Some("dune".to_owned()), + query_by: Some("title".to_owned()), ..Default::default() }; let search_res = typed_collection.documents().search(search_params).await; diff --git a/typesense/tests/client/keys_test.rs b/typesense/tests/client/keys_test.rs index 95683ac..a2f4a21 100644 --- a/typesense/tests/client/keys_test.rs +++ b/typesense/tests/client/keys_test.rs @@ -7,9 +7,9 @@ async fn run_test_keys_lifecycle() { // --- 1. Create a new API Key (via `keys`) --- let key_schema = ApiKeySchema { - description: key_description.to_string(), - actions: vec!["documents:search".to_string()], // Grant only search permissions - collections: vec!["*".to_string()], // For all collections + description: key_description.to_owned(), + actions: vec!["documents:search".to_owned()], // Grant only search permissions + collections: vec!["*".to_owned()], // For all collections ..Default::default() }; @@ -22,7 +22,7 @@ async fn run_test_keys_lifecycle() { created_key.value.is_some(), "The full API key value should be present upon creation." ); - assert_eq!(created_key.description, key_description.to_string()); + assert_eq!(created_key.description, key_description.to_owned()); let key_id = created_key.id.unwrap(); @@ -88,7 +88,7 @@ fn test_generate_scoped_search_key_with_example_values() { // The parameters to be embedded in the new scoped key. let params = ScopedKeyParameters { search_params: Some(SearchParameters { - filter_by: Some("company_id:124".to_string()), + filter_by: Some("company_id:124".to_owned()), ..Default::default() }), expires_at: Some(1906054106), diff --git a/typesense/tests/client/multi_search_test.rs b/typesense/tests/client/multi_search_test.rs index ea567de..c9c91c1 100644 --- a/typesense/tests/client/multi_search_test.rs +++ b/typesense/tests/client/multi_search_test.rs @@ -16,20 +16,20 @@ async fn setup_multi_search_tests( ) { // --- Create collections --- let products_schema = CollectionSchema { - name: products_collection_name.to_string(), + name: products_collection_name.to_owned(), fields: vec![ - Field::new("name".to_string(), "string".to_string()), - Field::new("price".to_string(), "int32".to_string()), + Field::new("name".to_owned(), "string".to_owned()), + Field::new("price".to_owned(), "int32".to_owned()), ], ..Default::default() }; client.collections().create(products_schema).await.unwrap(); let brands_schema = CollectionSchema { - name: brands_collection_name.to_string(), + name: brands_collection_name.to_owned(), fields: vec![ - Field::new("company_name".to_string(), "string".to_string()), - Field::new("country".to_string(), "string".to_string()), + Field::new("company_name".to_owned(), "string".to_owned()), + Field::new("country".to_owned(), "string".to_owned()), ], ..Default::default() }; @@ -302,8 +302,8 @@ async fn run_test_multi_search_generic_parsing() { assert_eq!( *product_doc, Product { - id: "p2".to_string(), - name: "MacBook Pro".to_string(), + id: "p2".to_owned(), + name: "MacBook Pro".to_owned(), price: 1999, } ); @@ -325,9 +325,9 @@ async fn run_test_multi_search_generic_parsing() { assert_eq!( *brand_doc, Brand { - id: "b1".to_string(), - company_name: "Apple Inc.".to_string(), - country: "USA".to_string(), + id: "b1".to_owned(), + company_name: "Apple Inc.".to_owned(), + country: "USA".to_owned(), } ); } From e7fe4c5c156f7d0323668a10f612b8ab1b7c2c1e Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Fri, 5 Sep 2025 20:40:17 +0700 Subject: [PATCH 12/41] ci: remove httpmock, ci with real Typesense server --- .github/workflows/ci.yml | 41 +++++++++++++++++------------ .github/workflows/lint.yml | 11 ++++++-- mocks/create_collection.yaml | 24 ----------------- mocks/drop_collection.yaml | 23 ---------------- mocks/import_documents.yaml | 13 --------- mocks/retrieve_all_collections.yaml | 34 ------------------------ mocks/retrieve_collection.yaml | 23 ---------------- mocks/search_collection.yaml | 17 ------------ typesense/src/client/mod.rs | 2 +- 9 files changed, 34 insertions(+), 154 deletions(-) delete mode 100644 mocks/create_collection.yaml delete mode 100644 mocks/drop_collection.yaml delete mode 100644 mocks/import_documents.yaml delete mode 100644 mocks/retrieve_all_collections.yaml delete mode 100644 mocks/retrieve_collection.yaml delete mode 100644 mocks/search_collection.yaml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0356dc7..c5583ca 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,26 +1,40 @@ name: CI on: + workflow_dispatch: push: branches: - main + paths-ignore: + - '**/*.md' pull_request: branches: - main + paths-ignore: + - '**/*.md' jobs: tests: - runs-on: "${{ matrix.platform.os }}-latest" + runs-on: '${{ matrix.platform.os }}-latest' strategy: matrix: - platform: [ - { os: "ubuntu", target: "x86_64-unknown-linux-gnu" }, - { os: "ubuntu", target: "wasm32-unknown-unknown" }, - ] - env: - # used to connect to httpmock - URL: "http://localhost:5000" - API_KEY: "VerySecretKey" + platform: + [ + { os: 'ubuntu', target: 'x86_64-unknown-linux-gnu' }, + { os: 'ubuntu', target: 'wasm32-unknown-unknown' }, + ] + services: + typesense: + image: typesense/typesense:29.0 + ports: + - 8108:8108/tcp + volumes: + - /tmp/typesense-server-data:/data + env: + TYPESENSE_DATA_DIR: '/data' + TYPESENSE_API_KEY: 'xyz' + TYPESENSE_ENABLE_CORS: true + TYPESENSE_URL: 'http://localhost:8108' steps: - uses: actions/checkout@v4 - name: Cache .cargo and target @@ -38,16 +52,9 @@ jobs: target: ${{ matrix.platform.target }} profile: minimal default: true - - name: Install httpmock - uses: actions-rs/cargo@v1 - with: - command: install - args: --features standalone -- httpmock - - name: Run httpmock - run: httpmock --expose --mock-files-dir=./mocks & - name: Install test runner for wasm if: matrix.platform.target == 'wasm32-unknown-unknown' - run: curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh + run: curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh - name: Stable Build uses: actions-rs/cargo@v1 with: diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 0527114..00e4569 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -1,10 +1,17 @@ name: Lint checks on: + workflow_dispatch: push: - branches: [ main ] + branches: + - main + paths-ignore: + - '**/*.md' pull_request: - branches: [ main ] + branches: + - main + paths-ignore: + - '**/*.md' jobs: lint: diff --git a/mocks/create_collection.yaml b/mocks/create_collection.yaml deleted file mode 100644 index a2168e6..0000000 --- a/mocks/create_collection.yaml +++ /dev/null @@ -1,24 +0,0 @@ -when: - method: POST - path: /collections - header: - - name: X-TYPESENSE-API-KEY - value: VerySecretKey - body: '{"name":"companies","fields":[{"name":"company_name","type":"string"},{"name":"num_employees","type":"int32"},{"name":"country","type":"string","facet":true}],"default_sorting_field":"num_employees"}' -then: - status: 200 - header: - - name: content-type - value: text/json - body: ' - { - "name": "companies", - "num_documents": 0, - "fields": [ - {"name": "company_name", "type": "string" }, - {"name": "num_employees", "type": "int32" }, - {"name": "country", "type": "string", "facet": true } - ], - "default_sorting_field": "num_employees", - "created_at": 1 - }' diff --git a/mocks/drop_collection.yaml b/mocks/drop_collection.yaml deleted file mode 100644 index 26c3655..0000000 --- a/mocks/drop_collection.yaml +++ /dev/null @@ -1,23 +0,0 @@ -when: - method: DELETE - path: /collections/companies - header: - - name: X-TYPESENSE-API-KEY - value: VerySecretKey -then: - status: 200 - header: - - name: content-type - value: text/json - body: ' - { - "name": "companies", - "num_documents": 1200, - "fields": [ - {"name": "company_name", "type": "string" }, - {"name": "num_employees", "type": "int32" }, - {"name": "country", "type": "string", "facet": true } - ], - "default_sorting_field": "num_employees", - "created_at": 1 - }' diff --git a/mocks/import_documents.yaml b/mocks/import_documents.yaml deleted file mode 100644 index e7469b7..0000000 --- a/mocks/import_documents.yaml +++ /dev/null @@ -1,13 +0,0 @@ -when: - method: POST - path: /collections/companies/documents/import - header: - - name: X-TYPESENSE-API-KEY - value: VerySecretKey - body: "{\"company_name\":\"test\",\"num_employees\":1,\"country\":\"c1\"}\n{\"company_name\":\"test2\",\"num_employees\":2,\"country\":\"c2\"}" -then: - status: 200 - header: - - name: content-type - value: application/text - body: "{\"success\":true}\n{\"success\":true}" diff --git a/mocks/retrieve_all_collections.yaml b/mocks/retrieve_all_collections.yaml deleted file mode 100644 index ccaaa50..0000000 --- a/mocks/retrieve_all_collections.yaml +++ /dev/null @@ -1,34 +0,0 @@ -when: - method: GET - path: /collections - header: - - name: X-TYPESENSE-API-KEY - value: VerySecretKey -then: - status: 200 - header: - - name: content-type - value: text/json - body: ' - [{ - "num_documents": 1250, - "name": "companies", - "fields": [ - {"name": "company_name", "type": "string"}, - {"name": "num_employees", "type": "int32"}, - {"name": "country", "type": "string", "facet": true} - ], - "default_sorting_field": "num_employees", - "created_at": 1 - }, - { - "num_documents": 1250, - "name": "ceos", - "fields": [ - {"name": "company_name", "type": "string"}, - {"name": "full_name", "type": "string"}, - {"name": "from_year", "type": "int32"} - ], - "default_sorting_field": "num_employees", - "created_at": 1 - }]' diff --git a/mocks/retrieve_collection.yaml b/mocks/retrieve_collection.yaml deleted file mode 100644 index ff4d743..0000000 --- a/mocks/retrieve_collection.yaml +++ /dev/null @@ -1,23 +0,0 @@ -when: - method: GET - path: /collections/companies - header: - - name: X-TYPESENSE-API-KEY - value: VerySecretKey -then: - status: 200 - header: - - name: content-type - value: text/json - body: ' - { - "name": "companies", - "num_documents": 1250, - "fields": [ - {"name": "company_name", "type": "string" }, - {"name": "num_employees", "type": "int32" }, - {"name": "country", "type": "string", "facet": true } - ], - "default_sorting_field": "num_employees", - "created_at": 1 - }' diff --git a/mocks/search_collection.yaml b/mocks/search_collection.yaml deleted file mode 100644 index 1c5f294..0000000 --- a/mocks/search_collection.yaml +++ /dev/null @@ -1,17 +0,0 @@ -when: - method: GET - path: /collections/companies/documents/search - header: - - name: X-TYPESENSE-API-KEY - value: VerySecretKey - query_param: - - name: q - value: test - - name: query_by - value: company_name -then: - status: 200 - header: - - name: content-type - value: application/text - body: "{\"facet_counts\":[],\"found\":2,\"hits\":[{\"document\":{\"company_name\":\"test\",\"country\":\"c1\",\"id\":\"0\",\"num_employees\":1},\"highlight\":{\"company_name\":{\"matched_tokens\":[\"test\"],\"snippet\":\"test\"}},\"highlights\":[{\"field\":\"company_name\",\"matched_tokens\":[\"test\"],\"snippet\":\"test\"}],\"text_match\":578730123365711993,\"text_match_info\":{\"best_field_score\":\"1108091339008\",\"best_field_weight\":15,\"fields_matched\":1,\"score\":\"578730123365711993\",\"tokens_matched\":1}},{\"document\":{\"company_name\":\"test2\",\"country\":\"c2\",\"id\":\"1\",\"num_employees\":2},\"highlight\":{\"company_name\":{\"matched_tokens\":[\"test\"],\"snippet\":\"test2\"}},\"highlights\":[{\"field\":\"company_name\",\"matched_tokens\":[\"test\"],\"snippet\":\"test2\"}],\"text_match\":578730089005449337,\"text_match_info\":{\"best_field_score\":\"1108074561536\",\"best_field_weight\":15,\"fields_matched\":1,\"score\":\"578730089005449337\",\"tokens_matched\":1}}],\"out_of\":2,\"page\":1,\"request_params\":{\"collection_name\":\"companies\",\"per_page\":10,\"q\":\"test\"},\"search_cutoff\":false,\"search_time_ms\":0}" diff --git a/typesense/src/client/mod.rs b/typesense/src/client/mod.rs index 06056da..3013a33 100644 --- a/typesense/src/client/mod.rs +++ b/typesense/src/client/mod.rs @@ -371,7 +371,7 @@ impl Client { /// Provides access to API endpoints for a specific collection. /// - /// This method returns a `Collection` handle, which is generic over the type of document + /// This method returns a `Collection` handle, which is generic over the type of document /// stored in that collection. /// /// # Type Parameters From d9b3a205580a0a81dbbd6ffcffa75743043d33d8 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Fri, 5 Sep 2025 20:55:58 +0700 Subject: [PATCH 13/41] ci: use typesense v30.0.rc10 --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c5583ca..b50ee12 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,7 +25,7 @@ jobs: ] services: typesense: - image: typesense/typesense:29.0 + image: typesense/typesense:30.0.rc10 ports: - 8108:8108/tcp volumes: From 4b811e2e7ee10ed1acaeb654674cf0c30797b65d Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Fri, 5 Sep 2025 21:07:34 +0700 Subject: [PATCH 14/41] ignore rust fmt for `typesense_codegen` --- .github/workflows/lint.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 00e4569..b631420 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -17,7 +17,7 @@ jobs: lint: runs-on: ubuntu-latest env: - TZ: "/usr/share/zoneinfo/your/location" + TZ: '/usr/share/zoneinfo/your/location' steps: - uses: actions/checkout@v4 - name: Cache .cargo and target @@ -39,7 +39,7 @@ jobs: uses: actions-rs/cargo@v1 with: command: fmt - args: --all -- --check + args: --package typesense --package typesense_derive --package xtask -- --check - run: rustup component add clippy - name: Run clippy uses: actions-rs/cargo@v1 From b6fde07478bbafa6fac8f87fd7ac9277a999b2cd Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Sun, 7 Sep 2025 15:03:48 +0700 Subject: [PATCH 15/41] feat: explicit `x-rust-builder: true` to generate builders for open api models --- openapi-generator-template/model.mustache | 7 +++++-- openapi.yml | 5 +++++ preprocessed_openapi.yml | 5 +++++ typesense_codegen/src/models/analytics_event.rs | 3 +-- .../src/models/analytics_event_create_response.rs | 3 +-- typesense_codegen/src/models/analytics_event_data.rs | 3 +-- typesense_codegen/src/models/analytics_events_response.rs | 3 +-- .../src/models/analytics_events_response_events_inner.rs | 3 +-- typesense_codegen/src/models/analytics_rule.rs | 3 +-- typesense_codegen/src/models/analytics_rule_create.rs | 3 +-- .../src/models/analytics_rule_create_params.rs | 3 +-- typesense_codegen/src/models/analytics_rule_update.rs | 3 +-- typesense_codegen/src/models/analytics_status.rs | 3 +-- typesense_codegen/src/models/api_key.rs | 3 +-- typesense_codegen/src/models/api_key_delete_response.rs | 3 +-- typesense_codegen/src/models/api_key_schema.rs | 3 +-- typesense_codegen/src/models/api_keys_response.rs | 3 +-- typesense_codegen/src/models/api_response.rs | 3 +-- typesense_codegen/src/models/api_stats_response.rs | 3 +-- typesense_codegen/src/models/collection_alias.rs | 3 +-- typesense_codegen/src/models/collection_alias_schema.rs | 3 +-- .../src/models/collection_aliases_response.rs | 3 +-- typesense_codegen/src/models/collection_response.rs | 3 +-- typesense_codegen/src/models/collection_schema.rs | 3 ++- typesense_codegen/src/models/collection_update_schema.rs | 3 +-- .../src/models/conversation_model_create_schema.rs | 3 +-- typesense_codegen/src/models/conversation_model_schema.rs | 3 +-- .../src/models/conversation_model_update_schema.rs | 3 +-- .../create_analytics_rule_200_response_one_of_inner.rs | 3 +-- ...eate_analytics_rule_200_response_one_of_inner_any_of.rs | 3 +-- typesense_codegen/src/models/debug_200_response.rs | 3 +-- .../src/models/delete_documents_200_response.rs | 3 +-- .../src/models/delete_documents_parameters.rs | 3 +-- .../src/models/delete_stopwords_set_200_response.rs | 3 +-- .../src/models/export_documents_parameters.rs | 3 +-- typesense_codegen/src/models/facet_counts.rs | 3 +-- typesense_codegen/src/models/facet_counts_counts_inner.rs | 3 +-- typesense_codegen/src/models/facet_counts_stats.rs | 3 +-- typesense_codegen/src/models/field.rs | 3 ++- typesense_codegen/src/models/field_embed.rs | 3 +-- typesense_codegen/src/models/field_embed_model_config.rs | 3 +-- typesense_codegen/src/models/get_collections_parameters.rs | 3 +-- typesense_codegen/src/models/health_status.rs | 3 +-- .../src/models/import_documents_parameters.rs | 3 +-- .../src/models/list_stemming_dictionaries_200_response.rs | 3 +-- .../src/models/multi_search_collection_parameters.rs | 3 ++- typesense_codegen/src/models/multi_search_parameters.rs | 3 ++- typesense_codegen/src/models/multi_search_result.rs | 3 +-- typesense_codegen/src/models/multi_search_result_item.rs | 3 +-- .../src/models/multi_search_searches_parameter.rs | 3 +-- typesense_codegen/src/models/nl_search_model_base.rs | 3 +-- .../src/models/nl_search_model_create_schema.rs | 3 +-- .../src/models/nl_search_model_delete_schema.rs | 3 +-- typesense_codegen/src/models/nl_search_model_schema.rs | 3 +-- typesense_codegen/src/models/preset_delete_schema.rs | 3 +-- typesense_codegen/src/models/preset_schema.rs | 3 +-- typesense_codegen/src/models/preset_upsert_schema.rs | 3 +-- typesense_codegen/src/models/presets_retrieve_schema.rs | 3 +-- typesense_codegen/src/models/schema_change_status.rs | 3 +-- typesense_codegen/src/models/search_grouped_hit.rs | 3 +-- typesense_codegen/src/models/search_highlight.rs | 3 +-- typesense_codegen/src/models/search_override.rs | 3 +-- .../src/models/search_override_delete_response.rs | 3 +-- typesense_codegen/src/models/search_override_exclude.rs | 3 +-- typesense_codegen/src/models/search_override_include.rs | 3 +-- typesense_codegen/src/models/search_override_rule.rs | 3 +-- typesense_codegen/src/models/search_override_schema.rs | 3 +-- typesense_codegen/src/models/search_overrides_response.rs | 3 +-- typesense_codegen/src/models/search_parameters.rs | 3 ++- typesense_codegen/src/models/search_request_params.rs | 3 +-- .../src/models/search_request_params_voice_query.rs | 3 +-- typesense_codegen/src/models/search_result.rs | 3 +-- typesense_codegen/src/models/search_result_conversation.rs | 3 +-- typesense_codegen/src/models/search_result_hit.rs | 3 +-- .../src/models/search_result_hit_hybrid_search_info.rs | 3 +-- .../src/models/search_result_hit_text_match_info.rs | 3 +-- typesense_codegen/src/models/search_synonym.rs | 3 +-- .../src/models/search_synonym_delete_response.rs | 3 +-- typesense_codegen/src/models/search_synonym_schema.rs | 3 +-- typesense_codegen/src/models/search_synonyms_response.rs | 3 +-- typesense_codegen/src/models/stemming_dictionary.rs | 3 +-- .../src/models/stemming_dictionary_words_inner.rs | 3 +-- .../src/models/stopwords_set_retrieve_schema.rs | 3 +-- typesense_codegen/src/models/stopwords_set_schema.rs | 3 +-- .../src/models/stopwords_set_upsert_schema.rs | 3 +-- .../src/models/stopwords_sets_retrieve_all_schema.rs | 3 +-- typesense_codegen/src/models/success_status.rs | 3 +-- typesense_codegen/src/models/synonym_item_schema.rs | 3 +-- typesense_codegen/src/models/synonym_set_create_schema.rs | 3 +-- typesense_codegen/src/models/synonym_set_delete_schema.rs | 3 +-- typesense_codegen/src/models/synonym_set_schema.rs | 3 +-- .../src/models/synonym_sets_retrieve_schema.rs | 3 +-- .../src/models/toggle_slow_request_log_request.rs | 3 +-- .../src/models/update_documents_200_response.rs | 3 +-- .../src/models/update_documents_parameters.rs | 3 +-- .../src/models/voice_query_model_collection_config.rs | 3 +-- 96 files changed, 113 insertions(+), 183 deletions(-) diff --git a/openapi-generator-template/model.mustache b/openapi-generator-template/model.mustache index b72f188..627362a 100644 --- a/openapi-generator-template/model.mustache +++ b/openapi-generator-template/model.mustache @@ -121,9 +121,12 @@ impl Default for {{classname}} { {{!-- for non-enum schemas --}} {{^isEnum}} {{^discriminator}} -{{#vendorExtensions.x-rust-has-byte-array}}#[serde_as] -{{/vendorExtensions.x-rust-has-byte-array}}{{#oneOf.isEmpty}}#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +{{#vendorExtensions.x-rust-builder}} +#[derive(bon::Builder)] #[builder(on(String, into))] +{{/vendorExtensions.x-rust-builder}} +{{#vendorExtensions.x-rust-has-byte-array}}#[serde_as] +{{/vendorExtensions.x-rust-has-byte-array}}{{#oneOf.isEmpty}}#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct {{{classname}}}{{{vendorExtensions.x-rust-generic-parameter}}} { {{#vars}} {{#description}} diff --git a/openapi.yml b/openapi.yml index f40206f..3108e43 100644 --- a/openapi.yml +++ b/openapi.yml @@ -2165,6 +2165,7 @@ components: - name - fields type: object + x-rust-builder: true properties: name: type: string @@ -2288,6 +2289,7 @@ components: - name - type type: object + x-rust-builder: true properties: name: type: string @@ -2950,6 +2952,7 @@ components: description: Error description SearchParameters: type: object + x-rust-builder: true properties: q: description: The query text to search for in the collection. @@ -3361,6 +3364,7 @@ components: description: > Parameters for the multi search API. type: object + x-rust-builder: true properties: q: description: The query text to search for in the collection. @@ -3748,6 +3752,7 @@ components: items: $ref: "#/components/schemas/MultiSearchCollectionParameters" MultiSearchCollectionParameters: + x-rust-builder: true allOf: - $ref: "#/components/schemas/MultiSearchParameters" - type: object diff --git a/preprocessed_openapi.yml b/preprocessed_openapi.yml index 6f82fbd..9daf180 100644 --- a/preprocessed_openapi.yml +++ b/preprocessed_openapi.yml @@ -2864,6 +2864,7 @@ components: - name - fields type: object + x-rust-builder: true properties: name: type: string @@ -2977,6 +2978,7 @@ components: - name - type type: object + x-rust-builder: true properties: name: type: string @@ -3624,6 +3626,7 @@ components: description: Error description SearchParameters: type: object + x-rust-builder: true properties: q: description: The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. @@ -3899,6 +3902,7 @@ components: description: | Parameters for the multi search API. type: object + x-rust-builder: true properties: q: description: The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. @@ -4158,6 +4162,7 @@ components: items: $ref: '#/components/schemas/MultiSearchCollectionParameters' MultiSearchCollectionParameters: + x-rust-builder: true allOf: - $ref: '#/components/schemas/MultiSearchParameters' - type: object diff --git a/typesense_codegen/src/models/analytics_event.rs b/typesense_codegen/src/models/analytics_event.rs index c02ad1a..4559896 100644 --- a/typesense_codegen/src/models/analytics_event.rs +++ b/typesense_codegen/src/models/analytics_event.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct AnalyticsEvent { /// Name of the analytics rule this event corresponds to #[serde(rename = "name")] diff --git a/typesense_codegen/src/models/analytics_event_create_response.rs b/typesense_codegen/src/models/analytics_event_create_response.rs index db9a23b..c15ca25 100644 --- a/typesense_codegen/src/models/analytics_event_create_response.rs +++ b/typesense_codegen/src/models/analytics_event_create_response.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct AnalyticsEventCreateResponse { #[serde(rename = "ok")] pub ok: bool, diff --git a/typesense_codegen/src/models/analytics_event_data.rs b/typesense_codegen/src/models/analytics_event_data.rs index c9434be..75b44f9 100644 --- a/typesense_codegen/src/models/analytics_event_data.rs +++ b/typesense_codegen/src/models/analytics_event_data.rs @@ -12,8 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; /// AnalyticsEventData : Event payload -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct AnalyticsEventData { #[serde(rename = "user_id", skip_serializing_if = "Option::is_none")] pub user_id: Option, diff --git a/typesense_codegen/src/models/analytics_events_response.rs b/typesense_codegen/src/models/analytics_events_response.rs index 85a68d8..fafd98b 100644 --- a/typesense_codegen/src/models/analytics_events_response.rs +++ b/typesense_codegen/src/models/analytics_events_response.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct AnalyticsEventsResponse { #[serde(rename = "events")] pub events: Vec, diff --git a/typesense_codegen/src/models/analytics_events_response_events_inner.rs b/typesense_codegen/src/models/analytics_events_response_events_inner.rs index d090aac..93f9dfc 100644 --- a/typesense_codegen/src/models/analytics_events_response_events_inner.rs +++ b/typesense_codegen/src/models/analytics_events_response_events_inner.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct AnalyticsEventsResponseEventsInner { #[serde(rename = "name", skip_serializing_if = "Option::is_none")] pub name: Option, diff --git a/typesense_codegen/src/models/analytics_rule.rs b/typesense_codegen/src/models/analytics_rule.rs index eba704a..cc15a1d 100644 --- a/typesense_codegen/src/models/analytics_rule.rs +++ b/typesense_codegen/src/models/analytics_rule.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct AnalyticsRule { #[serde(rename = "name")] pub name: String, diff --git a/typesense_codegen/src/models/analytics_rule_create.rs b/typesense_codegen/src/models/analytics_rule_create.rs index fe494b2..9373230 100644 --- a/typesense_codegen/src/models/analytics_rule_create.rs +++ b/typesense_codegen/src/models/analytics_rule_create.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct AnalyticsRuleCreate { #[serde(rename = "name")] pub name: String, diff --git a/typesense_codegen/src/models/analytics_rule_create_params.rs b/typesense_codegen/src/models/analytics_rule_create_params.rs index 116cac7..de7cf5a 100644 --- a/typesense_codegen/src/models/analytics_rule_create_params.rs +++ b/typesense_codegen/src/models/analytics_rule_create_params.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct AnalyticsRuleCreateParams { #[serde(rename = "destination_collection", skip_serializing_if = "Option::is_none")] pub destination_collection: Option, diff --git a/typesense_codegen/src/models/analytics_rule_update.rs b/typesense_codegen/src/models/analytics_rule_update.rs index c5a393f..66ad385 100644 --- a/typesense_codegen/src/models/analytics_rule_update.rs +++ b/typesense_codegen/src/models/analytics_rule_update.rs @@ -12,8 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; /// AnalyticsRuleUpdate : Fields allowed to update on an analytics rule -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct AnalyticsRuleUpdate { #[serde(rename = "name", skip_serializing_if = "Option::is_none")] pub name: Option, diff --git a/typesense_codegen/src/models/analytics_status.rs b/typesense_codegen/src/models/analytics_status.rs index c160da3..9d1b6bf 100644 --- a/typesense_codegen/src/models/analytics_status.rs +++ b/typesense_codegen/src/models/analytics_status.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct AnalyticsStatus { #[serde(rename = "popular_prefix_queries", skip_serializing_if = "Option::is_none")] pub popular_prefix_queries: Option, diff --git a/typesense_codegen/src/models/api_key.rs b/typesense_codegen/src/models/api_key.rs index fe95571..f108ead 100644 --- a/typesense_codegen/src/models/api_key.rs +++ b/typesense_codegen/src/models/api_key.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct ApiKey { #[serde(rename = "value", skip_serializing_if = "Option::is_none")] pub value: Option, diff --git a/typesense_codegen/src/models/api_key_delete_response.rs b/typesense_codegen/src/models/api_key_delete_response.rs index 36bef3f..c12440d 100644 --- a/typesense_codegen/src/models/api_key_delete_response.rs +++ b/typesense_codegen/src/models/api_key_delete_response.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct ApiKeyDeleteResponse { /// The id of the API key that was deleted #[serde(rename = "id")] diff --git a/typesense_codegen/src/models/api_key_schema.rs b/typesense_codegen/src/models/api_key_schema.rs index a0fed21..3e8c2ab 100644 --- a/typesense_codegen/src/models/api_key_schema.rs +++ b/typesense_codegen/src/models/api_key_schema.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct ApiKeySchema { #[serde(rename = "value", skip_serializing_if = "Option::is_none")] pub value: Option, diff --git a/typesense_codegen/src/models/api_keys_response.rs b/typesense_codegen/src/models/api_keys_response.rs index ec1c0b2..ca7686c 100644 --- a/typesense_codegen/src/models/api_keys_response.rs +++ b/typesense_codegen/src/models/api_keys_response.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct ApiKeysResponse { #[serde(rename = "keys")] pub keys: Vec, diff --git a/typesense_codegen/src/models/api_response.rs b/typesense_codegen/src/models/api_response.rs index 1253278..08c2c11 100644 --- a/typesense_codegen/src/models/api_response.rs +++ b/typesense_codegen/src/models/api_response.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct ApiResponse { #[serde(rename = "message")] pub message: String, diff --git a/typesense_codegen/src/models/api_stats_response.rs b/typesense_codegen/src/models/api_stats_response.rs index 41b886d..d8d2933 100644 --- a/typesense_codegen/src/models/api_stats_response.rs +++ b/typesense_codegen/src/models/api_stats_response.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct ApiStatsResponse { #[serde(rename = "delete_latency_ms", skip_serializing_if = "Option::is_none")] pub delete_latency_ms: Option, diff --git a/typesense_codegen/src/models/collection_alias.rs b/typesense_codegen/src/models/collection_alias.rs index a3b22b7..f94f6a2 100644 --- a/typesense_codegen/src/models/collection_alias.rs +++ b/typesense_codegen/src/models/collection_alias.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct CollectionAlias { /// Name of the collection alias #[serde(rename = "name")] diff --git a/typesense_codegen/src/models/collection_alias_schema.rs b/typesense_codegen/src/models/collection_alias_schema.rs index a2946d4..3a67ea0 100644 --- a/typesense_codegen/src/models/collection_alias_schema.rs +++ b/typesense_codegen/src/models/collection_alias_schema.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct CollectionAliasSchema { /// Name of the collection you wish to map the alias to #[serde(rename = "collection_name")] diff --git a/typesense_codegen/src/models/collection_aliases_response.rs b/typesense_codegen/src/models/collection_aliases_response.rs index a74e69c..0db53a1 100644 --- a/typesense_codegen/src/models/collection_aliases_response.rs +++ b/typesense_codegen/src/models/collection_aliases_response.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct CollectionAliasesResponse { #[serde(rename = "aliases")] pub aliases: Vec, diff --git a/typesense_codegen/src/models/collection_response.rs b/typesense_codegen/src/models/collection_response.rs index 00442c2..d664428 100644 --- a/typesense_codegen/src/models/collection_response.rs +++ b/typesense_codegen/src/models/collection_response.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct CollectionResponse { /// Name of the collection #[serde(rename = "name")] diff --git a/typesense_codegen/src/models/collection_schema.rs b/typesense_codegen/src/models/collection_schema.rs index 9640c6f..7e2c754 100644 --- a/typesense_codegen/src/models/collection_schema.rs +++ b/typesense_codegen/src/models/collection_schema.rs @@ -11,8 +11,9 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[derive(bon::Builder)] #[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct CollectionSchema { /// Name of the collection #[serde(rename = "name")] diff --git a/typesense_codegen/src/models/collection_update_schema.rs b/typesense_codegen/src/models/collection_update_schema.rs index 9abcce6..ca45a78 100644 --- a/typesense_codegen/src/models/collection_update_schema.rs +++ b/typesense_codegen/src/models/collection_update_schema.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct CollectionUpdateSchema { /// A list of fields for querying, filtering and faceting #[serde(rename = "fields")] diff --git a/typesense_codegen/src/models/conversation_model_create_schema.rs b/typesense_codegen/src/models/conversation_model_create_schema.rs index 327a757..3a2ed5b 100644 --- a/typesense_codegen/src/models/conversation_model_create_schema.rs +++ b/typesense_codegen/src/models/conversation_model_create_schema.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct ConversationModelCreateSchema { /// An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. #[serde(rename = "id", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/conversation_model_schema.rs b/typesense_codegen/src/models/conversation_model_schema.rs index 92cf6c6..828988d 100644 --- a/typesense_codegen/src/models/conversation_model_schema.rs +++ b/typesense_codegen/src/models/conversation_model_schema.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct ConversationModelSchema { /// An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. #[serde(rename = "id")] diff --git a/typesense_codegen/src/models/conversation_model_update_schema.rs b/typesense_codegen/src/models/conversation_model_update_schema.rs index 98d710a..7ac5e40 100644 --- a/typesense_codegen/src/models/conversation_model_update_schema.rs +++ b/typesense_codegen/src/models/conversation_model_update_schema.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct ConversationModelUpdateSchema { /// An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. #[serde(rename = "id", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs index 7b72e4b..8e773e2 100644 --- a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs +++ b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct CreateAnalyticsRule200ResponseOneOfInner { #[serde(rename = "name")] pub name: String, diff --git a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs index 126d313..12f7422 100644 --- a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs +++ b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct CreateAnalyticsRule200ResponseOneOfInnerAnyOf { #[serde(rename = "error", skip_serializing_if = "Option::is_none")] pub error: Option, diff --git a/typesense_codegen/src/models/debug_200_response.rs b/typesense_codegen/src/models/debug_200_response.rs index 2032659..0c88dd7 100644 --- a/typesense_codegen/src/models/debug_200_response.rs +++ b/typesense_codegen/src/models/debug_200_response.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct Debug200Response { #[serde(rename = "version", skip_serializing_if = "Option::is_none")] pub version: Option, diff --git a/typesense_codegen/src/models/delete_documents_200_response.rs b/typesense_codegen/src/models/delete_documents_200_response.rs index 4d9f208..5779adf 100644 --- a/typesense_codegen/src/models/delete_documents_200_response.rs +++ b/typesense_codegen/src/models/delete_documents_200_response.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct DeleteDocuments200Response { #[serde(rename = "num_deleted")] pub num_deleted: i32, diff --git a/typesense_codegen/src/models/delete_documents_parameters.rs b/typesense_codegen/src/models/delete_documents_parameters.rs index 972005c..903d717 100644 --- a/typesense_codegen/src/models/delete_documents_parameters.rs +++ b/typesense_codegen/src/models/delete_documents_parameters.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct DeleteDocumentsParameters { #[serde(rename = "filter_by")] pub filter_by: String, diff --git a/typesense_codegen/src/models/delete_stopwords_set_200_response.rs b/typesense_codegen/src/models/delete_stopwords_set_200_response.rs index 2d9bf3a..87fa748 100644 --- a/typesense_codegen/src/models/delete_stopwords_set_200_response.rs +++ b/typesense_codegen/src/models/delete_stopwords_set_200_response.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct DeleteStopwordsSet200Response { #[serde(rename = "id")] pub id: String, diff --git a/typesense_codegen/src/models/export_documents_parameters.rs b/typesense_codegen/src/models/export_documents_parameters.rs index fbf8b61..b1defbb 100644 --- a/typesense_codegen/src/models/export_documents_parameters.rs +++ b/typesense_codegen/src/models/export_documents_parameters.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct ExportDocumentsParameters { /// Filter conditions for refining your search results. Separate multiple conditions with &&. #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/facet_counts.rs b/typesense_codegen/src/models/facet_counts.rs index b48c6cf..a56913a 100644 --- a/typesense_codegen/src/models/facet_counts.rs +++ b/typesense_codegen/src/models/facet_counts.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct FacetCounts { #[serde(rename = "counts", skip_serializing_if = "Option::is_none")] pub counts: Option>, diff --git a/typesense_codegen/src/models/facet_counts_counts_inner.rs b/typesense_codegen/src/models/facet_counts_counts_inner.rs index fc5f6ff..9b732a5 100644 --- a/typesense_codegen/src/models/facet_counts_counts_inner.rs +++ b/typesense_codegen/src/models/facet_counts_counts_inner.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct FacetCountsCountsInner { #[serde(rename = "count", skip_serializing_if = "Option::is_none")] pub count: Option, diff --git a/typesense_codegen/src/models/facet_counts_stats.rs b/typesense_codegen/src/models/facet_counts_stats.rs index b54f770..24a8e63 100644 --- a/typesense_codegen/src/models/facet_counts_stats.rs +++ b/typesense_codegen/src/models/facet_counts_stats.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct FacetCountsStats { #[serde(rename = "max", skip_serializing_if = "Option::is_none")] pub max: Option, diff --git a/typesense_codegen/src/models/field.rs b/typesense_codegen/src/models/field.rs index 0d367af..b3fd4d7 100644 --- a/typesense_codegen/src/models/field.rs +++ b/typesense_codegen/src/models/field.rs @@ -11,8 +11,9 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[derive(bon::Builder)] #[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct Field { #[serde(rename = "name")] pub name: String, diff --git a/typesense_codegen/src/models/field_embed.rs b/typesense_codegen/src/models/field_embed.rs index 628bfc3..2b9b203 100644 --- a/typesense_codegen/src/models/field_embed.rs +++ b/typesense_codegen/src/models/field_embed.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct FieldEmbed { #[serde(rename = "from")] pub from: Vec, diff --git a/typesense_codegen/src/models/field_embed_model_config.rs b/typesense_codegen/src/models/field_embed_model_config.rs index 92fe3fe..407e32f 100644 --- a/typesense_codegen/src/models/field_embed_model_config.rs +++ b/typesense_codegen/src/models/field_embed_model_config.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct FieldEmbedModelConfig { #[serde(rename = "model_name")] pub model_name: String, diff --git a/typesense_codegen/src/models/get_collections_parameters.rs b/typesense_codegen/src/models/get_collections_parameters.rs index 198ec45..01226a7 100644 --- a/typesense_codegen/src/models/get_collections_parameters.rs +++ b/typesense_codegen/src/models/get_collections_parameters.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct GetCollectionsParameters { /// Comma-separated list of fields from the collection to exclude from the response #[serde(rename = "exclude_fields", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/health_status.rs b/typesense_codegen/src/models/health_status.rs index 7ee44c8..82a4489 100644 --- a/typesense_codegen/src/models/health_status.rs +++ b/typesense_codegen/src/models/health_status.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct HealthStatus { #[serde(rename = "ok")] pub ok: bool, diff --git a/typesense_codegen/src/models/import_documents_parameters.rs b/typesense_codegen/src/models/import_documents_parameters.rs index ad6f325..0b7abab 100644 --- a/typesense_codegen/src/models/import_documents_parameters.rs +++ b/typesense_codegen/src/models/import_documents_parameters.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct ImportDocumentsParameters { #[serde(rename = "batch_size", skip_serializing_if = "Option::is_none")] pub batch_size: Option, diff --git a/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs b/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs index 8934aa6..75a8ddf 100644 --- a/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs +++ b/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct ListStemmingDictionaries200Response { #[serde(rename = "dictionaries", skip_serializing_if = "Option::is_none")] pub dictionaries: Option>, diff --git a/typesense_codegen/src/models/multi_search_collection_parameters.rs b/typesense_codegen/src/models/multi_search_collection_parameters.rs index fba4310..cc5a457 100644 --- a/typesense_codegen/src/models/multi_search_collection_parameters.rs +++ b/typesense_codegen/src/models/multi_search_collection_parameters.rs @@ -11,8 +11,9 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[derive(bon::Builder)] #[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct MultiSearchCollectionParameters { /// The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. #[serde(rename = "q", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/multi_search_parameters.rs b/typesense_codegen/src/models/multi_search_parameters.rs index ef4651d..7602ca5 100644 --- a/typesense_codegen/src/models/multi_search_parameters.rs +++ b/typesense_codegen/src/models/multi_search_parameters.rs @@ -12,8 +12,9 @@ use crate::models; use serde::{Deserialize, Serialize}; /// MultiSearchParameters : Parameters for the multi search API. -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[derive(bon::Builder)] #[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct MultiSearchParameters { /// The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. #[serde(rename = "q", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/multi_search_result.rs b/typesense_codegen/src/models/multi_search_result.rs index e8e07cd..d3ffd67 100644 --- a/typesense_codegen/src/models/multi_search_result.rs +++ b/typesense_codegen/src/models/multi_search_result.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct MultiSearchResult { #[serde(rename = "results")] pub results: Vec>, diff --git a/typesense_codegen/src/models/multi_search_result_item.rs b/typesense_codegen/src/models/multi_search_result_item.rs index 99f9936..6f4c8bc 100644 --- a/typesense_codegen/src/models/multi_search_result_item.rs +++ b/typesense_codegen/src/models/multi_search_result_item.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct MultiSearchResultItem { #[serde(rename = "facet_counts", skip_serializing_if = "Option::is_none")] pub facet_counts: Option>, diff --git a/typesense_codegen/src/models/multi_search_searches_parameter.rs b/typesense_codegen/src/models/multi_search_searches_parameter.rs index 91878e9..f8e69d3 100644 --- a/typesense_codegen/src/models/multi_search_searches_parameter.rs +++ b/typesense_codegen/src/models/multi_search_searches_parameter.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct MultiSearchSearchesParameter { /// When true, merges the search results from each search query into a single ordered set of hits. #[serde(rename = "union", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/nl_search_model_base.rs b/typesense_codegen/src/models/nl_search_model_base.rs index 596c740..4e08735 100644 --- a/typesense_codegen/src/models/nl_search_model_base.rs +++ b/typesense_codegen/src/models/nl_search_model_base.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct NlSearchModelBase { /// Name of the NL model to use #[serde(rename = "model_name", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/nl_search_model_create_schema.rs b/typesense_codegen/src/models/nl_search_model_create_schema.rs index 880c084..4259d0a 100644 --- a/typesense_codegen/src/models/nl_search_model_create_schema.rs +++ b/typesense_codegen/src/models/nl_search_model_create_schema.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct NlSearchModelCreateSchema { /// Name of the NL model to use #[serde(rename = "model_name", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/nl_search_model_delete_schema.rs b/typesense_codegen/src/models/nl_search_model_delete_schema.rs index cf5912a..20dbf83 100644 --- a/typesense_codegen/src/models/nl_search_model_delete_schema.rs +++ b/typesense_codegen/src/models/nl_search_model_delete_schema.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct NlSearchModelDeleteSchema { /// ID of the deleted NL search model #[serde(rename = "id")] diff --git a/typesense_codegen/src/models/nl_search_model_schema.rs b/typesense_codegen/src/models/nl_search_model_schema.rs index 4d9b126..9a24637 100644 --- a/typesense_codegen/src/models/nl_search_model_schema.rs +++ b/typesense_codegen/src/models/nl_search_model_schema.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct NlSearchModelSchema { /// Name of the NL model to use #[serde(rename = "model_name", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/preset_delete_schema.rs b/typesense_codegen/src/models/preset_delete_schema.rs index 4d93986..77294d0 100644 --- a/typesense_codegen/src/models/preset_delete_schema.rs +++ b/typesense_codegen/src/models/preset_delete_schema.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct PresetDeleteSchema { #[serde(rename = "name")] pub name: String, diff --git a/typesense_codegen/src/models/preset_schema.rs b/typesense_codegen/src/models/preset_schema.rs index 9b4eb95..8c9352c 100644 --- a/typesense_codegen/src/models/preset_schema.rs +++ b/typesense_codegen/src/models/preset_schema.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct PresetSchema { #[serde(rename = "value")] pub value: Box, diff --git a/typesense_codegen/src/models/preset_upsert_schema.rs b/typesense_codegen/src/models/preset_upsert_schema.rs index 1ccb101..92203f8 100644 --- a/typesense_codegen/src/models/preset_upsert_schema.rs +++ b/typesense_codegen/src/models/preset_upsert_schema.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct PresetUpsertSchema { #[serde(rename = "value")] pub value: Box, diff --git a/typesense_codegen/src/models/presets_retrieve_schema.rs b/typesense_codegen/src/models/presets_retrieve_schema.rs index b1f1b0b..e13bc93 100644 --- a/typesense_codegen/src/models/presets_retrieve_schema.rs +++ b/typesense_codegen/src/models/presets_retrieve_schema.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct PresetsRetrieveSchema { #[serde(rename = "presets")] pub presets: Vec, diff --git a/typesense_codegen/src/models/schema_change_status.rs b/typesense_codegen/src/models/schema_change_status.rs index c0414d9..f051a9b 100644 --- a/typesense_codegen/src/models/schema_change_status.rs +++ b/typesense_codegen/src/models/schema_change_status.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SchemaChangeStatus { /// Name of the collection being modified #[serde(rename = "collection", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/search_grouped_hit.rs b/typesense_codegen/src/models/search_grouped_hit.rs index e74cd76..73d9292 100644 --- a/typesense_codegen/src/models/search_grouped_hit.rs +++ b/typesense_codegen/src/models/search_grouped_hit.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchGroupedHit { #[serde(rename = "found", skip_serializing_if = "Option::is_none")] pub found: Option, diff --git a/typesense_codegen/src/models/search_highlight.rs b/typesense_codegen/src/models/search_highlight.rs index aefa1eb..0b5101d 100644 --- a/typesense_codegen/src/models/search_highlight.rs +++ b/typesense_codegen/src/models/search_highlight.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchHighlight { #[serde(rename = "field", skip_serializing_if = "Option::is_none")] pub field: Option, diff --git a/typesense_codegen/src/models/search_override.rs b/typesense_codegen/src/models/search_override.rs index 006d556..0740e2d 100644 --- a/typesense_codegen/src/models/search_override.rs +++ b/typesense_codegen/src/models/search_override.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchOverride { #[serde(rename = "rule")] pub rule: Box, diff --git a/typesense_codegen/src/models/search_override_delete_response.rs b/typesense_codegen/src/models/search_override_delete_response.rs index b89be93..23bc8f4 100644 --- a/typesense_codegen/src/models/search_override_delete_response.rs +++ b/typesense_codegen/src/models/search_override_delete_response.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchOverrideDeleteResponse { /// The id of the override that was deleted #[serde(rename = "id")] diff --git a/typesense_codegen/src/models/search_override_exclude.rs b/typesense_codegen/src/models/search_override_exclude.rs index f4a0c24..e6c0dee 100644 --- a/typesense_codegen/src/models/search_override_exclude.rs +++ b/typesense_codegen/src/models/search_override_exclude.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchOverrideExclude { /// document id that should be excluded from the search results. #[serde(rename = "id")] diff --git a/typesense_codegen/src/models/search_override_include.rs b/typesense_codegen/src/models/search_override_include.rs index 56f3fc8..5344b55 100644 --- a/typesense_codegen/src/models/search_override_include.rs +++ b/typesense_codegen/src/models/search_override_include.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchOverrideInclude { /// document id that should be included #[serde(rename = "id")] diff --git a/typesense_codegen/src/models/search_override_rule.rs b/typesense_codegen/src/models/search_override_rule.rs index 9985d30..3ce37a4 100644 --- a/typesense_codegen/src/models/search_override_rule.rs +++ b/typesense_codegen/src/models/search_override_rule.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchOverrideRule { /// List of tag values to associate with this override rule. #[serde(rename = "tags", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/search_override_schema.rs b/typesense_codegen/src/models/search_override_schema.rs index 0463084..8dfdd8c 100644 --- a/typesense_codegen/src/models/search_override_schema.rs +++ b/typesense_codegen/src/models/search_override_schema.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchOverrideSchema { #[serde(rename = "rule")] pub rule: Box, diff --git a/typesense_codegen/src/models/search_overrides_response.rs b/typesense_codegen/src/models/search_overrides_response.rs index b888bfa..eaef52b 100644 --- a/typesense_codegen/src/models/search_overrides_response.rs +++ b/typesense_codegen/src/models/search_overrides_response.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchOverridesResponse { #[serde(rename = "overrides")] pub overrides: Vec, diff --git a/typesense_codegen/src/models/search_parameters.rs b/typesense_codegen/src/models/search_parameters.rs index a7253d5..d1f8f89 100644 --- a/typesense_codegen/src/models/search_parameters.rs +++ b/typesense_codegen/src/models/search_parameters.rs @@ -11,8 +11,9 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +#[derive(bon::Builder)] #[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchParameters { /// The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. #[serde(rename = "q", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/search_request_params.rs b/typesense_codegen/src/models/search_request_params.rs index 0b0dcd1..727ebb7 100644 --- a/typesense_codegen/src/models/search_request_params.rs +++ b/typesense_codegen/src/models/search_request_params.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchRequestParams { #[serde(rename = "collection_name")] pub collection_name: String, diff --git a/typesense_codegen/src/models/search_request_params_voice_query.rs b/typesense_codegen/src/models/search_request_params_voice_query.rs index 5afcd97..b5fd5a3 100644 --- a/typesense_codegen/src/models/search_request_params_voice_query.rs +++ b/typesense_codegen/src/models/search_request_params_voice_query.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchRequestParamsVoiceQuery { #[serde(rename = "transcribed_query", skip_serializing_if = "Option::is_none")] pub transcribed_query: Option, diff --git a/typesense_codegen/src/models/search_result.rs b/typesense_codegen/src/models/search_result.rs index 303ec88..b1630c9 100644 --- a/typesense_codegen/src/models/search_result.rs +++ b/typesense_codegen/src/models/search_result.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchResult { #[serde(rename = "facet_counts", skip_serializing_if = "Option::is_none")] pub facet_counts: Option>, diff --git a/typesense_codegen/src/models/search_result_conversation.rs b/typesense_codegen/src/models/search_result_conversation.rs index 5e7e124..c47f800 100644 --- a/typesense_codegen/src/models/search_result_conversation.rs +++ b/typesense_codegen/src/models/search_result_conversation.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchResultConversation { #[serde(rename = "answer")] pub answer: String, diff --git a/typesense_codegen/src/models/search_result_hit.rs b/typesense_codegen/src/models/search_result_hit.rs index 7ce8215..8ffb5e4 100644 --- a/typesense_codegen/src/models/search_result_hit.rs +++ b/typesense_codegen/src/models/search_result_hit.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchResultHit { /// (Deprecated) Contains highlighted portions of the search fields #[serde(rename = "highlights", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs b/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs index e675e57..def14c5 100644 --- a/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs +++ b/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs @@ -12,8 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; /// SearchResultHitHybridSearchInfo : Information about hybrid search scoring -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchResultHitHybridSearchInfo { /// Combined score from rank fusion of text and vector search #[serde(rename = "rank_fusion_score", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/search_result_hit_text_match_info.rs b/typesense_codegen/src/models/search_result_hit_text_match_info.rs index 89cb80f..6ad7736 100644 --- a/typesense_codegen/src/models/search_result_hit_text_match_info.rs +++ b/typesense_codegen/src/models/search_result_hit_text_match_info.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchResultHitTextMatchInfo { #[serde(rename = "best_field_score", skip_serializing_if = "Option::is_none")] pub best_field_score: Option, diff --git a/typesense_codegen/src/models/search_synonym.rs b/typesense_codegen/src/models/search_synonym.rs index 5dcbb5c..4310dab 100644 --- a/typesense_codegen/src/models/search_synonym.rs +++ b/typesense_codegen/src/models/search_synonym.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchSynonym { /// For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. #[serde(rename = "root", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/search_synonym_delete_response.rs b/typesense_codegen/src/models/search_synonym_delete_response.rs index 6bb092f..d138eab 100644 --- a/typesense_codegen/src/models/search_synonym_delete_response.rs +++ b/typesense_codegen/src/models/search_synonym_delete_response.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchSynonymDeleteResponse { /// The id of the synonym that was deleted #[serde(rename = "id")] diff --git a/typesense_codegen/src/models/search_synonym_schema.rs b/typesense_codegen/src/models/search_synonym_schema.rs index 08db709..99a96a9 100644 --- a/typesense_codegen/src/models/search_synonym_schema.rs +++ b/typesense_codegen/src/models/search_synonym_schema.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchSynonymSchema { /// For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. #[serde(rename = "root", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/search_synonyms_response.rs b/typesense_codegen/src/models/search_synonyms_response.rs index 82d93b0..eab2311 100644 --- a/typesense_codegen/src/models/search_synonyms_response.rs +++ b/typesense_codegen/src/models/search_synonyms_response.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchSynonymsResponse { #[serde(rename = "synonyms")] pub synonyms: Vec, diff --git a/typesense_codegen/src/models/stemming_dictionary.rs b/typesense_codegen/src/models/stemming_dictionary.rs index 978d4c0..3976e9c 100644 --- a/typesense_codegen/src/models/stemming_dictionary.rs +++ b/typesense_codegen/src/models/stemming_dictionary.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct StemmingDictionary { /// Unique identifier for the dictionary #[serde(rename = "id")] diff --git a/typesense_codegen/src/models/stemming_dictionary_words_inner.rs b/typesense_codegen/src/models/stemming_dictionary_words_inner.rs index 88a2b83..c712b4b 100644 --- a/typesense_codegen/src/models/stemming_dictionary_words_inner.rs +++ b/typesense_codegen/src/models/stemming_dictionary_words_inner.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct StemmingDictionaryWordsInner { /// The word form to be stemmed #[serde(rename = "word")] diff --git a/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs b/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs index b1a1934..c3b7b9c 100644 --- a/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs +++ b/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct StopwordsSetRetrieveSchema { #[serde(rename = "stopwords")] pub stopwords: Box, diff --git a/typesense_codegen/src/models/stopwords_set_schema.rs b/typesense_codegen/src/models/stopwords_set_schema.rs index 01049b1..bf1dace 100644 --- a/typesense_codegen/src/models/stopwords_set_schema.rs +++ b/typesense_codegen/src/models/stopwords_set_schema.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct StopwordsSetSchema { #[serde(rename = "id")] pub id: String, diff --git a/typesense_codegen/src/models/stopwords_set_upsert_schema.rs b/typesense_codegen/src/models/stopwords_set_upsert_schema.rs index 0e98ef1..2feb7f1 100644 --- a/typesense_codegen/src/models/stopwords_set_upsert_schema.rs +++ b/typesense_codegen/src/models/stopwords_set_upsert_schema.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct StopwordsSetUpsertSchema { #[serde(rename = "stopwords")] pub stopwords: Vec, diff --git a/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs b/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs index 8cab67c..8e26e17 100644 --- a/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs +++ b/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct StopwordsSetsRetrieveAllSchema { #[serde(rename = "stopwords")] pub stopwords: Vec, diff --git a/typesense_codegen/src/models/success_status.rs b/typesense_codegen/src/models/success_status.rs index c27ffe7..9b1f636 100644 --- a/typesense_codegen/src/models/success_status.rs +++ b/typesense_codegen/src/models/success_status.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SuccessStatus { #[serde(rename = "success")] pub success: bool, diff --git a/typesense_codegen/src/models/synonym_item_schema.rs b/typesense_codegen/src/models/synonym_item_schema.rs index c21afad..8b1d84b 100644 --- a/typesense_codegen/src/models/synonym_item_schema.rs +++ b/typesense_codegen/src/models/synonym_item_schema.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SynonymItemSchema { /// Unique identifier for the synonym item #[serde(rename = "id")] diff --git a/typesense_codegen/src/models/synonym_set_create_schema.rs b/typesense_codegen/src/models/synonym_set_create_schema.rs index 0f3d0ee..c52dac9 100644 --- a/typesense_codegen/src/models/synonym_set_create_schema.rs +++ b/typesense_codegen/src/models/synonym_set_create_schema.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SynonymSetCreateSchema { /// Array of synonym items #[serde(rename = "items")] diff --git a/typesense_codegen/src/models/synonym_set_delete_schema.rs b/typesense_codegen/src/models/synonym_set_delete_schema.rs index 1b142df..e345e32 100644 --- a/typesense_codegen/src/models/synonym_set_delete_schema.rs +++ b/typesense_codegen/src/models/synonym_set_delete_schema.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SynonymSetDeleteSchema { /// Name of the deleted synonym set #[serde(rename = "name")] diff --git a/typesense_codegen/src/models/synonym_set_schema.rs b/typesense_codegen/src/models/synonym_set_schema.rs index dea8b9b..b500baf 100644 --- a/typesense_codegen/src/models/synonym_set_schema.rs +++ b/typesense_codegen/src/models/synonym_set_schema.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SynonymSetSchema { /// Array of synonym items #[serde(rename = "items")] diff --git a/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs b/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs index c43a073..ac28af6 100644 --- a/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs +++ b/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SynonymSetsRetrieveSchema { /// Array of synonym sets #[serde(rename = "synonym_sets")] diff --git a/typesense_codegen/src/models/toggle_slow_request_log_request.rs b/typesense_codegen/src/models/toggle_slow_request_log_request.rs index 282ddb2..fdce446 100644 --- a/typesense_codegen/src/models/toggle_slow_request_log_request.rs +++ b/typesense_codegen/src/models/toggle_slow_request_log_request.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct ToggleSlowRequestLogRequest { #[serde(rename = "log-slow-requests-time-ms")] pub log_slow_requests_time_ms: i32, diff --git a/typesense_codegen/src/models/update_documents_200_response.rs b/typesense_codegen/src/models/update_documents_200_response.rs index ec87fff..48d8905 100644 --- a/typesense_codegen/src/models/update_documents_200_response.rs +++ b/typesense_codegen/src/models/update_documents_200_response.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct UpdateDocuments200Response { /// The number of documents that have been updated #[serde(rename = "num_updated")] diff --git a/typesense_codegen/src/models/update_documents_parameters.rs b/typesense_codegen/src/models/update_documents_parameters.rs index 5735f53..36ce061 100644 --- a/typesense_codegen/src/models/update_documents_parameters.rs +++ b/typesense_codegen/src/models/update_documents_parameters.rs @@ -11,8 +11,7 @@ use crate::models; use serde::{Deserialize, Serialize}; -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct UpdateDocumentsParameters { #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] pub filter_by: Option, diff --git a/typesense_codegen/src/models/voice_query_model_collection_config.rs b/typesense_codegen/src/models/voice_query_model_collection_config.rs index dbab78f..99cb770 100644 --- a/typesense_codegen/src/models/voice_query_model_collection_config.rs +++ b/typesense_codegen/src/models/voice_query_model_collection_config.rs @@ -12,8 +12,7 @@ use crate::models; use serde::{Deserialize, Serialize}; /// VoiceQueryModelCollectionConfig : Configuration for the voice query model -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] -#[builder(on(String, into))] +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct VoiceQueryModelCollectionConfig { #[serde(rename = "model_name", skip_serializing_if = "Option::is_none")] pub model_name: Option, From 4d4d38ec807a89a995866162a9c4d0d5ac6c1fc9 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Sun, 7 Sep 2025 21:02:40 +0700 Subject: [PATCH 16/41] rename `x-rust-operation-generic-parameter` to `x-rust-generic-parameter` --- openapi-generator-template/reqwest/api.mustache | 4 ++-- openapi.yml | 2 +- preprocessed_openapi.yml | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/openapi-generator-template/reqwest/api.mustache b/openapi-generator-template/reqwest/api.mustache index d88f89a..b1feb8d 100644 --- a/openapi-generator-template/reqwest/api.mustache +++ b/openapi-generator-template/reqwest/api.mustache @@ -92,14 +92,14 @@ pub enum {{{operationIdCamelCase}}}Error { /// {{{.}}} {{/notes}} {{#vendorExtensions.x-group-parameters}} -pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}{{{vendorExtensions.x-rust-operation-generic-parameter}}}(configuration: &configuration::Configuration{{#allParams}}{{#-first}}, {{! +pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}{{{vendorExtensions.x-rust-generic-parameter}}}(configuration: &configuration::Configuration{{#allParams}}{{#-first}}, {{! ### Params }}params: {{{operationIdCamelCase}}}Params{{/-first}}{{/allParams}}{{! ### Function return type }}) -> Result<{{#vendorExtensions.x-rust-return-type}}{{{.}}}{{/vendorExtensions.x-rust-return-type}}{{^vendorExtensions.x-rust-return-type}}{{#isResponseFile}}{{#supportAsync}}reqwest::Response{{/supportAsync}}{{^supportAsync}}reqwest::blocking::Response{{/supportAsync}}{{/isResponseFile}}{{^isResponseFile}}{{#supportMultipleResponses}}ResponseContent<{{{operationIdCamelCase}}}Success>{{/supportMultipleResponses}}{{^supportMultipleResponses}}{{^returnType}}(){{/returnType}}{{{returnType}}}{{/supportMultipleResponses}}{{/isResponseFile}}{{/vendorExtensions.x-rust-return-type}}, Error<{{{operationIdCamelCase}}}Error>> { {{/vendorExtensions.x-group-parameters}} {{^vendorExtensions.x-group-parameters}} -pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}{{{vendorExtensions.x-rust-operation-generic-parameter}}}(configuration: &configuration::Configuration, {{#allParams}}{{{paramName}}}: {{! +pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}{{{vendorExtensions.x-rust-generic-parameter}}}(configuration: &configuration::Configuration, {{#allParams}}{{{paramName}}}: {{! ### Option Start }}{{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{! ### &str and Vec<&str> diff --git a/openapi.yml b/openapi.yml index 3108e43..a331198 100644 --- a/openapi.yml +++ b/openapi.yml @@ -429,7 +429,7 @@ paths: summary: Search for documents in a collection description: Search for documents in a collection that match the search criteria. operationId: searchCollection - x-rust-operation-generic-parameter: " serde::Deserialize<'de> + Serialize>" + x-rust-generic-parameter: " serde::Deserialize<'de> + Serialize>" x-rust-return-type: "models::SearchResult" parameters: - name: collectionName diff --git a/preprocessed_openapi.yml b/preprocessed_openapi.yml index 9daf180..0a034f3 100644 --- a/preprocessed_openapi.yml +++ b/preprocessed_openapi.yml @@ -405,7 +405,7 @@ paths: summary: Search for documents in a collection description: Search for documents in a collection that match the search criteria. operationId: searchCollection - x-rust-operation-generic-parameter: ' serde::Deserialize<''de> + Serialize>' + x-rust-generic-parameter: ' serde::Deserialize<''de> + Serialize>' x-rust-return-type: models::SearchResult parameters: - name: collectionName From d20bdecbb18484a4cefa0c9865d6d66daa3c8dea Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Sun, 7 Sep 2025 21:46:35 +0700 Subject: [PATCH 17/41] make `perform_union` generic and remove `UnionSearchResultExt` --- typesense/src/client/multi_search.rs | 95 ++++++++++++++------- typesense/src/traits/mod.rs | 2 +- typesense/src/traits/multi_search_ext.rs | 89 ------------------- typesense/tests/client/mod.rs | 13 +-- typesense/tests/client/multi_search_test.rs | 11 +-- 5 files changed, 71 insertions(+), 139 deletions(-) diff --git a/typesense/src/client/multi_search.rs b/typesense/src/client/multi_search.rs index 9041035..3e25fa8 100644 --- a/typesense/src/client/multi_search.rs +++ b/typesense/src/client/multi_search.rs @@ -27,8 +27,7 @@ impl<'a> MultiSearch<'a> { /// Performs a **federated** multi-search operation, returning a list of search results. /// /// This function allows you to send multiple search queries in a single HTTP request, which is - /// efficient for reducing network latency. It is specifically designed for federated searches, - /// where each query in the request runs independently and returns its own corresponding result. + /// efficient for reducing network latency. /// /// The returned `MultiSearchResult` contains a `results` vector where each item maps to a /// query in the request, in the exact same order. To process these results in a type-safe @@ -141,33 +140,53 @@ impl<'a> MultiSearch<'a> { /// Performs a multi-search request in **union** mode, returning a single, merged `SearchResult`. /// - /// This function is ideal for building a federated search experience where results from - /// different collections are displayed together in a single, ranked list. It forces - /// `union: true` in the search request. - /// /// For more details, see the /// [official Typesense API documentation on union search](https://typesense.org/docs/latest/api/federated-multi-search.html#union-search). /// /// ### Handling Search Results /// - /// The return type of this function is always `SearchResult` because - /// the search queries can target collections with different document schemas. - /// /// #### 1. Heterogeneous Documents (Different Schemas) /// - /// When searching across different collections (e.g., `products` and `brands`), you must - /// inspect the `serde_json::Value` of each document to determine its type before + /// When searching across different collections (e.g., `products` and `brands`), generic parameter `D` must be `serde_json::Value`. + /// You must inspect the `serde_json::Value` of each document to determine its type before /// deserializing it into a concrete struct. /// /// ```no_run - /// # use typesense::models::SearchResult; + /// # use typesense::{models, Client}; /// # use serde_json::Value; + /// # use reqwest::Url; /// # #[derive(serde::Deserialize)] /// # struct Product { name: String } /// # #[derive(serde::Deserialize)] /// # struct Brand { company_name: String } /// # async fn run() -> Result<(), Box> { - /// # let search_result: SearchResult = todo!(); + /// # let client = Client::builder() + /// # .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) + /// # .api_key("xyz") + /// # .build() + /// # .unwrap(); + /// let search_requests = models::MultiSearchBody { + /// searches: vec![ + /// // Search #0 targets the 'products' collection + /// models::MultiSearchCollectionParameters { + /// collection: Some("products".to_owned()), + /// q: Some("shoe".to_owned()), + /// query_by: Some("name".to_owned()), + /// ..Default::default() + /// }, + /// // Search #1 targets the 'brands' collection + /// models::MultiSearchCollectionParameters { + /// collection: Some("brands".to_owned()), + /// q: Some("nike".to_owned()), + /// query_by: Some("company_name".to_owned()), + /// ..Default::default() + /// }, + /// ], + /// ..Default::default() + /// }; + /// let common_params = models::MultiSearchParameters::default(); + /// + /// let search_result: models::SearchResult = client.multi_search().perform_union(search_requests, common_params).await?; /// for hit in search_result.hits.unwrap_or_default() { /// if let Some(doc) = hit.document { /// if doc.get("price").is_some() { @@ -185,22 +204,40 @@ impl<'a> MultiSearch<'a> { /// /// #### 2. Homogeneous Documents (Same Schema) /// - /// If all search queries target collections that share the **same schema**, you can - /// convert the entire result into a strongly-typed `SearchResult` using the - /// [`SearchResult::try_into_typed`] helper method. This is much more convenient - /// than parsing each hit individually. + /// If all search queries target collections that share the **same schema**, you can directly use the concrete type for `D`. /// /// ```no_run - /// # use typesense::{models::SearchResult, prelude::*}; + /// # use typesense::{models, Client}; + /// # use reqwest::Url; /// # use serde_json::Value; /// # #[derive(serde::Deserialize)] /// # struct Product { name: String } /// # async fn run() -> Result<(), Box> { - /// # let client: typesense::Client = todo!(); - /// let value_result: SearchResult = client.multi_search().perform_union(todo!(), todo!()).await?; + /// # let client = Client::builder() + /// # .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) + /// # .api_key("xyz") + /// # .build() + /// # .unwrap(); + /// let search_requests = models::MultiSearchBody { + /// searches: vec![ + /// models::MultiSearchCollectionParameters { + /// collection: Some("products".to_owned()), + /// q: Some("shoe".to_owned()), + /// query_by: Some("name".to_owned()), + /// ..Default::default() + /// }, + /// models::MultiSearchCollectionParameters { + /// collection: Some("products".to_owned()), + /// q: Some("sock".to_owned()), + /// query_by: Some("name".to_owned()), + /// ..Default::default() + /// }, + /// ], + /// ..Default::default() + /// }; + /// let common_params = models::MultiSearchParameters::default(); /// - /// // Convert the entire result into a strongly-typed one. - /// let typed_result: SearchResult = value_result.try_into_typed()?; + /// let typed_result: models::SearchResult = client.multi_search().perform_union(search_requests, common_params).await?; /// /// if let Some(product) = typed_result.hits.unwrap_or_default().get(0) { /// println!("Found product: {}", product.document.as_ref().unwrap().name); @@ -216,13 +253,13 @@ impl<'a> MultiSearch<'a> { /// /// # Returns /// - /// A `Result` containing a `SearchResult` on success, or an `Error` on failure. - pub async fn perform_union( + /// A `Result` containing a `SearchResult` on success, or an `Error` on failure. + pub async fn perform_union serde::Deserialize<'de>>( &self, search_requests: MultiSearchBody, common_search_params: raw_models::MultiSearchParameters, - ) -> Result, Error> { - // Explicitly set `union: true` for the request body, overriding any user value. + ) -> Result, Error> { + // Explicitly set `union: true` for the request body let request_body = raw_models::MultiSearchSearchesParameter { union: Some(true), searches: search_requests.searches, @@ -239,12 +276,8 @@ impl<'a> MultiSearch<'a> { }) .await; - // Handle the result: parse to raw SearchResult, then convert to generic SearchResult match raw_result { - Ok(json_value) => { - // A union search returns a single SearchResult object, not a MultiSearchResult. - serde_json::from_value(json_value).map_err(Error::from) - } + Ok(json_value) => serde_json::from_value(json_value).map_err(Error::from), Err(e) => Err(e), } } diff --git a/typesense/src/traits/mod.rs b/typesense/src/traits/mod.rs index 05203b4..667128e 100644 --- a/typesense/src/traits/mod.rs +++ b/typesense/src/traits/mod.rs @@ -6,4 +6,4 @@ mod multi_search_ext; pub use document::Document; pub use field_type::*; -pub use multi_search_ext::{MultiSearchResultExt, UnionSearchResultExt}; +pub use multi_search_ext::MultiSearchResultExt; diff --git a/typesense/src/traits/multi_search_ext.rs b/typesense/src/traits/multi_search_ext.rs index e5d3865..bdbc8e8 100644 --- a/typesense/src/traits/multi_search_ext.rs +++ b/typesense/src/traits/multi_search_ext.rs @@ -19,23 +19,6 @@ pub trait MultiSearchResultExt { ) -> Result, MultiSearchParseError>; } -/// An extension trait for `SearchResult` to provide typed parsing. -/// -/// This is primarily useful when working with results from a **union search**. -/// Since union searches return documents as raw JSON (`serde_json::Value`), -/// this trait allows you to attempt conversion into a concrete typed document -/// model of your choosing. -pub trait UnionSearchResultExt { - /// Attempts to convert a `SearchResult` into a `SearchResult`. - /// - /// # Type Parameters - /// * `D` - The concrete document type to deserialize the hits into. - /// - /// # Errors - /// Returns a `serde_json::Error` if any document in the result cannot be - /// successfully deserialized into type `D`. - fn try_into_typed(self) -> Result, serde_json::Error>; -} /// Small helpers to convert documents stored as `serde_json::Value` into a concrete `D`. fn deserialize_opt_document( doc: Option, @@ -78,38 +61,6 @@ fn convert_group_ref( }) } -fn convert_hit_owned( - value_hit: SearchResultHit, -) -> Result, serde_json::Error> { - Ok(SearchResultHit { - document: deserialize_opt_document(value_hit.document)?, - highlights: value_hit.highlights, - highlight: value_hit.highlight, - text_match: value_hit.text_match, - text_match_info: value_hit.text_match_info, - geo_distance_meters: value_hit.geo_distance_meters, - vector_distance: value_hit.vector_distance, - hybrid_search_info: value_hit.hybrid_search_info, - search_index: value_hit.search_index, - }) -} - -fn convert_group_owned( - group: SearchGroupedHit, -) -> Result, serde_json::Error> { - let hits = group - .hits - .into_iter() - .map(convert_hit_owned::) - .collect::, _>>()?; - - Ok(SearchGroupedHit { - found: group.found, - group_key: group.group_key, - hits, - }) -} - /// Convert a single `MultiSearchResultItem` into a strongly-typed `SearchResult`. fn multi_search_item_to_search_result( item: &MultiSearchResultItem, @@ -172,43 +123,3 @@ impl MultiSearchResultExt for MultiSearchResult { .map_err(|source| MultiSearchParseError::Deserialization { index, source }) } } - -/// Trait for converting a `SearchResult` (union result) into a typed one. -impl UnionSearchResultExt for SearchResult { - fn try_into_typed(self) -> Result, serde_json::Error> { - let typed_hits = match self.hits { - Some(value_hits) => Some( - value_hits - .into_iter() - .map(convert_hit_owned::) - .collect::, _>>()?, - ), - None => None, - }; - - let typed_grouped_hits = match self.grouped_hits { - Some(raw_groups) => Some( - raw_groups - .into_iter() - .map(convert_group_owned::) - .collect::, _>>()?, - ), - None => None, - }; - - Ok(SearchResult { - hits: typed_hits, - grouped_hits: typed_grouped_hits, - found: self.found, - found_docs: self.found_docs, - out_of: self.out_of, - page: self.page, - search_time_ms: self.search_time_ms, - facet_counts: self.facet_counts, - search_cutoff: self.search_cutoff, - request_params: self.request_params, - conversation: self.conversation, - union_request_params: self.union_request_params, - }) - } -} diff --git a/typesense/tests/client/mod.rs b/typesense/tests/client/mod.rs index 0f7f5aa..b410247 100644 --- a/typesense/tests/client/mod.rs +++ b/typesense/tests/client/mod.rs @@ -17,22 +17,17 @@ pub fn get_client() -> Client { .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) .api_key("xyz") .healthcheck_interval(Duration::from_secs(5)) - .retry_policy(ExponentialBackoff::builder().build_with_max_retries(1)) + .retry_policy(ExponentialBackoff::builder().build_with_max_retries(0)) .connection_timeout(Duration::from_secs(3)) .build() .expect("Failed to create Typesense client") } /// Generates a unique name for a test resource by combining a prefix, -/// a nanoid, and an optional suffix. -/// e.g., "test_collection_aB1cD2eF_create" +/// a timestamp, and a nano id. +/// e.g., "test_collection_123456789_aB1cD2eF" pub fn new_id(prefix: &str) -> String { - // Using nanoid for a short, URL-friendly, and collision-resistant random ID. - // The default length of 21 is more than enough. We use 8 for conciseness. - let random_part = nanoid::nanoid!(8); // e.g., "fX3a-b_1" - - // The timestamp helps ensure IDs are unique even across test runs that happen close together, - // although nanoid is likely sufficient on its own. + let random_part = nanoid::nanoid!(8); let timestamp = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() diff --git a/typesense/tests/client/multi_search_test.rs b/typesense/tests/client/multi_search_test.rs index c9c91c1..1af56c1 100644 --- a/typesense/tests/client/multi_search_test.rs +++ b/typesense/tests/client/multi_search_test.rs @@ -362,7 +362,7 @@ async fn run_test_multi_search_union_heterogeneous() { // Call the new union function let result = client .multi_search() - .perform_union(search_requests, common_params) + .perform_union::(search_requests, common_params) .await; assert!( @@ -440,19 +440,12 @@ async fn run_test_multi_search_union_homogeneous_and_typed_conversion() { ], }; - // 1. Call perform_union, which returns a SearchResult - let value_result = client + let typed_result: SearchResult = client .multi_search() .perform_union(search_requests, MultiSearchParameters::default()) .await .expect("Union search failed"); - // 2. Use the helper to convert it to a SearchResult - let typed_result: SearchResult = value_result - .try_into_typed() - .expect("Conversion to typed result failed"); - - // 3. Assert the strongly-typed result assert_eq!(typed_result.found, Some(2)); let mut hits = typed_result.hits.expect("Expected hits"); From 8609710806c08f07592eebb2ae0e0f8096d4185a Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Sun, 7 Sep 2025 22:37:26 +0700 Subject: [PATCH 18/41] use String instead of reqwest::Url for node configuration --- typesense/src/client/mod.rs | 42 ++++++++---------- typesense/src/lib.rs | 6 +-- typesense/tests/client/client_test.rs | 62 +++++---------------------- typesense/tests/client/mod.rs | 3 +- 4 files changed, 32 insertions(+), 81 deletions(-) diff --git a/typesense/src/client/mod.rs b/typesense/src/client/mod.rs index 3013a33..83e6aec 100644 --- a/typesense/src/client/mod.rs +++ b/typesense/src/client/mod.rs @@ -19,13 +19,12 @@ //! #[cfg(not(target_family = "wasm"))] //! { //! use typesense::{Client, models, ExponentialBackoff}; -//! use reqwest::Url; //! use std::time::Duration; //! //! #[tokio::main] //! async fn main() -> Result<(), Box> { //! let client = Client::builder() -//! .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) +//! .nodes(vec!["http://localhost:8108"]) //! .api_key("xyz") //! .healthcheck_interval(Duration::from_secs(60)) //! .retry_policy(ExponentialBackoff::builder().build_with_max_retries(3)) @@ -76,7 +75,7 @@ //! fn main() { //! spawn_local(async { //! let client = Client::builder() -//! .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) +//! .nodes(vec!["http://localhost:8108"]) //! .api_key("xyz") //! .healthcheck_interval(Duration::from_secs(60)) //! // .retry_policy(...) <-- not supported in Wasm @@ -122,7 +121,6 @@ use serde::Serialize; use serde::de::DeserializeOwned; use crate::Error; -use reqwest::Url; #[cfg(not(target_arch = "wasm32"))] use reqwest_middleware::ClientBuilder as ReqwestMiddlewareClientBuilder; #[cfg(not(target_arch = "wasm32"))] @@ -140,7 +138,7 @@ use web_time::{Duration, Instant}; // This is an internal detail to track the state of each node. #[derive(Debug)] struct Node { - url: Url, + url: String, is_healthy: bool, last_access_timestamp: Instant, } @@ -174,12 +172,17 @@ impl Client { #[builder] pub fn new( /// The Typesense API key used for authentication. - api_key: impl Into, + #[builder(into)] + api_key: String, /// A list of all nodes in the Typesense cluster. - nodes: Vec, - /// An optional, preferred node to try first for every request. This is for your server-side load balancer. + #[builder( + with = |iter: impl IntoIterator>| + iter.into_iter().map(Into::into).collect::>() + )] + nodes: Vec, #[builder(into)] - nearest_node: Option, + /// An optional, preferred node to try first for every request. This is for your server-side load balancer. + nearest_node: Option, #[builder(default = Duration::from_secs(60))] /// The duration after which an unhealthy node will be retried for requests. healthcheck_interval: Duration, @@ -216,7 +219,7 @@ impl Client { Ok(Self { nodes: node_list, nearest_node: nearest_node_arc, - api_key: api_key.into(), + api_key, healthcheck_interval, current_node_index: AtomicUsize::new(0), @@ -311,7 +314,6 @@ impl Client { // Create a temporary config for this attempt. let gen_config = configuration::Configuration { base_path: node_url - .to_string() .strip_suffix('/') .unwrap_or(node_url.as_str()) .to_string(), @@ -351,12 +353,11 @@ impl Client { /// # #[cfg(not(target_family = "wasm"))] /// # { /// # use typesense::{Client, GetCollectionsParameters}; - /// # use reqwest::Url; /// # /// # #[tokio::main] /// # async fn main() -> Result<(), Box> { /// # let client = Client::builder() - /// # .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) + /// # .nodes(vec!["http://localhost:8108"]) /// # .api_key("xyz") /// # .build() /// # .unwrap(); @@ -389,13 +390,12 @@ impl Client { /// # { /// # use typesense::Client; /// # use serde::{Serialize, Deserialize}; - /// # use reqwest::Url; /// # /// # #[derive(Serialize, Deserialize, Debug)] /// # struct Book { id: String, title: String } /// # async fn run() -> Result<(), Box> { /// # let client = Client::builder() - /// # .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) + /// # .nodes(vec!["http://localhost:8108"]) /// # .api_key("xyz") /// # .build() /// # .unwrap(); @@ -433,10 +433,9 @@ impl Client { /// # #[cfg(not(target_family = "wasm"))] /// # { /// # use typesense::Client; - /// # use reqwest::Url; /// # async fn run() -> Result<(), Box> { /// # let client = Client::builder() - /// # .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) + /// # .nodes(vec!["http://localhost:8108"]) /// # .api_key("xyz") /// # .build() /// # .unwrap(); @@ -460,12 +459,11 @@ impl Client { /// # #[cfg(not(target_family = "wasm"))] /// # { /// # use typesense::{Client, models}; - /// # use reqwest::Url; /// # /// # #[tokio::main] /// # async fn main() -> Result<(), Box> { /// # let client = Client::builder() - /// # .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) + /// # .nodes(vec!["http://localhost:8108"]) /// # .api_key("xyz") /// # .build() /// # .unwrap(); @@ -494,12 +492,11 @@ impl Client { /// # #[cfg(not(target_family = "wasm"))] /// # { /// # use typesense::Client; - /// # use reqwest::Url; /// # /// # #[tokio::main] /// # async fn main() -> Result<(), Box> { /// # let client = Client::builder() - /// # .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) + /// # .nodes(vec!["http://localhost:8108"]) /// # .api_key("xyz") /// # .build() /// # .unwrap(); @@ -519,12 +516,11 @@ impl Client { /// # #[cfg(not(target_family = "wasm"))] /// # { /// # use typesense::{Client, models}; - /// # use reqwest::Url; /// # /// # #[tokio::main] /// # async fn main() -> Result<(), Box> { /// # let client = Client::builder() - /// # .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) + /// # .nodes(vec!["http://localhost:8108"]) /// # .api_key("xyz") /// # .build() /// # .unwrap(); diff --git a/typesense/src/lib.rs b/typesense/src/lib.rs index 599551c..98a15f3 100644 --- a/typesense/src/lib.rs +++ b/typesense/src/lib.rs @@ -26,7 +26,6 @@ //! { //! use serde::{Deserialize, Serialize}; //! use typesense::{Client, Typesense, ExponentialBackoff, prelude::*}; -//! use reqwest::Url; //! use std::time::Duration; //! //! /// A struct representing a company document. @@ -45,7 +44,7 @@ //! #[tokio::main] //! async fn main() -> Result<(), Box> { //! let client = Client::builder() -//! .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) +//! .nodes(vec!["http://localhost:8108"]) //! .api_key("xyz") //! .healthcheck_interval(Duration::from_secs(60)) //! .retry_policy(ExponentialBackoff::builder().build_with_max_retries(3)) @@ -77,7 +76,6 @@ //! { //! use serde::{Deserialize, Serialize}; //! use typesense::{Client, Typesense, prelude::*}; -//! use reqwest::Url; //! use std::time::Duration; //! use wasm_bindgen_futures::spawn_local; //! @@ -97,7 +95,7 @@ //! fn main() { //! spawn_local(async { //! let client = Client::builder() -//! .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) +//! .nodes(vec!["http://localhost:8108"]) //! .api_key("xyz") //! .healthcheck_interval(Duration::from_secs(60)) //! // .retry_policy(...) <-- disabled in Wasm diff --git a/typesense/tests/client/client_test.rs b/typesense/tests/client/client_test.rs index d996d9e..c9f9e00 100644 --- a/typesense/tests/client/client_test.rs +++ b/typesense/tests/client/client_test.rs @@ -1,6 +1,5 @@ #![cfg(not(target_family = "wasm"))] -use reqwest::Url; use reqwest_retry::policies::ExponentialBackoff; use std::time::Duration; use typesense::models::CollectionResponse; @@ -42,7 +41,7 @@ async fn setup_mock_server_404(server: &MockServer, collection_name: &str) { } // Helper function to create a client configuration for tests. -fn get_client(nodes: Vec, nearest_node: Option) -> Client { +fn get_client(nodes: Vec, nearest_node: Option) -> Client { Client::builder() .nodes(nodes) .maybe_nearest_node(nearest_node) @@ -59,7 +58,7 @@ async fn test_success_on_first_node() { let server1 = MockServer::start().await; setup_mock_server_ok(&server1, "products").await; - let client = get_client(vec![Url::parse(&server1.uri()).unwrap()], None); + let client = get_client(vec![server1.uri()], None); let result = client.collection("products").retrieve().await; @@ -76,13 +75,7 @@ async fn test_failover_to_second_node() { setup_mock_server_503(&server1, "products").await; setup_mock_server_ok(&server2, "products").await; - let client = get_client( - vec![ - Url::parse(&server1.uri()).unwrap(), - Url::parse(&server2.uri()).unwrap(), - ], - None, - ); + let client = get_client(vec![server1.uri(), server2.uri()], None); let result = client.collection("products").retrieve().await; assert!(result.is_ok()); @@ -100,10 +93,7 @@ async fn test_nearest_node_is_prioritized() { setup_mock_server_ok(&nearest_server, "products").await; setup_mock_server_ok(®ular_server, "products").await; - let client = get_client( - vec![Url::parse(®ular_server.uri()).unwrap()], - Some(Url::parse(&nearest_server.uri()).unwrap()), - ); + let client = get_client(vec![regular_server.uri()], Some(nearest_server.uri())); let result = client.collection("products").retrieve().await; assert!(result.is_ok()); @@ -120,10 +110,7 @@ async fn test_failover_from_nearest_to_regular_node() { setup_mock_server_503(&nearest_server, "products").await; setup_mock_server_ok(®ular_server, "products").await; - let client = get_client( - vec![Url::parse(®ular_server.uri()).unwrap()], - Some(Url::parse(&nearest_server.uri()).unwrap()), - ); + let client = get_client(vec![regular_server.uri()], Some(nearest_server.uri())); let result = client.collection("products").retrieve().await; assert!(result.is_ok()); @@ -143,14 +130,7 @@ async fn test_round_robin_failover() { setup_mock_server_503(&server2, "products").await; setup_mock_server_ok(&server3, "products").await; - let client = get_client( - vec![ - Url::parse(&server1.uri()).unwrap(), - Url::parse(&server2.uri()).unwrap(), - Url::parse(&server3.uri()).unwrap(), - ], - None, - ); + let client = get_client(vec![server1.uri(), server2.uri(), server3.uri()], None); // First request should fail over to the third node let result = client.collection("products").retrieve().await; @@ -190,10 +170,7 @@ async fn test_health_check_and_node_recovery() { setup_mock_server_ok(&server2, "products").await; let client = Client::builder() - .nodes(vec![ - Url::parse(&server1.uri()).unwrap(), - Url::parse(&server2.uri()).unwrap(), - ]) + .nodes(vec![server1.uri(), server2.uri()]) .api_key("test-key") .healthcheck_interval(Duration::from_millis(500)) // Use a very short healthcheck interval for the test .retry_policy(ExponentialBackoff::builder().build_with_max_retries(0)) @@ -231,13 +208,7 @@ async fn test_all_nodes_fail() { setup_mock_server_503(&server1, "products").await; setup_mock_server_503(&server2, "products").await; - let client = get_client( - vec![ - Url::parse(&server1.uri()).unwrap(), - Url::parse(&server2.uri()).unwrap(), - ], - None, - ); + let client = get_client(vec![server1.uri(), server2.uri()], None); let result = client.collection("products").retrieve().await; assert!(result.is_err()); @@ -260,13 +231,7 @@ async fn test_fail_fast_on_non_retriable_error() { setup_mock_server_404(&server1, "products").await; setup_mock_server_ok(&server2, "products").await; - let client = get_client( - vec![ - Url::parse(&server1.uri()).unwrap(), - Url::parse(&server2.uri()).unwrap(), - ], - None, - ); + let client = get_client(vec![server1.uri(), server2.uri()], None); let result = client.collection("products").retrieve().await; assert!(result.is_err()); @@ -296,14 +261,7 @@ async fn test_load_balancing_with_healthy_nodes() { setup_mock_server_ok(&server3, "products").await; // 2. Setup client with the three nodes - let client = get_client( - vec![ - Url::parse(&server1.uri()).unwrap(), - Url::parse(&server2.uri()).unwrap(), - Url::parse(&server3.uri()).unwrap(), - ], - None, - ); + let client = get_client(vec![server1.uri(), server2.uri(), server3.uri()], None); // 3. Make three consecutive requests let result1 = client.collection("products").retrieve().await; diff --git a/typesense/tests/client/mod.rs b/typesense/tests/client/mod.rs index b410247..b466f03 100644 --- a/typesense/tests/client/mod.rs +++ b/typesense/tests/client/mod.rs @@ -5,7 +5,6 @@ mod documents_test; mod keys_test; mod multi_search_test; -use reqwest::Url; use reqwest_retry::policies::ExponentialBackoff; use std::time::Duration; use typesense::Client; @@ -14,7 +13,7 @@ use web_time::{SystemTime, UNIX_EPOCH}; /// Helper function to create a new client for all tests in this suite. pub fn get_client() -> Client { Client::builder() - .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) + .nodes(vec!["http://localhost:8108"]) .api_key("xyz") .healthcheck_interval(Duration::from_secs(5)) .retry_policy(ExponentialBackoff::builder().build_with_max_retries(0)) From 4726f74faeef51ffc71e5b45606f346a998f3eae Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Sun, 7 Sep 2025 22:38:15 +0700 Subject: [PATCH 19/41] don't `pub use models::*` at the root --- typesense/src/client/mod.rs | 2 +- typesense/src/client/multi_search.rs | 7 +++++-- typesense/src/lib.rs | 1 - typesense/src/traits/document.rs | 2 +- typesense/src/traits/multi_search_ext.rs | 2 +- typesense/tests/client/collections_test.rs | 5 ++--- 6 files changed, 10 insertions(+), 9 deletions(-) diff --git a/typesense/src/client/mod.rs b/typesense/src/client/mod.rs index 83e6aec..b18d3d4 100644 --- a/typesense/src/client/mod.rs +++ b/typesense/src/client/mod.rs @@ -352,7 +352,7 @@ impl Client { /// ```no_run /// # #[cfg(not(target_family = "wasm"))] /// # { - /// # use typesense::{Client, GetCollectionsParameters}; + /// # use typesense::{Client, models::GetCollectionsParameters}; /// # /// # #[tokio::main] /// # async fn main() -> Result<(), Box> { diff --git a/typesense/src/client/multi_search.rs b/typesense/src/client/multi_search.rs index 3e25fa8..1601dea 100644 --- a/typesense/src/client/multi_search.rs +++ b/typesense/src/client/multi_search.rs @@ -2,7 +2,10 @@ //! //! A `MultiSearch` instance is created via the main `client.multi_search()` method. -use crate::{Client, Error, MultiSearchBody, models::SearchResult}; +use crate::{ + Client, Error, + models::{MultiSearchBody, SearchResult}, +}; use typesense_codegen::{ apis::{ configuration::Configuration, @@ -46,7 +49,7 @@ impl<'a> MultiSearch<'a> { /// ```no_run /// # #[cfg(not(target_family = "wasm"))] /// # { - /// # use typesense::{Client, SearchResult, models, prelude::*}; + /// # use typesense::{Client, models::{self, SearchResult}, prelude::*}; /// # use reqwest::Url; /// # use serde::Deserialize; /// # diff --git a/typesense/src/lib.rs b/typesense/src/lib.rs index 98a15f3..1e603c0 100644 --- a/typesense/src/lib.rs +++ b/typesense/src/lib.rs @@ -121,7 +121,6 @@ pub mod prelude; pub use client::{Client, ExponentialBackoff}; pub use error::*; -pub use models::*; #[cfg(feature = "typesense_derive")] #[doc(hidden)] diff --git a/typesense/src/traits/document.rs b/typesense/src/traits/document.rs index e26a53a..adf87e7 100644 --- a/typesense/src/traits/document.rs +++ b/typesense/src/traits/document.rs @@ -3,7 +3,7 @@ //! In Typesense, documents are each one of the JSON elements that are stored in the collections. //! A document to be indexed in a given collection must conform to the schema of the collection. //! -use crate::collection_schema::CollectionSchema; +use crate::models::CollectionSchema; use serde::{Serialize, de::DeserializeOwned}; /// Trait that should implement every struct that wants to be represented as a Typesense diff --git a/typesense/src/traits/multi_search_ext.rs b/typesense/src/traits/multi_search_ext.rs index bdbc8e8..5be2bd5 100644 --- a/typesense/src/traits/multi_search_ext.rs +++ b/typesense/src/traits/multi_search_ext.rs @@ -2,7 +2,7 @@ use crate::models::{MultiSearchResult, MultiSearchResultItem, SearchGroupedHit, use serde::de::DeserializeOwned; use serde_json::Value; -use crate::{MultiSearchParseError, SearchResult}; +use crate::{MultiSearchParseError, models::SearchResult}; /// An extension trait for `MultiSearchResult` to provide typed parsing. pub trait MultiSearchResultExt { diff --git a/typesense/tests/client/collections_test.rs b/typesense/tests/client/collections_test.rs index eab99a9..ebfb919 100644 --- a/typesense/tests/client/collections_test.rs +++ b/typesense/tests/client/collections_test.rs @@ -1,6 +1,5 @@ -use typesense::{ - GetCollectionsParameters, - models::{CollectionSchema, CollectionUpdateSchema, Field}, +use typesense::models::{ + CollectionSchema, CollectionUpdateSchema, Field, GetCollectionsParameters, }; use super::{get_client, new_id}; From a1f0a486ecfd05d6eacbecd46cf870b8ee9ba32d Mon Sep 17 00:00:00 2001 From: RoDmitry Date: Thu, 11 Sep 2025 16:00:48 +0000 Subject: [PATCH 20/41] Optimize + fmt --- .github/workflows/lint.yml | 4 +- .../reqwest/api.mustache | 12 +- rustfmt.toml | 1 + typesense/Cargo.toml | 10 +- typesense/src/client/collection/document.rs | 29 +- typesense/src/client/collection/documents.rs | 55 +- typesense/src/client/collection/mod.rs | 35 +- typesense/src/client/collections.rs | 15 +- typesense/src/client/key.rs | 24 +- typesense/src/client/keys.rs | 18 +- typesense/src/client/mod.rs | 233 ++++--- typesense/src/client/multi_search.rs | 24 +- typesense/tests/client/client_test.rs | 32 +- typesense/tests/derive/collection.rs | 3 +- typesense_codegen/src/apis/analytics_api.rs | 326 +++++++--- typesense_codegen/src/apis/collections_api.rs | 347 +++++++--- .../src/apis/conversations_api.rs | 196 ++++-- typesense_codegen/src/apis/curation_api.rs | 130 ++-- typesense_codegen/src/apis/debug_api.rs | 39 +- typesense_codegen/src/apis/documents_api.rs | 613 +++++++++++++----- typesense_codegen/src/apis/health_api.rs | 39 +- typesense_codegen/src/apis/keys_api.rs | 155 +++-- typesense_codegen/src/apis/mod.rs | 3 +- .../src/apis/nl_search_models_api.rs | 193 ++++-- typesense_codegen/src/apis/operations_api.rs | 268 +++++--- typesense_codegen/src/apis/override_api.rs | 49 +- typesense_codegen/src/apis/presets_api.rs | 157 +++-- typesense_codegen/src/apis/stemming_api.rs | 113 +++- typesense_codegen/src/apis/stopwords_api.rs | 157 +++-- typesense_codegen/src/apis/synonyms_api.rs | 157 +++-- .../src/models/analytics_event.rs | 9 +- .../models/analytics_event_create_response.rs | 9 +- .../src/models/analytics_event_data.rs | 5 +- .../src/models/analytics_events_response.rs | 9 +- .../analytics_events_response_events_inner.rs | 5 +- .../src/models/analytics_rule.rs | 12 +- .../src/models/analytics_rule_create.rs | 12 +- .../models/analytics_rule_create_params.rs | 15 +- .../src/models/analytics_rule_update.rs | 5 +- .../src/models/analytics_status.rs | 20 +- typesense_codegen/src/models/api_key.rs | 5 +- .../src/models/api_key_delete_response.rs | 9 +- .../src/models/api_key_schema.rs | 9 +- .../src/models/api_keys_response.rs | 9 +- typesense_codegen/src/models/api_response.rs | 9 +- .../src/models/api_stats_response.rs | 45 +- .../src/models/collection_alias.rs | 5 +- .../src/models/collection_alias_schema.rs | 9 +- .../src/models/collection_aliases_response.rs | 9 +- .../src/models/collection_response.rs | 26 +- .../src/models/collection_schema.rs | 21 +- .../src/models/collection_update_schema.rs | 7 +- .../conversation_model_create_schema.rs | 13 +- .../src/models/conversation_model_schema.rs | 14 +- .../conversation_model_update_schema.rs | 9 +- .../create_analytics_rule_200_response.rs | 5 +- ...nalytics_rule_200_response_one_of_inner.rs | 12 +- ...s_rule_200_response_one_of_inner_any_of.rs | 9 +- .../models/create_analytics_rule_request.rs | 5 +- .../src/models/debug_200_response.rs | 9 +- .../models/delete_documents_200_response.rs | 9 +- .../src/models/delete_documents_parameters.rs | 5 +- .../delete_stopwords_set_200_response.rs | 9 +- typesense_codegen/src/models/dirty_values.rs | 6 +- .../src/models/drop_tokens_mode.rs | 8 +- .../src/models/export_documents_parameters.rs | 5 +- typesense_codegen/src/models/facet_counts.rs | 5 +- .../src/models/facet_counts_counts_inner.rs | 5 +- .../src/models/facet_counts_stats.rs | 5 +- typesense_codegen/src/models/field.rs | 19 +- typesense_codegen/src/models/field_embed.rs | 5 +- .../src/models/field_embed_model_config.rs | 5 +- .../src/models/get_collections_parameters.rs | 7 +- typesense_codegen/src/models/health_status.rs | 9 +- .../src/models/import_documents_parameters.rs | 10 +- typesense_codegen/src/models/index_action.rs | 6 +- ...list_stemming_dictionaries_200_response.rs | 9 +- .../multi_search_collection_parameters.rs | 188 ++++-- .../src/models/multi_search_parameters.rs | 178 +++-- .../src/models/multi_search_result.rs | 5 +- .../src/models/multi_search_result_item.rs | 10 +- .../models/multi_search_searches_parameter.rs | 7 +- .../src/models/nl_search_model_base.rs | 5 +- .../models/nl_search_model_create_schema.rs | 5 +- .../models/nl_search_model_delete_schema.rs | 9 +- .../src/models/nl_search_model_schema.rs | 5 +- .../src/models/preset_delete_schema.rs | 9 +- typesense_codegen/src/models/preset_schema.rs | 5 +- .../src/models/preset_upsert_schema.rs | 5 +- .../src/models/preset_upsert_schema_value.rs | 3 +- .../src/models/presets_retrieve_schema.rs | 9 +- .../src/models/schema_change_status.rs | 5 +- .../src/models/search_grouped_hit.rs | 8 +- .../src/models/search_highlight.rs | 5 +- .../src/models/search_override.rs | 33 +- .../models/search_override_delete_response.rs | 9 +- .../src/models/search_override_exclude.rs | 9 +- .../src/models/search_override_include.rs | 10 +- .../src/models/search_override_rule.rs | 11 +- .../src/models/search_override_schema.rs | 33 +- .../src/models/search_overrides_response.rs | 9 +- .../src/models/search_parameters.rs | 190 ++++-- .../src/models/search_request_params.rs | 5 +- .../search_request_params_voice_query.rs | 5 +- typesense_codegen/src/models/search_result.rs | 10 +- .../src/models/search_result_conversation.rs | 10 +- .../src/models/search_result_hit.rs | 10 +- .../search_result_hit_hybrid_search_info.rs | 5 +- .../search_result_hit_text_match_info.rs | 5 +- .../src/models/search_synonym.rs | 5 +- .../models/search_synonym_delete_response.rs | 9 +- .../src/models/search_synonym_schema.rs | 5 +- .../src/models/search_synonyms_response.rs | 9 +- .../src/models/stemming_dictionary.rs | 10 +- .../models/stemming_dictionary_words_inner.rs | 10 +- .../models/stopwords_set_retrieve_schema.rs | 5 +- .../src/models/stopwords_set_schema.rs | 5 +- .../src/models/stopwords_set_upsert_schema.rs | 5 +- .../stopwords_sets_retrieve_all_schema.rs | 9 +- .../src/models/success_status.rs | 9 +- .../src/models/synonym_item_schema.rs | 5 +- .../src/models/synonym_set_create_schema.rs | 9 +- .../src/models/synonym_set_delete_schema.rs | 9 +- .../src/models/synonym_set_schema.rs | 10 +- .../models/synonym_sets_retrieve_schema.rs | 9 +- .../models/toggle_slow_request_log_request.rs | 5 +- .../models/update_documents_200_response.rs | 9 +- .../src/models/update_documents_parameters.rs | 9 +- .../voice_query_model_collection_config.rs | 13 +- xtask/src/main.rs | 4 +- 130 files changed, 3064 insertions(+), 1818 deletions(-) create mode 100644 rustfmt.toml diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index b631420..f1c26dd 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -35,11 +35,11 @@ jobs: profile: minimal default: true - run: rustup component add rustfmt - - name: Check formt + - name: Check format uses: actions-rs/cargo@v1 with: command: fmt - args: --package typesense --package typesense_derive --package xtask -- --check + args: -- --check - run: rustup component add clippy - name: Run clippy uses: actions-rs/cargo@v1 diff --git a/openapi-generator-template/reqwest/api.mustache b/openapi-generator-template/reqwest/api.mustache index b1feb8d..e64b087 100644 --- a/openapi-generator-template/reqwest/api.mustache +++ b/openapi-generator-template/reqwest/api.mustache @@ -239,10 +239,10 @@ pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}{{{vendorExtensi {{#isApiKey}} {{#isKeyInQuery}} if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.query(&[("{{{keyParamName}}}", value)]); } @@ -310,10 +310,10 @@ pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}{{{vendorExtensi {{#isApiKey}} {{#isKeyInHeader}} if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("{{{keyParamName}}}", value); }; diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..c3c8c37 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1 @@ +imports_granularity = "Crate" diff --git a/typesense/Cargo.toml b/typesense/Cargo.toml index f64cc64..a408579 100644 --- a/typesense/Cargo.toml +++ b/typesense/Cargo.toml @@ -9,7 +9,6 @@ description = "Client for typesense" [features] default = ["derive"] -tokio_test = [] # Provide derive(Typesense) macro. derive = ["typesense_derive"] @@ -18,17 +17,18 @@ derive = ["typesense_derive"] crate-type = ["cdylib", "rlib"] [dependencies] +typesense_codegen = { workspace = true } +typesense_derive = { workspace = true, optional = true } anyhow = "1.0" base64 = "0.22" +bon = "3.7.0" +debug_unsafe = "0.1" hmac = "0.12" +reqwest-retry = "0.7.0" serde = { version = "1", features = ["derive"] } serde_json = "1.0" sha2 = "0.10" -typesense_derive = { workspace = true, optional = true } -typesense_codegen = { workspace = true } thiserror = "1.0" -bon = "3.7.0" -reqwest-retry = "0.7.0" web-time = "=1.1.0" # required for wasm32 target # native-only dependencies diff --git a/typesense/src/client/collection/document.rs b/typesense/src/client/collection/document.rs index 7e5ae12..5f97a4b 100644 --- a/typesense/src/client/collection/document.rs +++ b/typesense/src/client/collection/document.rs @@ -4,9 +4,9 @@ //! via a parent `Collection` struct, for example: //! `client.collection::("books").document("123")` -use crate::{Client, Error}; +use crate::{Client, Error, execute_wrapper}; use serde::{Serialize, de::DeserializeOwned}; -use typesense_codegen::apis::{configuration, documents_api}; +use typesense_codegen::apis::documents_api; /// Provides methods for interacting with a single document within a specific Typesense collection. /// @@ -28,6 +28,7 @@ where T: DeserializeOwned + Serialize + Send + Sync, { /// Creates a new `Document` instance for a specific document ID. + #[inline] pub(super) fn new(client: &'a Client, collection_name: String, document_id: String) -> Self { Self { client, @@ -47,13 +48,7 @@ where document_id: self.document_id.to_owned(), }; - let result_value = self - .client - .execute(|config: configuration::Configuration| { - let params_for_move = params.clone(); - async move { documents_api::get_document(&config, params_for_move).await } - }) - .await?; + let result_value = execute_wrapper!(self, documents_api::get_document, params)?; // Deserialize the raw JSON value into the user's type T. serde_json::from_value(result_value).map_err(Error::from) @@ -113,13 +108,7 @@ where dirty_values: params.unwrap_or_default().dirty_values, }; - let result_value = self - .client - .execute(|config: configuration::Configuration| { - let params_for_move = params.clone(); - async move { documents_api::update_document(&config, params_for_move).await } - }) - .await?; + let result_value = execute_wrapper!(self, documents_api::update_document, params)?; // Deserialize the raw JSON value of the updated document into T. serde_json::from_value(result_value).map_err(Error::from) @@ -136,13 +125,7 @@ where document_id: self.document_id.to_owned(), }; - let result_value = self - .client - .execute(|config: configuration::Configuration| { - let params_for_move = params.clone(); - async move { documents_api::delete_document(&config, params_for_move).await } - }) - .await?; + let result_value = execute_wrapper!(self, documents_api::delete_document, params)?; // Deserialize the raw JSON value of the deleted document into T. serde_json::from_value(result_value).map_err(Error::from) diff --git a/typesense/src/client/collection/documents.rs b/typesense/src/client/collection/documents.rs index 3030954..908519b 100644 --- a/typesense/src/client/collection/documents.rs +++ b/typesense/src/client/collection/documents.rs @@ -4,12 +4,13 @@ //! via the main `client.collection("collection_name").documents()` method or //! `client.collection_of::("...").documents()`. -use crate::models::DocumentIndexParameters; -use crate::models::SearchResult; -use crate::{Client, Error}; +use crate::{ + Client, Error, execute_wrapper, + models::{DocumentIndexParameters, SearchResult}, +}; use serde::{Serialize, de::DeserializeOwned}; use typesense_codegen::{ - apis::{configuration, documents_api}, + apis::documents_api, models::{ self as raw_models, DeleteDocumentsParameters, ExportDocumentsParameters, ImportDocumentsParameters, UpdateDocumentsParameters, @@ -34,6 +35,7 @@ where T: DeserializeOwned + Serialize + Send + Sync, { /// Creates a new `Documents` instance. + #[inline] pub(super) fn new(client: &'a Client, collection_name: String) -> Self { Self { client, @@ -58,12 +60,7 @@ where action: Some(action.to_owned()), dirty_values: params.unwrap_or_default().dirty_values, // Or expose this as an argument if needed }; - self.client - .execute(|config: configuration::Configuration| { - let params_for_move = params.clone(); - async move { documents_api::index_document(&config, params_for_move).await } - }) - .await + execute_wrapper!(self, documents_api::index_document, params) } /// Creates a new document in the collection. @@ -128,13 +125,7 @@ where return_doc: params.return_doc, return_id: params.return_id, }; - - self.client - .execute(|config: configuration::Configuration| { - let params_for_move = params.clone(); - async move { documents_api::import_documents(&config, params_for_move).await } - }) - .await + execute_wrapper!(self, documents_api::import_documents, params) } /// Exports all documents in a collection in JSONL format. @@ -151,13 +142,7 @@ where filter_by: params.filter_by, include_fields: params.include_fields, }; - - self.client - .execute(|config: configuration::Configuration| { - let params_for_move = params.clone(); - async move { documents_api::export_documents(&config, params_for_move).await } - }) - .await + execute_wrapper!(self, documents_api::export_documents, params) } /// Deletes a batch of documents matching a specific filter condition. @@ -176,12 +161,7 @@ where ignore_not_found: params.ignore_not_found, truncate: params.truncate, }; - self.client - .execute(|config: configuration::Configuration| { - let params_for_move = params.clone(); - async move { documents_api::delete_documents(&config, params_for_move).await } - }) - .await + execute_wrapper!(self, documents_api::delete_documents, params) } /// Updates a batch of documents matching a specific filter condition. @@ -200,12 +180,7 @@ where filter_by: params.filter_by, body: serde_json::to_value(document)?, }; - self.client - .execute(|config: configuration::Configuration| { - let params_for_move = params.clone(); - async move { documents_api::update_documents(&config, params_for_move).await } - }) - .await + execute_wrapper!(self, documents_api::update_documents, params) } /// Searches for documents in the collection that match the given criteria. @@ -293,12 +268,6 @@ where enable_analytics: params.enable_analytics, synonym_sets: params.synonym_sets, }; - - self.client - .execute(|config: configuration::Configuration| { - let params_for_move = search_params.clone(); - async move { documents_api::search_collection(&config, params_for_move).await } - }) - .await + execute_wrapper!(self, documents_api::search_collection, search_params) } } diff --git a/typesense/src/client/collection/mod.rs b/typesense/src/client/collection/mod.rs index d4dfb7d..3d2ca26 100644 --- a/typesense/src/client/collection/mod.rs +++ b/typesense/src/client/collection/mod.rs @@ -4,13 +4,10 @@ mod document; mod documents; -use crate::{Client, Error}; +use crate::{Client, Error, execute_wrapper}; use serde::{Serialize, de::DeserializeOwned}; -use typesense_codegen::{ - apis::{collections_api, configuration}, - models, -}; +use typesense_codegen::{apis::collections_api, models}; /// Provides methods for interacting with a Typesense collection. /// @@ -29,6 +26,7 @@ where T: DeserializeOwned + Serialize + Send + Sync, { /// Creates a new `Collection` instance. + #[inline] pub(super) fn new(client: &'a Client, collection_name: String) -> Self { Self { client, @@ -38,11 +36,13 @@ where } /// Provides access to the document-related API endpoints for a specific collection. + #[inline] pub fn documents(&'a self) -> documents::Documents<'a, T> { documents::Documents::new(self.client, self.collection_name.to_owned()) } /// Provides access to the API endpoints for a single document within a Typesense collection. + #[inline] pub fn document(&'a self, document_id: impl Into) -> document::Document<'a, T> { document::Document::new( self.client, @@ -52,40 +52,32 @@ where } /// Retrieves the details of a collection, given its name. + #[inline] pub async fn retrieve( &self, ) -> Result> { let params = collections_api::GetCollectionParams { collection_name: self.collection_name.to_owned(), }; - - self.client - .execute(|config: configuration::Configuration| { - let params_for_move = params.clone(); - async move { collections_api::get_collection(&config, params_for_move).await } - }) - .await + execute_wrapper!(self, collections_api::get_collection, params) } /// Permanently drops a collection. + #[inline] pub async fn delete( &self, ) -> Result> { let params = collections_api::DeleteCollectionParams { collection_name: self.collection_name.to_owned(), }; - self.client - .execute(|config: configuration::Configuration| { - let params_for_move = params.clone(); - async move { collections_api::delete_collection(&config, params_for_move).await } - }) - .await + execute_wrapper!(self, collections_api::delete_collection, params) } /// Updates a collection's schema to modify the fields and their types. /// /// # Arguments /// * `update_schema` - A `CollectionUpdateSchema` object describing the fields to update. + #[inline] pub async fn update( &self, update_schema: models::CollectionUpdateSchema, @@ -94,11 +86,6 @@ where collection_name: self.collection_name.to_owned(), collection_update_schema: update_schema, }; - self.client - .execute(|config: configuration::Configuration| { - let params_for_move = params.clone(); - async move { collections_api::update_collection(&config, params_for_move).await } - }) - .await + execute_wrapper!(self, collections_api::update_collection, params) } } diff --git a/typesense/src/client/collections.rs b/typesense/src/client/collections.rs index dd9db45..7273c7d 100644 --- a/typesense/src/client/collections.rs +++ b/typesense/src/client/collections.rs @@ -2,7 +2,7 @@ //! //! A `Collections` instance is created via the main `client.collections()` method. -use crate::{Client, Error}; +use crate::{Client, Error, execute_wrapper}; use typesense_codegen::{ apis::{ collections_api::{self, GetCollectionsParams}, @@ -20,6 +20,7 @@ pub struct Collections<'a> { impl<'a> Collections<'a> { /// Creates a new `Collection` instance + #[inline] pub(super) fn new(client: &'a Client) -> Self { Self { client } } @@ -35,13 +36,7 @@ impl<'a> Collections<'a> { let params = collections_api::CreateCollectionParams { collection_schema: schema, }; - - self.client - .execute(|config: configuration::Configuration| { - let params_for_move = params.clone(); - async move { collections_api::create_collection(&config, params_for_move).await } - }) - .await + execute_wrapper!(self, collections_api::create_collection, params) } /// List the existing Typesense collections. @@ -50,13 +45,13 @@ impl<'a> Collections<'a> { params: GetCollectionsParameters, ) -> Result, Error> { self.client - .execute(|config: configuration::Configuration| { + .execute(|config: &configuration::Configuration| { let params_for_move = GetCollectionsParams { exclude_fields: params.exclude_fields.clone(), limit: params.limit, offset: params.offset, }; - async move { collections_api::get_collections(&config, params_for_move).await } + collections_api::get_collections(config, params_for_move) }) .await } diff --git a/typesense/src/client/key.rs b/typesense/src/client/key.rs index 5fe8e7d..3af249f 100644 --- a/typesense/src/client/key.rs +++ b/typesense/src/client/key.rs @@ -2,11 +2,8 @@ //! //! A `Key` instance is created via the `client.key(key_id)` method. -use crate::{Client, Error}; -use typesense_codegen::{ - apis::{configuration, keys_api}, - models, -}; +use crate::{Client, Error, execute_wrapper}; +use typesense_codegen::{apis::keys_api, models}; /// Provides methods for managing a specific Typesense API key. /// @@ -18,6 +15,7 @@ pub struct Key<'a> { impl<'a> Key<'a> { /// Creates a new `Key` instance for a specific key ID. + #[inline] pub(super) fn new(client: &'a Client, key_id: i64) -> Self { Self { client, key_id } } @@ -26,30 +24,22 @@ impl<'a> Key<'a> { /// /// For security reasons, this endpoint only returns the key prefix and metadata, /// not the full key value. + #[inline] pub async fn retrieve(&self) -> Result> { let params = keys_api::GetKeyParams { key_id: self.key_id, }; - self.client - .execute(|config: configuration::Configuration| { - let params_for_move = params.clone(); - async move { keys_api::get_key(&config, params_for_move).await } - }) - .await + execute_wrapper!(self, keys_api::get_key, params) } /// Deletes this specific API key. + #[inline] pub async fn delete( &self, ) -> Result> { let params = keys_api::DeleteKeyParams { key_id: self.key_id, }; - self.client - .execute(|config: configuration::Configuration| { - let params_for_move = params.clone(); - async move { keys_api::delete_key(&config, params_for_move).await } - }) - .await + execute_wrapper!(self, keys_api::delete_key, params) } } diff --git a/typesense/src/client/keys.rs b/typesense/src/client/keys.rs index ad0896d..ef4f57f 100644 --- a/typesense/src/client/keys.rs +++ b/typesense/src/client/keys.rs @@ -3,13 +3,13 @@ //! An `Keys` instance is created via the `client.keys()` method. use crate::{ - Client, Error, + Client, Error, execute_wrapper, models::{self, ScopedKeyParameters}, }; use base64::{Engine, engine::general_purpose::STANDARD as Base64Engine}; use hmac::{Hmac, Mac}; use sha2::Sha256; -use typesense_codegen::apis::{configuration, keys_api}; +use typesense_codegen::apis::keys_api; /// Provides methods for managing a collection of Typesense API keys. /// @@ -20,6 +20,7 @@ pub struct Keys<'a> { impl<'a> Keys<'a> { /// Creates a new `Keys` instance. + #[inline] pub(super) fn new(client: &'a Client) -> Self { Self { client } } @@ -38,21 +39,12 @@ impl<'a> Keys<'a> { let params = keys_api::CreateKeyParams { api_key_schema: Some(schema), }; - self.client - .execute(|config: configuration::Configuration| { - let params_for_move = params.clone(); - async move { keys_api::create_key(&config, params_for_move).await } - }) - .await + execute_wrapper!(self, keys_api::create_key, params) } /// Lists all API keys and their metadata. pub async fn retrieve(&self) -> Result> { - self.client - .execute(|config: configuration::Configuration| async move { - keys_api::get_keys(&config).await - }) - .await + execute_wrapper!(self, keys_api::get_keys) } /// Generate a scoped search API key that can have embedded search parameters in them. diff --git a/typesense/src/client/mod.rs b/typesense/src/client/mod.rs index b18d3d4..7a70e97 100644 --- a/typesense/src/client/mod.rs +++ b/typesense/src/client/mod.rs @@ -112,35 +112,59 @@ mod key; mod keys; mod multi_search; +use crate::Error; use collection::Collection; use collections::Collections; use key::Key; use keys::Keys; -use serde::Serialize; -use serde::de::DeserializeOwned; +use debug_unsafe::{option::OptionUnwrapper, slice::SliceGetter}; +use serde::{Serialize, de::DeserializeOwned}; -use crate::Error; #[cfg(not(target_arch = "wasm32"))] use reqwest_middleware::ClientBuilder as ReqwestMiddlewareClientBuilder; #[cfg(not(target_arch = "wasm32"))] use reqwest_retry::RetryTransientMiddleware; pub use reqwest_retry::policies::ExponentialBackoff; -use std::future::Future; -use std::sync::{ - Arc, Mutex, - atomic::{AtomicUsize, Ordering}, +use std::{ + future::Future, + sync::{ + RwLock, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }, }; use typesense_codegen::apis::{self, configuration}; use web_time::{Duration, Instant}; +/// Wraps api call in `client::execute()` +#[macro_export] +macro_rules! execute_wrapper { + ($self:ident, $call:expr) => { + $self + .client + .execute(|config: &typesense_codegen::apis::configuration::Configuration| $call(config)) + .await + }; + ($self:ident, $call:expr, $params:expr) => { + $self + .client + .execute( + |config: &typesense_codegen::apis::configuration::Configuration| { + let params_cloned = $params.clone(); + $call(config, params_cloned) + }, + ) + .await + }; +} + // This is an internal detail to track the state of each node. #[derive(Debug)] struct Node { - url: String, - is_healthy: bool, - last_access_timestamp: Instant, + config: configuration::Configuration, + is_healthy: AtomicBool, + last_accessed: RwLock, } /// The main entry point for all interactions with the Typesense API. /// @@ -148,16 +172,10 @@ struct Node { /// API resource groups (namespaces) like `collections`, `documents`, and `operations`. #[derive(Debug)] pub struct Client { - nodes: Vec>>, - nearest_node: Option>>, - api_key: String, + nodes: Vec, + is_nearest_node_set: bool, healthcheck_interval: Duration, current_node_index: AtomicUsize, - - #[cfg(not(target_arch = "wasm32"))] - retry_policy: ExponentialBackoff, - #[cfg(not(target_arch = "wasm32"))] - connection_timeout: Duration, } #[bon::bon] @@ -193,146 +211,117 @@ impl Client { /// The timeout for each individual network request. connection_timeout: Duration, ) -> Result { - if nodes.is_empty() && nearest_node.is_none() { - return Err("Configuration must include at least one node or a nearest_node."); - } + let is_nearest_node_set = nearest_node.is_some(); - let node_list = nodes + let nodes: Vec<_> = nodes .into_iter() - .map(|url| { - Arc::new(Mutex::new(Node { - url, - is_healthy: true, - last_access_timestamp: Instant::now(), - })) + .chain(nearest_node) + .map(|mut url| { + #[cfg(target_arch = "wasm32")] + let http_client = reqwest::Client::builder() + .build() + .expect("Failed to build reqwest client"); + + #[cfg(not(target_arch = "wasm32"))] + let http_client = ReqwestMiddlewareClientBuilder::new( + reqwest::Client::builder() + .timeout(connection_timeout) + .build() + .expect("Failed to build reqwest client"), + ) + .with(RetryTransientMiddleware::new_with_policy(retry_policy)) + .build(); + + if url.len() > 1 && url.chars().last().unwrap_safe_unchecked() == '/' { + url.pop(); + } + + let config = configuration::Configuration { + base_path: url, + api_key: Some(configuration::ApiKey { + prefix: None, + key: api_key.clone(), + }), + client: http_client, + ..Default::default() + }; + + Node { + config, + is_healthy: AtomicBool::new(true), + last_accessed: RwLock::new(Instant::now()), + } }) .collect(); - let nearest_node_arc = nearest_node.map(|url| { - Arc::new(Mutex::new(Node { - url, - is_healthy: true, - last_access_timestamp: Instant::now(), - })) - }); + if nodes.is_empty() { + return Err("Configuration must include at least one node or a nearest_node."); + } Ok(Self { - nodes: node_list, - nearest_node: nearest_node_arc, - api_key, + nodes, + is_nearest_node_set, healthcheck_interval, current_node_index: AtomicUsize::new(0), - - #[cfg(not(target_arch = "wasm32"))] - retry_policy, - #[cfg(not(target_arch = "wasm32"))] - connection_timeout, }) } /// Selects the next node to use for a request based on health and priority. - fn get_next_node(&self) -> Arc> { - // 1. Always try the nearest_node first if it exists. - if let Some(nearest_node_arc) = &self.nearest_node { - let node = nearest_node_arc.lock().unwrap(); - let is_due_for_check = Instant::now().duration_since(node.last_access_timestamp) - >= self.healthcheck_interval; - - if node.is_healthy || is_due_for_check { - return Arc::clone(nearest_node_arc); - } - } - - // 2. Fallback to the main list of nodes if no healthy nearest_node is available. - if self.nodes.is_empty() { - // This can only happen if ONLY a nearest_node was provided and it's unhealthy. - // We must return it to give it a chance to recover. - return Arc::clone(self.nearest_node.as_ref().unwrap()); - } - - // 3. Loop through all nodes once to find a healthy one. + fn get_next_node(&self) -> &Node { + let (nodes_len, mut index) = if self.is_nearest_node_set { + let last_node_index = self.nodes.len() - 1; + (last_node_index, last_node_index) + } else { + ( + self.nodes.len(), + self.current_node_index.fetch_add(1, Ordering::Relaxed) % self.nodes.len(), + ) + }; for _ in 0..self.nodes.len() { - let index = self.current_node_index.fetch_add(1, Ordering::Relaxed) % self.nodes.len(); - let node_arc = &self.nodes[index]; - let node = node_arc.lock().unwrap(); - let is_due_for_check = Instant::now().duration_since(node.last_access_timestamp) - >= self.healthcheck_interval; + let node = self.nodes.get_safe_unchecked(index); - if node.is_healthy || is_due_for_check { - return Arc::clone(node_arc); + if node.is_healthy.load(Ordering::Relaxed) + || node.last_accessed.read().unwrap().elapsed() >= self.healthcheck_interval + { + return node; } + index = self.current_node_index.fetch_add(1, Ordering::Relaxed) % nodes_len; } - // 4. If all nodes are unhealthy and not due for a check, just pick the next one in the round-robin. + // If all nodes are unhealthy and not due for a check, just pick the next one in the round-robin. // This gives it a chance to prove it has recovered. let index = self.current_node_index.load(Ordering::Relaxed) % self.nodes.len(); - Arc::clone(&self.nodes[index]) + self.nodes.get_safe_unchecked(index) } /// Sets the health status of a given node after a request attempt. - fn set_node_health(&self, node_arc: &Arc>, is_healthy: bool) { - let mut node = node_arc.lock().unwrap(); - node.is_healthy = is_healthy; - node.last_access_timestamp = Instant::now(); + #[inline] + fn set_node_health(&self, node: &Node, is_healthy: bool) { + *node.last_accessed.write().unwrap() = Instant::now(); + node.is_healthy.store(is_healthy, Ordering::Relaxed); } /// The core execution method that handles multi-node failover and retries. /// This internal method is called by all public API methods. - pub(super) async fn execute(&self, api_call: F) -> Result> + pub(super) async fn execute(&'a self, api_call: F) -> Result> where - F: Fn(configuration::Configuration) -> Fut, + F: Fn(&'a configuration::Configuration) -> Fut, Fut: Future>>, E: std::fmt::Debug + 'static, apis::Error: std::error::Error + 'static, { let mut last_api_error: Option> = None; - let num_nodes_to_try = self.nodes.len() + self.nearest_node.is_some() as usize; - // Loop up to the total number of available nodes. - for _ in 0..num_nodes_to_try { - let node_arc = self.get_next_node(); - let node_url = { - let node = node_arc.lock().unwrap(); - node.url.clone() - }; - - #[cfg(target_arch = "wasm32")] - let http_client = reqwest::Client::builder() - .build() - .expect("Failed to build reqwest client"); - - #[cfg(not(target_arch = "wasm32"))] - let http_client = ReqwestMiddlewareClientBuilder::new( - reqwest::Client::builder() - .timeout(self.connection_timeout) - .build() - .expect("Failed to build reqwest client"), - ) - .with(RetryTransientMiddleware::new_with_policy(self.retry_policy)) - .build(); - - // Create a temporary config for this attempt. - let gen_config = configuration::Configuration { - base_path: node_url - .strip_suffix('/') - .unwrap_or(node_url.as_str()) - .to_string(), - api_key: Some(configuration::ApiKey { - prefix: None, - key: self.api_key.clone(), - }), - client: http_client, - ..Default::default() - }; - - match api_call(gen_config).await { + for _ in 0..self.nodes.len() { + let node = self.get_next_node(); + match api_call(&node.config).await { Ok(response) => { - self.set_node_health(&node_arc, true); + self.set_node_health(node, true); return Ok(response); } Err(e) => { if is_retriable(&e) { - self.set_node_health(&node_arc, false); + self.set_node_health(node, false); last_api_error = Some(e); } else { return Err(e.into()); @@ -366,6 +355,7 @@ impl Client { /// # } /// # } /// ``` + #[inline] pub fn collections(&self) -> Collections<'_> { Collections::new(self) } @@ -410,6 +400,7 @@ impl Client { /// # } /// # } /// ``` + #[inline] pub fn collection_of<'a, T>(&'a self, collection_name: impl Into) -> Collection<'a, T> where T: DeserializeOwned + Serialize + Send + Sync, @@ -445,6 +436,7 @@ impl Client { /// # } /// # } /// ``` + #[inline] pub fn collection<'a>( &'a self, collection_name: impl Into, @@ -478,6 +470,7 @@ impl Client { /// # } /// # } /// ``` + #[inline] pub fn keys(&self) -> Keys<'_> { Keys::new(self) } @@ -505,6 +498,7 @@ impl Client { /// # } /// # } /// ``` + #[inline] pub fn key(&self, key_id: i64) -> Key<'_> { Key::new(self, key_id) } @@ -539,6 +533,7 @@ impl Client { /// # } /// # } /// ``` + #[inline] pub fn multi_search(&self) -> multi_search::MultiSearch<'_> { multi_search::MultiSearch::new(self) } diff --git a/typesense/src/client/multi_search.rs b/typesense/src/client/multi_search.rs index 1601dea..1df379b 100644 --- a/typesense/src/client/multi_search.rs +++ b/typesense/src/client/multi_search.rs @@ -3,14 +3,11 @@ //! A `MultiSearch` instance is created via the main `client.multi_search()` method. use crate::{ - Client, Error, + Client, Error, execute_wrapper, models::{MultiSearchBody, SearchResult}, }; use typesense_codegen::{ - apis::{ - configuration::Configuration, - documents_api::{self, MultiSearchParams}, - }, + apis::documents_api::{self, MultiSearchParams}, models as raw_models, }; @@ -23,6 +20,7 @@ pub struct MultiSearch<'a> { impl<'a> MultiSearch<'a> { /// Creates a new `MultiSearch` instance. + #[inline] pub(super) fn new(client: &'a Client) -> Self { Self { client } } @@ -126,13 +124,7 @@ impl<'a> MultiSearch<'a> { }; let multi_search_params = build_multi_search_params(request_body, common_search_params); - let raw_result = self - .client - .execute(|config: Configuration| { - let params_for_move: MultiSearchParams = multi_search_params.clone(); - async move { documents_api::multi_search(&config, params_for_move).await } - }) - .await; + let raw_result = execute_wrapper!(self, documents_api::multi_search, multi_search_params); // Now, handle the raw result and parse it into the strong type. match raw_result { @@ -271,13 +263,7 @@ impl<'a> MultiSearch<'a> { let multi_search_params = build_multi_search_params(request_body, common_search_params); // Execute the request to get the raw JSON value - let raw_result = self - .client - .execute(|config: Configuration| { - let params_for_move = multi_search_params.clone(); - async move { documents_api::multi_search(&config, params_for_move).await } - }) - .await; + let raw_result = execute_wrapper!(self, documents_api::multi_search, multi_search_params); match raw_result { Ok(json_value) => serde_json::from_value(json_value).map_err(Error::from), diff --git a/typesense/tests/client/client_test.rs b/typesense/tests/client/client_test.rs index c9f9e00..d28d9ed 100644 --- a/typesense/tests/client/client_test.rs +++ b/typesense/tests/client/client_test.rs @@ -2,10 +2,11 @@ use reqwest_retry::policies::ExponentialBackoff; use std::time::Duration; -use typesense::models::CollectionResponse; -use typesense::*; -use wiremock::matchers::{header, method, path}; -use wiremock::{Mock, MockServer, ResponseTemplate}; +use typesense::{models::CollectionResponse, *}; +use wiremock::{ + Mock, MockServer, ResponseTemplate, + matchers::{header, method, path}, +}; // Helper to create a mock Typesense server for a successful collection retrieval. async fn setup_mock_server_ok(server: &MockServer, collection_name: &str) { @@ -133,8 +134,8 @@ async fn test_round_robin_failover() { let client = get_client(vec![server1.uri(), server2.uri(), server3.uri()], None); // First request should fail over to the third node - let result = client.collection("products").retrieve().await; - assert!(result.is_ok()); + assert!(client.collection("products").retrieve().await.is_ok()); + assert_eq!(server1.received_requests().await.unwrap().len(), 1); assert_eq!(server2.received_requests().await.unwrap().len(), 1); assert_eq!(server3.received_requests().await.unwrap().len(), 1); @@ -146,19 +147,18 @@ async fn test_round_robin_failover() { // Reset server 3 to also fail server3.reset().await; setup_mock_server_503(&server3, "products").await; - // Make server 1 healthy again - server1.reset().await; - setup_mock_server_ok(&server1, "products").await; + // Make server 2 healthy again + server2.reset().await; + setup_mock_server_ok(&server2, "products").await; - let result2 = client.collection("products").retrieve().await; - assert!(result2.is_ok()); + assert!(client.collection("products").retrieve().await.is_ok()); // Server 3 was tried first and failed. assert_eq!(server3.received_requests().await.unwrap().len(), 1); - // Server 1 was tried next and succeeded. - assert_eq!(server1.received_requests().await.unwrap().len(), 1); - // Server 2 was not touched this time. - assert_eq!(server2.received_requests().await.unwrap().len(), 1); // Remains 1 from first call + // Server 2 was tried next and succeeded. + assert_eq!(server2.received_requests().await.unwrap().len(), 1); + // Server 1 was not touched this time. + assert_eq!(server1.received_requests().await.unwrap().len(), 1); // Remains 1 from first call } #[tokio::test] @@ -189,7 +189,7 @@ async fn test_health_check_and_node_recovery() { assert_eq!(server2.received_requests().await.unwrap().len(), 2); // Got another request // 3. Wait for the healthcheck interval to pass. - tokio::time::sleep(Duration::from_millis(600)).await; + tokio::time::sleep(Duration::from_millis(501)).await; // 4. Make server1 healthy again. server1.reset().await; diff --git a/typesense/tests/derive/collection.rs b/typesense/tests/derive/collection.rs index b83b9a2..71dcd91 100644 --- a/typesense/tests/derive/collection.rs +++ b/typesense/tests/derive/collection.rs @@ -1,6 +1,5 @@ use serde::{Deserialize, Serialize}; -use typesense::Typesense; -use typesense::prelude::Document; +use typesense::{Typesense, prelude::Document}; #[test] fn derived_document_generates_schema() { diff --git a/typesense_codegen/src/apis/analytics_api.rs b/typesense_codegen/src/apis/analytics_api.rs index bbab7fd..97910c7 100644 --- a/typesense_codegen/src/apis/analytics_api.rs +++ b/typesense_codegen/src/apis/analytics_api.rs @@ -4,35 +4,34 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ - +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`create_analytics_event`] #[derive(Clone, Debug)] pub struct CreateAnalyticsEventParams { /// The analytics event to be created - pub analytics_event: models::AnalyticsEvent + pub analytics_event: models::AnalyticsEvent, } /// struct for passing parameters to the method [`create_analytics_rule`] #[derive(Clone, Debug)] pub struct CreateAnalyticsRuleParams { /// The analytics rule(s) to be created - pub create_analytics_rule_request: models::CreateAnalyticsRuleRequest + pub create_analytics_rule_request: models::CreateAnalyticsRuleRequest, } /// struct for passing parameters to the method [`delete_analytics_rule`] #[derive(Clone, Debug)] pub struct DeleteAnalyticsRuleParams { /// The name of the analytics rule to delete - pub rule_name: String + pub rule_name: String, } /// struct for passing parameters to the method [`get_analytics_events`] @@ -42,21 +41,21 @@ pub struct GetAnalyticsEventsParams { /// Analytics rule name pub name: String, /// Number of events to return (max 1000) - pub n: i32 + pub n: i32, } /// struct for passing parameters to the method [`retrieve_analytics_rule`] #[derive(Clone, Debug)] pub struct RetrieveAnalyticsRuleParams { /// The name of the analytics rule to retrieve - pub rule_name: String + pub rule_name: String, } /// struct for passing parameters to the method [`retrieve_analytics_rules`] #[derive(Clone, Debug)] pub struct RetrieveAnalyticsRulesParams { /// Filter rules by rule_tag - pub rule_tag: Option + pub rule_tag: Option, } /// struct for passing parameters to the method [`upsert_analytics_rule`] @@ -65,10 +64,9 @@ pub struct UpsertAnalyticsRuleParams { /// The name of the analytics rule to upsert pub rule_name: String, /// The Analytics rule to be upserted - pub analytics_rule_update: models::AnalyticsRuleUpdate + pub analytics_rule_update: models::AnalyticsRuleUpdate, } - /// struct for typed errors of method [`create_analytics_event`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -138,21 +136,24 @@ pub enum UpsertAnalyticsRuleError { UnknownValue(serde_json::Value), } - /// Submit a single analytics event. The event must correspond to an existing analytics rule by name. -pub async fn create_analytics_event(configuration: &configuration::Configuration, params: CreateAnalyticsEventParams) -> Result> { - +pub async fn create_analytics_event( + configuration: &configuration::Configuration, + params: CreateAnalyticsEventParams, +) -> Result> { let uri_str = format!("{}/analytics/events", configuration.base_path); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -173,30 +174,46 @@ pub async fn create_analytics_event(configuration: &configuration::Configuration let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Create one or more analytics rules. You can send a single rule object or an array of rule objects. -pub async fn create_analytics_rule(configuration: &configuration::Configuration, params: CreateAnalyticsRuleParams) -> Result> { - +pub async fn create_analytics_rule( + configuration: &configuration::Configuration, + params: CreateAnalyticsRuleParams, +) -> Result> { let uri_str = format!("{}/analytics/rules", configuration.base_path); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -217,30 +234,50 @@ pub async fn create_analytics_rule(configuration: &configuration::Configuration, let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CreateAnalyticsRule200Response`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CreateAnalyticsRule200Response`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::CreateAnalyticsRule200Response`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::CreateAnalyticsRule200Response`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Permanently deletes an analytics rule, given it's name -pub async fn delete_analytics_rule(configuration: &configuration::Configuration, params: DeleteAnalyticsRuleParams) -> Result> { - - let uri_str = format!("{}/analytics/rules/{ruleName}", configuration.base_path, ruleName=crate::apis::urlencode(params.rule_name)); - let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_analytics_rule( + configuration: &configuration::Configuration, + params: DeleteAnalyticsRuleParams, +) -> Result> { + let uri_str = format!( + "{}/analytics/rules/{ruleName}", + configuration.base_path, + ruleName = crate::apis::urlencode(params.rule_name) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -260,30 +297,45 @@ pub async fn delete_analytics_rule(configuration: &configuration::Configuration, let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsRule`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsRule`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::AnalyticsRule`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsRule`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Triggers a flush of analytics data to persistent storage. -pub async fn flush_analytics(configuration: &configuration::Configuration) -> Result> { - +pub async fn flush_analytics( + configuration: &configuration::Configuration, +) -> Result> { let uri_str = format!("{}/analytics/flush", configuration.base_path); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -303,19 +355,33 @@ pub async fn flush_analytics(configuration: &configuration::Configuration) -> Re let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve the most recent events for a user and rule. -pub async fn get_analytics_events(configuration: &configuration::Configuration, params: GetAnalyticsEventsParams) -> Result> { - +pub async fn get_analytics_events( + configuration: &configuration::Configuration, + params: GetAnalyticsEventsParams, +) -> Result> { let uri_str = format!("{}/analytics/events", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -326,10 +392,10 @@ pub async fn get_analytics_events(configuration: &configuration::Configuration, req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -349,19 +415,32 @@ pub async fn get_analytics_events(configuration: &configuration::Configuration, let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsEventsResponse`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsEventsResponse`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::AnalyticsEventsResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsEventsResponse`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Returns sizes of internal analytics buffers and queues. -pub async fn get_analytics_status(configuration: &configuration::Configuration) -> Result> { - +pub async fn get_analytics_status( + configuration: &configuration::Configuration, +) -> Result> { let uri_str = format!("{}/analytics/status", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -369,10 +448,10 @@ pub async fn get_analytics_status(configuration: &configuration::Configuration) req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -392,30 +471,48 @@ pub async fn get_analytics_status(configuration: &configuration::Configuration) let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsStatus`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsStatus`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::AnalyticsStatus`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsStatus`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve the details of an analytics rule, given it's name -pub async fn retrieve_analytics_rule(configuration: &configuration::Configuration, params: RetrieveAnalyticsRuleParams) -> Result> { - - let uri_str = format!("{}/analytics/rules/{ruleName}", configuration.base_path, ruleName=crate::apis::urlencode(params.rule_name)); +pub async fn retrieve_analytics_rule( + configuration: &configuration::Configuration, + params: RetrieveAnalyticsRuleParams, +) -> Result> { + let uri_str = format!( + "{}/analytics/rules/{ruleName}", + configuration.base_path, + ruleName = crate::apis::urlencode(params.rule_name) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -435,19 +532,33 @@ pub async fn retrieve_analytics_rule(configuration: &configuration::Configuratio let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsRule`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsRule`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::AnalyticsRule`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsRule`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve all analytics rules. Use the optional rule_tag filter to narrow down results. -pub async fn retrieve_analytics_rules(configuration: &configuration::Configuration, params: RetrieveAnalyticsRulesParams) -> Result, Error> { - +pub async fn retrieve_analytics_rules( + configuration: &configuration::Configuration, + params: RetrieveAnalyticsRulesParams, +) -> Result, Error> { let uri_str = format!("{}/analytics/rules", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -458,10 +569,10 @@ pub async fn retrieve_analytics_rules(configuration: &configuration::Configurati req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -481,30 +592,48 @@ pub async fn retrieve_analytics_rules(configuration: &configuration::Configurati let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `Vec`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `Vec`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Upserts an analytics rule with the given name. -pub async fn upsert_analytics_rule(configuration: &configuration::Configuration, params: UpsertAnalyticsRuleParams) -> Result> { - - let uri_str = format!("{}/analytics/rules/{ruleName}", configuration.base_path, ruleName=crate::apis::urlencode(params.rule_name)); +pub async fn upsert_analytics_rule( + configuration: &configuration::Configuration, + params: UpsertAnalyticsRuleParams, +) -> Result> { + let uri_str = format!( + "{}/analytics/rules/{ruleName}", + configuration.base_path, + ruleName = crate::apis::urlencode(params.rule_name) + ); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -525,13 +654,24 @@ pub async fn upsert_analytics_rule(configuration: &configuration::Configuration, let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsRule`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsRule`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::AnalyticsRule`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsRule`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } - diff --git a/typesense_codegen/src/apis/collections_api.rs b/typesense_codegen/src/apis/collections_api.rs index bccc4da..d2356ce 100644 --- a/typesense_codegen/src/apis/collections_api.rs +++ b/typesense_codegen/src/apis/collections_api.rs @@ -4,49 +4,48 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ - +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`create_collection`] #[derive(Clone, Debug)] pub struct CreateCollectionParams { /// The collection object to be created - pub collection_schema: models::CollectionSchema + pub collection_schema: models::CollectionSchema, } /// struct for passing parameters to the method [`delete_alias`] #[derive(Clone, Debug)] pub struct DeleteAliasParams { /// The name of the alias to delete - pub alias_name: String + pub alias_name: String, } /// struct for passing parameters to the method [`delete_collection`] #[derive(Clone, Debug)] pub struct DeleteCollectionParams { /// The name of the collection to delete - pub collection_name: String + pub collection_name: String, } /// struct for passing parameters to the method [`get_alias`] #[derive(Clone, Debug)] pub struct GetAliasParams { /// The name of the alias to retrieve - pub alias_name: String + pub alias_name: String, } /// struct for passing parameters to the method [`get_collection`] #[derive(Clone, Debug)] pub struct GetCollectionParams { /// The name of the collection to retrieve - pub collection_name: String + pub collection_name: String, } /// struct for passing parameters to the method [`get_collections`] @@ -54,7 +53,7 @@ pub struct GetCollectionParams { pub struct GetCollectionsParams { pub exclude_fields: Option, pub limit: Option, - pub offset: Option + pub offset: Option, } /// struct for passing parameters to the method [`update_collection`] @@ -63,7 +62,7 @@ pub struct UpdateCollectionParams { /// The name of the collection to update pub collection_name: String, /// The document object with fields to be updated - pub collection_update_schema: models::CollectionUpdateSchema + pub collection_update_schema: models::CollectionUpdateSchema, } /// struct for passing parameters to the method [`upsert_alias`] @@ -72,10 +71,9 @@ pub struct UpsertAliasParams { /// The name of the alias to create/update pub alias_name: String, /// Collection alias to be created/updated - pub collection_alias_schema: Option + pub collection_alias_schema: Option, } - /// struct for typed errors of method [`create_collection`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -149,21 +147,24 @@ pub enum UpsertAliasError { UnknownValue(serde_json::Value), } - /// When a collection is created, we give it a name and describe the fields that will be indexed from the documents added to the collection. -pub async fn create_collection(configuration: &configuration::Configuration, params: CreateCollectionParams) -> Result> { - +pub async fn create_collection( + configuration: &configuration::Configuration, + params: CreateCollectionParams, +) -> Result> { let uri_str = format!("{}/collections", configuration.base_path); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -184,29 +185,49 @@ pub async fn create_collection(configuration: &configuration::Configuration, par let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionResponse`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionResponse`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::CollectionResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionResponse`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } -pub async fn delete_alias(configuration: &configuration::Configuration, params: DeleteAliasParams) -> Result> { - - let uri_str = format!("{}/aliases/{aliasName}", configuration.base_path, aliasName=crate::apis::urlencode(params.alias_name)); - let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_alias( + configuration: &configuration::Configuration, + params: DeleteAliasParams, +) -> Result> { + let uri_str = format!( + "{}/aliases/{aliasName}", + configuration.base_path, + aliasName = crate::apis::urlencode(params.alias_name) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -226,30 +247,50 @@ pub async fn delete_alias(configuration: &configuration::Configuration, params: let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionAlias`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAlias`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::CollectionAlias`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAlias`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Permanently drops a collection. This action cannot be undone. For large collections, this might have an impact on read latencies. -pub async fn delete_collection(configuration: &configuration::Configuration, params: DeleteCollectionParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); - let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_collection( + configuration: &configuration::Configuration, + params: DeleteCollectionParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -269,30 +310,48 @@ pub async fn delete_collection(configuration: &configuration::Configuration, par let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionResponse`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionResponse`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::CollectionResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionResponse`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Find out which collection an alias points to by fetching it -pub async fn get_alias(configuration: &configuration::Configuration, params: GetAliasParams) -> Result> { - - let uri_str = format!("{}/aliases/{aliasName}", configuration.base_path, aliasName=crate::apis::urlencode(params.alias_name)); +pub async fn get_alias( + configuration: &configuration::Configuration, + params: GetAliasParams, +) -> Result> { + let uri_str = format!( + "{}/aliases/{aliasName}", + configuration.base_path, + aliasName = crate::apis::urlencode(params.alias_name) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -312,19 +371,32 @@ pub async fn get_alias(configuration: &configuration::Configuration, params: Get let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionAlias`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAlias`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::CollectionAlias`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAlias`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// List all aliases and the corresponding collections that they map to. -pub async fn get_aliases(configuration: &configuration::Configuration) -> Result> { - +pub async fn get_aliases( + configuration: &configuration::Configuration, +) -> Result> { let uri_str = format!("{}/aliases", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -332,10 +404,10 @@ pub async fn get_aliases(configuration: &configuration::Configuration) -> Result req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -355,30 +427,48 @@ pub async fn get_aliases(configuration: &configuration::Configuration) -> Result let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionAliasesResponse`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAliasesResponse`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::CollectionAliasesResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAliasesResponse`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve the details of a collection, given its name. -pub async fn get_collection(configuration: &configuration::Configuration, params: GetCollectionParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); +pub async fn get_collection( + configuration: &configuration::Configuration, + params: GetCollectionParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -398,19 +488,33 @@ pub async fn get_collection(configuration: &configuration::Configuration, params let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionResponse`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionResponse`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::CollectionResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionResponse`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Returns a summary of all your collections. The collections are returned sorted by creation date, with the most recent collections appearing first. -pub async fn get_collections(configuration: &configuration::Configuration, params: GetCollectionsParams) -> Result, Error> { - +pub async fn get_collections( + configuration: &configuration::Configuration, + params: GetCollectionsParams, +) -> Result, Error> { let uri_str = format!("{}/collections", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -427,10 +531,10 @@ pub async fn get_collections(configuration: &configuration::Configuration, param req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -450,30 +554,50 @@ pub async fn get_collections(configuration: &configuration::Configuration, param let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `Vec`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `Vec`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Update a collection's schema to modify the fields and their types. -pub async fn update_collection(configuration: &configuration::Configuration, params: UpdateCollectionParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); - let mut req_builder = configuration.client.request(reqwest::Method::PATCH, &uri_str); +pub async fn update_collection( + configuration: &configuration::Configuration, + params: UpdateCollectionParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::PATCH, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -494,30 +618,48 @@ pub async fn update_collection(configuration: &configuration::Configuration, par let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionUpdateSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionUpdateSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::CollectionUpdateSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionUpdateSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Create or update a collection alias. An alias is a virtual collection name that points to a real collection. If you're familiar with symbolic links on Linux, it's very similar to that. Aliases are useful when you want to reindex your data in the background on a new collection and switch your application to it without any changes to your code. -pub async fn upsert_alias(configuration: &configuration::Configuration, params: UpsertAliasParams) -> Result> { - - let uri_str = format!("{}/aliases/{aliasName}", configuration.base_path, aliasName=crate::apis::urlencode(params.alias_name)); +pub async fn upsert_alias( + configuration: &configuration::Configuration, + params: UpsertAliasParams, +) -> Result> { + let uri_str = format!( + "{}/aliases/{aliasName}", + configuration.base_path, + aliasName = crate::apis::urlencode(params.alias_name) + ); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -538,13 +680,24 @@ pub async fn upsert_alias(configuration: &configuration::Configuration, params: let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionAlias`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAlias`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::CollectionAlias`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAlias`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } - diff --git a/typesense_codegen/src/apis/conversations_api.rs b/typesense_codegen/src/apis/conversations_api.rs index 1a071e0..4596344 100644 --- a/typesense_codegen/src/apis/conversations_api.rs +++ b/typesense_codegen/src/apis/conversations_api.rs @@ -4,34 +4,33 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ - +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`create_conversation_model`] #[derive(Clone, Debug)] pub struct CreateConversationModelParams { - pub conversation_model_create_schema: models::ConversationModelCreateSchema + pub conversation_model_create_schema: models::ConversationModelCreateSchema, } /// struct for passing parameters to the method [`delete_conversation_model`] #[derive(Clone, Debug)] pub struct DeleteConversationModelParams { /// The id of the conversation model to delete - pub model_id: String + pub model_id: String, } /// struct for passing parameters to the method [`retrieve_conversation_model`] #[derive(Clone, Debug)] pub struct RetrieveConversationModelParams { /// The id of the conversation model to retrieve - pub model_id: String + pub model_id: String, } /// struct for passing parameters to the method [`update_conversation_model`] @@ -39,10 +38,9 @@ pub struct RetrieveConversationModelParams { pub struct UpdateConversationModelParams { /// The id of the conversation model to update pub model_id: String, - pub conversation_model_update_schema: models::ConversationModelUpdateSchema + pub conversation_model_update_schema: models::ConversationModelUpdateSchema, } - /// struct for typed errors of method [`create_conversation_model`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -79,21 +77,24 @@ pub enum UpdateConversationModelError { UnknownValue(serde_json::Value), } - /// Create a Conversation Model -pub async fn create_conversation_model(configuration: &configuration::Configuration, params: CreateConversationModelParams) -> Result> { - +pub async fn create_conversation_model( + configuration: &configuration::Configuration, + params: CreateConversationModelParams, +) -> Result> { let uri_str = format!("{}/conversations/models", configuration.base_path); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -114,30 +115,50 @@ pub async fn create_conversation_model(configuration: &configuration::Configurat let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Delete a conversation model -pub async fn delete_conversation_model(configuration: &configuration::Configuration, params: DeleteConversationModelParams) -> Result> { - - let uri_str = format!("{}/conversations/models/{modelId}", configuration.base_path, modelId=crate::apis::urlencode(params.model_id)); - let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_conversation_model( + configuration: &configuration::Configuration, + params: DeleteConversationModelParams, +) -> Result> { + let uri_str = format!( + "{}/conversations/models/{modelId}", + configuration.base_path, + modelId = crate::apis::urlencode(params.model_id) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -157,19 +178,32 @@ pub async fn delete_conversation_model(configuration: &configuration::Configurat let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve all conversation models -pub async fn retrieve_all_conversation_models(configuration: &configuration::Configuration) -> Result, Error> { - +pub async fn retrieve_all_conversation_models( + configuration: &configuration::Configuration, +) -> Result, Error> { let uri_str = format!("{}/conversations/models", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -177,10 +211,10 @@ pub async fn retrieve_all_conversation_models(configuration: &configuration::Con req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -200,30 +234,49 @@ pub async fn retrieve_all_conversation_models(configuration: &configuration::Con let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `Vec`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `Vec`" + )))); + } } } else { let content = resp.text().await?; - let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + let entity: Option = + serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve a conversation model -pub async fn retrieve_conversation_model(configuration: &configuration::Configuration, params: RetrieveConversationModelParams) -> Result> { - - let uri_str = format!("{}/conversations/models/{modelId}", configuration.base_path, modelId=crate::apis::urlencode(params.model_id)); +pub async fn retrieve_conversation_model( + configuration: &configuration::Configuration, + params: RetrieveConversationModelParams, +) -> Result> { + let uri_str = format!( + "{}/conversations/models/{modelId}", + configuration.base_path, + modelId = crate::apis::urlencode(params.model_id) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -243,30 +296,48 @@ pub async fn retrieve_conversation_model(configuration: &configuration::Configur let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Update a conversation model -pub async fn update_conversation_model(configuration: &configuration::Configuration, params: UpdateConversationModelParams) -> Result> { - - let uri_str = format!("{}/conversations/models/{modelId}", configuration.base_path, modelId=crate::apis::urlencode(params.model_id)); +pub async fn update_conversation_model( + configuration: &configuration::Configuration, + params: UpdateConversationModelParams, +) -> Result> { + let uri_str = format!( + "{}/conversations/models/{modelId}", + configuration.base_path, + modelId = crate::apis::urlencode(params.model_id) + ); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -287,13 +358,24 @@ pub async fn update_conversation_model(configuration: &configuration::Configurat let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } - diff --git a/typesense_codegen/src/apis/curation_api.rs b/typesense_codegen/src/apis/curation_api.rs index 9fde986..42a9d2c 100644 --- a/typesense_codegen/src/apis/curation_api.rs +++ b/typesense_codegen/src/apis/curation_api.rs @@ -4,15 +4,14 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ - +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`delete_search_override`] #[derive(Clone, Debug)] @@ -20,14 +19,14 @@ pub struct DeleteSearchOverrideParams { /// The name of the collection pub collection_name: String, /// The ID of the search override to delete - pub override_id: String + pub override_id: String, } /// struct for passing parameters to the method [`get_search_overrides`] #[derive(Clone, Debug)] pub struct GetSearchOverridesParams { /// The name of the collection - pub collection_name: String + pub collection_name: String, } /// struct for passing parameters to the method [`upsert_search_override`] @@ -38,10 +37,9 @@ pub struct UpsertSearchOverrideParams { /// The ID of the search override to create/update pub override_id: String, /// The search override object to be created/updated - pub search_override_schema: models::SearchOverrideSchema + pub search_override_schema: models::SearchOverrideSchema, } - /// struct for typed errors of method [`delete_search_override`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -65,20 +63,28 @@ pub enum UpsertSearchOverrideError { UnknownValue(serde_json::Value), } - -pub async fn delete_search_override(configuration: &configuration::Configuration, params: DeleteSearchOverrideParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), overrideId=crate::apis::urlencode(params.override_id)); - let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_search_override( + configuration: &configuration::Configuration, + params: DeleteSearchOverrideParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/overrides/{overrideId}", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name), + overrideId = crate::apis::urlencode(params.override_id) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -98,29 +104,47 @@ pub async fn delete_search_override(configuration: &configuration::Configuration let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } -pub async fn get_search_overrides(configuration: &configuration::Configuration, params: GetSearchOverridesParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/overrides", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); +pub async fn get_search_overrides( + configuration: &configuration::Configuration, + params: GetSearchOverridesParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/overrides", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -140,30 +164,49 @@ pub async fn get_search_overrides(configuration: &configuration::Configuration, let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverridesResponse`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverridesResponse`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SearchOverridesResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverridesResponse`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Create or update an override to promote certain documents over others. Using overrides, you can include or exclude specific documents for a given query. -pub async fn upsert_search_override(configuration: &configuration::Configuration, params: UpsertSearchOverrideParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), overrideId=crate::apis::urlencode(params.override_id)); +pub async fn upsert_search_override( + configuration: &configuration::Configuration, + params: UpsertSearchOverrideParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/overrides/{overrideId}", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name), + overrideId = crate::apis::urlencode(params.override_id) + ); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -184,13 +227,24 @@ pub async fn upsert_search_override(configuration: &configuration::Configuration let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverride`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SearchOverride`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } - diff --git a/typesense_codegen/src/apis/debug_api.rs b/typesense_codegen/src/apis/debug_api.rs index 42d0e88..86fc9ea 100644 --- a/typesense_codegen/src/apis/debug_api.rs +++ b/typesense_codegen/src/apis/debug_api.rs @@ -4,16 +4,14 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ - +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration, ContentType}; - /// struct for typed errors of method [`debug`] #[derive(Debug, Clone, Serialize, Deserialize)] @@ -22,10 +20,10 @@ pub enum DebugError { UnknownValue(serde_json::Value), } - /// Print debugging information -pub async fn debug(configuration: &configuration::Configuration) -> Result> { - +pub async fn debug( + configuration: &configuration::Configuration, +) -> Result> { let uri_str = format!("{}/debug", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -33,10 +31,10 @@ pub async fn debug(configuration: &configuration::Configuration) -> Result format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -56,13 +54,24 @@ pub async fn debug(configuration: &configuration::Configuration) -> Result serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::Debug200Response`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::Debug200Response`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::Debug200Response`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::Debug200Response`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } - diff --git a/typesense_codegen/src/apis/documents_api.rs b/typesense_codegen/src/apis/documents_api.rs index 596d6c9..744a858 100644 --- a/typesense_codegen/src/apis/documents_api.rs +++ b/typesense_codegen/src/apis/documents_api.rs @@ -4,15 +4,14 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ - +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`delete_document`] #[derive(Clone, Debug)] @@ -20,7 +19,7 @@ pub struct DeleteDocumentParams { /// The name of the collection to search for the document under pub collection_name: String, /// The Document ID - pub document_id: String + pub document_id: String, } /// struct for passing parameters to the method [`delete_documents`] @@ -31,7 +30,7 @@ pub struct DeleteDocumentsParams { pub filter_by: Option, pub batch_size: Option, pub ignore_not_found: Option, - pub truncate: Option + pub truncate: Option, } /// struct for passing parameters to the method [`delete_search_override`] @@ -40,7 +39,7 @@ pub struct DeleteSearchOverrideParams { /// The name of the collection pub collection_name: String, /// The ID of the search override to delete - pub override_id: String + pub override_id: String, } /// struct for passing parameters to the method [`export_documents`] @@ -50,7 +49,7 @@ pub struct ExportDocumentsParams { pub collection_name: String, pub filter_by: Option, pub include_fields: Option, - pub exclude_fields: Option + pub exclude_fields: Option, } /// struct for passing parameters to the method [`get_document`] @@ -59,7 +58,7 @@ pub struct GetDocumentParams { /// The name of the collection to search for the document under pub collection_name: String, /// The Document ID - pub document_id: String + pub document_id: String, } /// struct for passing parameters to the method [`get_search_override`] @@ -68,14 +67,14 @@ pub struct GetSearchOverrideParams { /// The name of the collection pub collection_name: String, /// The id of the search override - pub override_id: String + pub override_id: String, } /// struct for passing parameters to the method [`get_search_overrides`] #[derive(Clone, Debug)] pub struct GetSearchOverridesParams { /// The name of the collection - pub collection_name: String + pub collection_name: String, } /// struct for passing parameters to the method [`import_documents`] @@ -90,7 +89,7 @@ pub struct ImportDocumentsParams { pub remote_embedding_batch_size: Option, pub return_doc: Option, pub action: Option, - pub dirty_values: Option + pub dirty_values: Option, } /// struct for passing parameters to the method [`index_document`] @@ -103,7 +102,7 @@ pub struct IndexDocumentParams { /// Additional action to perform pub action: Option, /// Dealing with Dirty Data - pub dirty_values: Option + pub dirty_values: Option, } /// struct for passing parameters to the method [`multi_search`] @@ -173,7 +172,7 @@ pub struct MultiSearchParams { pub conversation: Option, pub conversation_model_id: Option, pub conversation_id: Option, - pub multi_search_searches_parameter: Option + pub multi_search_searches_parameter: Option, } /// struct for passing parameters to the method [`search_collection`] @@ -251,7 +250,7 @@ pub struct SearchCollectionParams { pub voice_query: Option, pub conversation: Option, pub conversation_model_id: Option, - pub conversation_id: Option + pub conversation_id: Option, } /// struct for passing parameters to the method [`update_document`] @@ -264,7 +263,7 @@ pub struct UpdateDocumentParams { /// The document object with fields to be updated pub body: serde_json::Value, /// Dealing with Dirty Data - pub dirty_values: Option + pub dirty_values: Option, } /// struct for passing parameters to the method [`update_documents`] @@ -274,7 +273,7 @@ pub struct UpdateDocumentsParams { pub collection_name: String, /// The document fields to be updated pub body: serde_json::Value, - pub filter_by: Option + pub filter_by: Option, } /// struct for passing parameters to the method [`upsert_search_override`] @@ -285,10 +284,9 @@ pub struct UpsertSearchOverrideParams { /// The ID of the search override to create/update pub override_id: String, /// The search override object to be created/updated - pub search_override_schema: models::SearchOverrideSchema + pub search_override_schema: models::SearchOverrideSchema, } - /// struct for typed errors of method [`delete_document`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -402,21 +400,29 @@ pub enum UpsertSearchOverrideError { UnknownValue(serde_json::Value), } - /// Delete an individual document from a collection by using its ID. -pub async fn delete_document(configuration: &configuration::Configuration, params: DeleteDocumentParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/documents/{documentId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), documentId=crate::apis::urlencode(params.document_id)); - let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_document( + configuration: &configuration::Configuration, + params: DeleteDocumentParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/documents/{documentId}", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name), + documentId = crate::apis::urlencode(params.document_id) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -436,21 +442,41 @@ pub async fn delete_document(configuration: &configuration::Configuration, param let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `serde_json::Value`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `serde_json::Value`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Delete a bunch of documents that match a specific filter condition. Use the `batch_size` parameter to control the number of documents that should deleted at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. -pub async fn delete_documents(configuration: &configuration::Configuration, params: DeleteDocumentsParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/documents", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); - let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_documents( + configuration: &configuration::Configuration, + params: DeleteDocumentsParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/documents", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); if let Some(ref param_value) = params.filter_by { req_builder = req_builder.query(&[("filter_by", ¶m_value.to_string())]); @@ -468,10 +494,10 @@ pub async fn delete_documents(configuration: &configuration::Configuration, para req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -491,29 +517,50 @@ pub async fn delete_documents(configuration: &configuration::Configuration, para let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::DeleteDocuments200Response`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::DeleteDocuments200Response`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::DeleteDocuments200Response`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::DeleteDocuments200Response`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } -pub async fn delete_search_override(configuration: &configuration::Configuration, params: DeleteSearchOverrideParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), overrideId=crate::apis::urlencode(params.override_id)); - let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_search_override( + configuration: &configuration::Configuration, + params: DeleteSearchOverrideParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/overrides/{overrideId}", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name), + overrideId = crate::apis::urlencode(params.override_id) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -533,20 +580,38 @@ pub async fn delete_search_override(configuration: &configuration::Configuration let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Export all documents in a collection in JSON lines format. -pub async fn export_documents(configuration: &configuration::Configuration, params: ExportDocumentsParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/documents/export", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); +pub async fn export_documents( + configuration: &configuration::Configuration, + params: ExportDocumentsParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/documents/export", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref param_value) = params.filter_by { @@ -562,10 +627,10 @@ pub async fn export_documents(configuration: &configuration::Configuration, para req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -585,29 +650,44 @@ pub async fn export_documents(configuration: &configuration::Configuration, para let content = resp.text().await?; match content_type { ContentType::Json | ContentType::Text => return Ok(content), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `String`")))), + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `String`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Fetch an individual document from a collection by using its ID. -pub async fn get_document(configuration: &configuration::Configuration, params: GetDocumentParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/documents/{documentId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), documentId=crate::apis::urlencode(params.document_id)); +pub async fn get_document( + configuration: &configuration::Configuration, + params: GetDocumentParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/documents/{documentId}", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name), + documentId = crate::apis::urlencode(params.document_id) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -627,30 +707,49 @@ pub async fn get_document(configuration: &configuration::Configuration, params: let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `serde_json::Value`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `serde_json::Value`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve the details of a search override, given its id. -pub async fn get_search_override(configuration: &configuration::Configuration, params: GetSearchOverrideParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), overrideId=crate::apis::urlencode(params.override_id)); +pub async fn get_search_override( + configuration: &configuration::Configuration, + params: GetSearchOverrideParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/overrides/{overrideId}", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name), + overrideId = crate::apis::urlencode(params.override_id) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -670,29 +769,47 @@ pub async fn get_search_override(configuration: &configuration::Configuration, p let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverride`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SearchOverride`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } -pub async fn get_search_overrides(configuration: &configuration::Configuration, params: GetSearchOverridesParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/overrides", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); +pub async fn get_search_overrides( + configuration: &configuration::Configuration, + params: GetSearchOverridesParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/overrides", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -712,21 +829,41 @@ pub async fn get_search_overrides(configuration: &configuration::Configuration, let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverridesResponse`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverridesResponse`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SearchOverridesResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverridesResponse`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// The documents to be imported must be formatted in a newline delimited JSON structure. You can feed the output file from a Typesense export operation directly as import. -pub async fn import_documents(configuration: &configuration::Configuration, params: ImportDocumentsParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/documents/import", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); +pub async fn import_documents( + configuration: &configuration::Configuration, + params: ImportDocumentsParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/documents/import", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); if let Some(ref param_value) = params.batch_size { req_builder = req_builder.query(&[("batch_size", ¶m_value.to_string())]); @@ -735,7 +872,8 @@ pub async fn import_documents(configuration: &configuration::Configuration, para req_builder = req_builder.query(&[("return_id", ¶m_value.to_string())]); } if let Some(ref param_value) = params.remote_embedding_batch_size { - req_builder = req_builder.query(&[("remote_embedding_batch_size", ¶m_value.to_string())]); + req_builder = + req_builder.query(&[("remote_embedding_batch_size", ¶m_value.to_string())]); } if let Some(ref param_value) = params.return_doc { req_builder = req_builder.query(&[("return_doc", ¶m_value.to_string())]); @@ -750,14 +888,16 @@ pub async fn import_documents(configuration: &configuration::Configuration, para req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - req_builder = req_builder.header(reqwest::header::CONTENT_TYPE, "text/plain").body(params.body); + req_builder = req_builder + .header(reqwest::header::CONTENT_TYPE, "text/plain") + .body(params.body); let req = req_builder.build()?; let resp = configuration.client.execute(req).await?; @@ -774,20 +914,36 @@ pub async fn import_documents(configuration: &configuration::Configuration, para let content = resp.text().await?; match content_type { ContentType::Json | ContentType::Text => return Ok(content), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `String`")))), + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `String`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// A document to be indexed in a given collection must conform to the schema of the collection. -pub async fn index_document(configuration: &configuration::Configuration, params: IndexDocumentParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/documents", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); +pub async fn index_document( + configuration: &configuration::Configuration, + params: IndexDocumentParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/documents", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); if let Some(ref param_value) = params.action { req_builder = req_builder.query(&[("action", ¶m_value.to_string())]); @@ -799,10 +955,10 @@ pub async fn index_document(configuration: &configuration::Configuration, params req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -823,21 +979,37 @@ pub async fn index_document(configuration: &configuration::Configuration, params let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `serde_json::Value`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `serde_json::Value`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// This is especially useful to avoid round-trip network latencies incurred otherwise if each of these requests are sent in separate HTTP requests. You can also use this feature to do a federated search across multiple collections in a single HTTP request. -pub async fn multi_search(configuration: &configuration::Configuration, params: MultiSearchParams) -> Result> { - +pub async fn multi_search( + configuration: &configuration::Configuration, + params: MultiSearchParams, +) -> Result> { let uri_str = format!("{}/multi_search", configuration.base_path); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); if let Some(ref param_value) = params.q { req_builder = req_builder.query(&[("q", ¶m_value.to_string())]); @@ -912,7 +1084,8 @@ pub async fn multi_search(configuration: &configuration::Configuration, params: req_builder = req_builder.query(&[("highlight_full_fields", ¶m_value.to_string())]); } if let Some(ref param_value) = params.highlight_affix_num_tokens { - req_builder = req_builder.query(&[("highlight_affix_num_tokens", ¶m_value.to_string())]); + req_builder = + req_builder.query(&[("highlight_affix_num_tokens", ¶m_value.to_string())]); } if let Some(ref param_value) = params.highlight_start_tag { req_builder = req_builder.query(&[("highlight_start_tag", ¶m_value.to_string())]); @@ -933,7 +1106,10 @@ pub async fn multi_search(configuration: &configuration::Configuration, params: req_builder = req_builder.query(&[("typo_tokens_threshold", ¶m_value.to_string())]); } if let Some(ref param_value) = params.enable_typos_for_alpha_numerical_tokens { - req_builder = req_builder.query(&[("enable_typos_for_alpha_numerical_tokens", ¶m_value.to_string())]); + req_builder = req_builder.query(&[( + "enable_typos_for_alpha_numerical_tokens", + ¶m_value.to_string(), + )]); } if let Some(ref param_value) = params.filter_curated_hits { req_builder = req_builder.query(&[("filter_curated_hits", ¶m_value.to_string())]); @@ -978,10 +1154,14 @@ pub async fn multi_search(configuration: &configuration::Configuration, params: req_builder = req_builder.query(&[("prioritize_token_position", ¶m_value.to_string())]); } if let Some(ref param_value) = params.prioritize_num_matching_fields { - req_builder = req_builder.query(&[("prioritize_num_matching_fields", ¶m_value.to_string())]); + req_builder = + req_builder.query(&[("prioritize_num_matching_fields", ¶m_value.to_string())]); } if let Some(ref param_value) = params.enable_typos_for_numerical_tokens { - req_builder = req_builder.query(&[("enable_typos_for_numerical_tokens", ¶m_value.to_string())]); + req_builder = req_builder.query(&[( + "enable_typos_for_numerical_tokens", + ¶m_value.to_string(), + )]); } if let Some(ref param_value) = params.exhaustive_search { req_builder = req_builder.query(&[("exhaustive_search", ¶m_value.to_string())]); @@ -1005,10 +1185,12 @@ pub async fn multi_search(configuration: &configuration::Configuration, params: req_builder = req_builder.query(&[("vector_query", ¶m_value.to_string())]); } if let Some(ref param_value) = params.remote_embedding_timeout_ms { - req_builder = req_builder.query(&[("remote_embedding_timeout_ms", ¶m_value.to_string())]); + req_builder = + req_builder.query(&[("remote_embedding_timeout_ms", ¶m_value.to_string())]); } if let Some(ref param_value) = params.remote_embedding_num_tries { - req_builder = req_builder.query(&[("remote_embedding_num_tries", ¶m_value.to_string())]); + req_builder = + req_builder.query(&[("remote_embedding_num_tries", ¶m_value.to_string())]); } if let Some(ref param_value) = params.facet_strategy { req_builder = req_builder.query(&[("facet_strategy", ¶m_value.to_string())]); @@ -1035,10 +1217,10 @@ pub async fn multi_search(configuration: &configuration::Configuration, params: req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -1059,20 +1241,38 @@ pub async fn multi_search(configuration: &configuration::Configuration, params: let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `serde_json::Value`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `serde_json::Value`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Search for documents in a collection that match the search criteria. -pub async fn search_collection serde::Deserialize<'de> + Serialize>(configuration: &configuration::Configuration, params: SearchCollectionParams) -> Result, Error> { - - let uri_str = format!("{}/collections/{collectionName}/documents/search", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); +pub async fn search_collection serde::Deserialize<'de> + Serialize>( + configuration: &configuration::Configuration, + params: SearchCollectionParams, +) -> Result, Error> { + let uri_str = format!( + "{}/collections/{collectionName}/documents/search", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref param_value) = params.q { @@ -1157,7 +1357,8 @@ pub async fn search_collection serde::Deserialize<'de> + Serialize>( req_builder = req_builder.query(&[("highlight_full_fields", ¶m_value.to_string())]); } if let Some(ref param_value) = params.highlight_affix_num_tokens { - req_builder = req_builder.query(&[("highlight_affix_num_tokens", ¶m_value.to_string())]); + req_builder = + req_builder.query(&[("highlight_affix_num_tokens", ¶m_value.to_string())]); } if let Some(ref param_value) = params.highlight_start_tag { req_builder = req_builder.query(&[("highlight_start_tag", ¶m_value.to_string())]); @@ -1187,7 +1388,10 @@ pub async fn search_collection serde::Deserialize<'de> + Serialize>( req_builder = req_builder.query(&[("typo_tokens_threshold", ¶m_value.to_string())]); } if let Some(ref param_value) = params.enable_typos_for_alpha_numerical_tokens { - req_builder = req_builder.query(&[("enable_typos_for_alpha_numerical_tokens", ¶m_value.to_string())]); + req_builder = req_builder.query(&[( + "enable_typos_for_alpha_numerical_tokens", + ¶m_value.to_string(), + )]); } if let Some(ref param_value) = params.filter_curated_hits { req_builder = req_builder.query(&[("filter_curated_hits", ¶m_value.to_string())]); @@ -1235,10 +1439,14 @@ pub async fn search_collection serde::Deserialize<'de> + Serialize>( req_builder = req_builder.query(&[("prioritize_token_position", ¶m_value.to_string())]); } if let Some(ref param_value) = params.prioritize_num_matching_fields { - req_builder = req_builder.query(&[("prioritize_num_matching_fields", ¶m_value.to_string())]); + req_builder = + req_builder.query(&[("prioritize_num_matching_fields", ¶m_value.to_string())]); } if let Some(ref param_value) = params.enable_typos_for_numerical_tokens { - req_builder = req_builder.query(&[("enable_typos_for_numerical_tokens", ¶m_value.to_string())]); + req_builder = req_builder.query(&[( + "enable_typos_for_numerical_tokens", + ¶m_value.to_string(), + )]); } if let Some(ref param_value) = params.exhaustive_search { req_builder = req_builder.query(&[("exhaustive_search", ¶m_value.to_string())]); @@ -1262,10 +1470,12 @@ pub async fn search_collection serde::Deserialize<'de> + Serialize>( req_builder = req_builder.query(&[("vector_query", ¶m_value.to_string())]); } if let Some(ref param_value) = params.remote_embedding_timeout_ms { - req_builder = req_builder.query(&[("remote_embedding_timeout_ms", ¶m_value.to_string())]); + req_builder = + req_builder.query(&[("remote_embedding_timeout_ms", ¶m_value.to_string())]); } if let Some(ref param_value) = params.remote_embedding_num_tries { - req_builder = req_builder.query(&[("remote_embedding_num_tries", ¶m_value.to_string())]); + req_builder = + req_builder.query(&[("remote_embedding_num_tries", ¶m_value.to_string())]); } if let Some(ref param_value) = params.facet_strategy { req_builder = req_builder.query(&[("facet_strategy", ¶m_value.to_string())]); @@ -1292,10 +1502,10 @@ pub async fn search_collection serde::Deserialize<'de> + Serialize>( req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -1315,21 +1525,42 @@ pub async fn search_collection serde::Deserialize<'de> + Serialize>( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchResult`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchResult`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SearchResult`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SearchResult`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Update an individual document from a collection by using its ID. The update can be partial. -pub async fn update_document(configuration: &configuration::Configuration, params: UpdateDocumentParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/documents/{documentId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), documentId=crate::apis::urlencode(params.document_id)); - let mut req_builder = configuration.client.request(reqwest::Method::PATCH, &uri_str); +pub async fn update_document( + configuration: &configuration::Configuration, + params: UpdateDocumentParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/documents/{documentId}", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name), + documentId = crate::apis::urlencode(params.document_id) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::PATCH, &uri_str); if let Some(ref param_value) = params.dirty_values { req_builder = req_builder.query(&[("dirty_values", ¶m_value.to_string())]); @@ -1338,10 +1569,10 @@ pub async fn update_document(configuration: &configuration::Configuration, param req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -1362,21 +1593,41 @@ pub async fn update_document(configuration: &configuration::Configuration, param let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `serde_json::Value`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `serde_json::Value`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// The filter_by query parameter is used to filter to specify a condition against which the documents are matched. The request body contains the fields that should be updated for any documents that match the filter condition. This endpoint is only available if the Typesense server is version `0.25.0.rc12` or later. -pub async fn update_documents(configuration: &configuration::Configuration, params: UpdateDocumentsParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/documents", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); - let mut req_builder = configuration.client.request(reqwest::Method::PATCH, &uri_str); +pub async fn update_documents( + configuration: &configuration::Configuration, + params: UpdateDocumentsParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/documents", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::PATCH, &uri_str); if let Some(ref param_value) = params.filter_by { req_builder = req_builder.query(&[("filter_by", ¶m_value.to_string())]); @@ -1385,10 +1636,10 @@ pub async fn update_documents(configuration: &configuration::Configuration, para req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -1409,30 +1660,49 @@ pub async fn update_documents(configuration: &configuration::Configuration, para let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::UpdateDocuments200Response`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::UpdateDocuments200Response`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::UpdateDocuments200Response`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::UpdateDocuments200Response`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Create or update an override to promote certain documents over others. Using overrides, you can include or exclude specific documents for a given query. -pub async fn upsert_search_override(configuration: &configuration::Configuration, params: UpsertSearchOverrideParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), overrideId=crate::apis::urlencode(params.override_id)); +pub async fn upsert_search_override( + configuration: &configuration::Configuration, + params: UpsertSearchOverrideParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/overrides/{overrideId}", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name), + overrideId = crate::apis::urlencode(params.override_id) + ); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -1453,13 +1723,24 @@ pub async fn upsert_search_override(configuration: &configuration::Configuration let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverride`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SearchOverride`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } - diff --git a/typesense_codegen/src/apis/health_api.rs b/typesense_codegen/src/apis/health_api.rs index 50f8085..1a61750 100644 --- a/typesense_codegen/src/apis/health_api.rs +++ b/typesense_codegen/src/apis/health_api.rs @@ -4,16 +4,14 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ - +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration, ContentType}; - /// struct for typed errors of method [`health`] #[derive(Debug, Clone, Serialize, Deserialize)] @@ -22,10 +20,10 @@ pub enum HealthError { UnknownValue(serde_json::Value), } - /// Checks if Typesense server is ready to accept requests. -pub async fn health(configuration: &configuration::Configuration) -> Result> { - +pub async fn health( + configuration: &configuration::Configuration, +) -> Result> { let uri_str = format!("{}/health", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -33,10 +31,10 @@ pub async fn health(configuration: &configuration::Configuration) -> Result format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -56,13 +54,24 @@ pub async fn health(configuration: &configuration::Configuration) -> Result serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::HealthStatus`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::HealthStatus`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::HealthStatus`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::HealthStatus`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } - diff --git a/typesense_codegen/src/apis/keys_api.rs b/typesense_codegen/src/apis/keys_api.rs index e635b0e..b419c52 100644 --- a/typesense_codegen/src/apis/keys_api.rs +++ b/typesense_codegen/src/apis/keys_api.rs @@ -4,38 +4,36 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ - +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`create_key`] #[derive(Clone, Debug)] pub struct CreateKeyParams { /// The object that describes API key scope - pub api_key_schema: Option + pub api_key_schema: Option, } /// struct for passing parameters to the method [`delete_key`] #[derive(Clone, Debug)] pub struct DeleteKeyParams { /// The ID of the key to delete - pub key_id: i64 + pub key_id: i64, } /// struct for passing parameters to the method [`get_key`] #[derive(Clone, Debug)] pub struct GetKeyParams { /// The ID of the key to retrieve - pub key_id: i64 + pub key_id: i64, } - /// struct for typed errors of method [`create_key`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -69,21 +67,24 @@ pub enum GetKeysError { UnknownValue(serde_json::Value), } - /// Create an API Key with fine-grain access control. You can restrict access on both a per-collection and per-action level. The generated key is returned only during creation. You want to store this key carefully in a secure place. -pub async fn create_key(configuration: &configuration::Configuration, params: CreateKeyParams) -> Result> { - +pub async fn create_key( + configuration: &configuration::Configuration, + params: CreateKeyParams, +) -> Result> { let uri_str = format!("{}/keys", configuration.base_path); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -104,29 +105,49 @@ pub async fn create_key(configuration: &configuration::Configuration, params: Cr let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ApiKey`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ApiKey`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::ApiKey`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::ApiKey`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } -pub async fn delete_key(configuration: &configuration::Configuration, params: DeleteKeyParams) -> Result> { - - let uri_str = format!("{}/keys/{keyId}", configuration.base_path, keyId=params.key_id); - let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_key( + configuration: &configuration::Configuration, + params: DeleteKeyParams, +) -> Result> { + let uri_str = format!( + "{}/keys/{keyId}", + configuration.base_path, + keyId = params.key_id + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -146,30 +167,48 @@ pub async fn delete_key(configuration: &configuration::Configuration, params: De let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ApiKeyDeleteResponse`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ApiKeyDeleteResponse`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::ApiKeyDeleteResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::ApiKeyDeleteResponse`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve (metadata about) a key. Only the key prefix is returned when you retrieve a key. Due to security reasons, only the create endpoint returns the full API key. -pub async fn get_key(configuration: &configuration::Configuration, params: GetKeyParams) -> Result> { - - let uri_str = format!("{}/keys/{keyId}", configuration.base_path, keyId=params.key_id); +pub async fn get_key( + configuration: &configuration::Configuration, + params: GetKeyParams, +) -> Result> { + let uri_str = format!( + "{}/keys/{keyId}", + configuration.base_path, + keyId = params.key_id + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -189,18 +228,31 @@ pub async fn get_key(configuration: &configuration::Configuration, params: GetKe let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ApiKey`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ApiKey`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::ApiKey`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::ApiKey`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } -pub async fn get_keys(configuration: &configuration::Configuration) -> Result> { - +pub async fn get_keys( + configuration: &configuration::Configuration, +) -> Result> { let uri_str = format!("{}/keys", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -208,10 +260,10 @@ pub async fn get_keys(configuration: &configuration::Configuration) -> Result format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -231,13 +283,24 @@ pub async fn get_keys(configuration: &configuration::Configuration) -> Result serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ApiKeysResponse`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ApiKeysResponse`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::ApiKeysResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::ApiKeysResponse`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } - diff --git a/typesense_codegen/src/apis/mod.rs b/typesense_codegen/src/apis/mod.rs index 9e6d17d..9b18bf9 100644 --- a/typesense_codegen/src/apis/mod.rs +++ b/typesense_codegen/src/apis/mod.rs @@ -1,5 +1,4 @@ -use std::error; -use std::fmt; +use std::{error, fmt}; #[derive(Debug, Clone)] pub struct ResponseContent { diff --git a/typesense_codegen/src/apis/nl_search_models_api.rs b/typesense_codegen/src/apis/nl_search_models_api.rs index fbf5493..b30d551 100644 --- a/typesense_codegen/src/apis/nl_search_models_api.rs +++ b/typesense_codegen/src/apis/nl_search_models_api.rs @@ -4,35 +4,34 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ - +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`create_nl_search_model`] #[derive(Clone, Debug)] pub struct CreateNlSearchModelParams { /// The NL search model to be created - pub nl_search_model_create_schema: models::NlSearchModelCreateSchema + pub nl_search_model_create_schema: models::NlSearchModelCreateSchema, } /// struct for passing parameters to the method [`delete_nl_search_model`] #[derive(Clone, Debug)] pub struct DeleteNlSearchModelParams { /// The ID of the NL search model to delete - pub model_id: String + pub model_id: String, } /// struct for passing parameters to the method [`retrieve_nl_search_model`] #[derive(Clone, Debug)] pub struct RetrieveNlSearchModelParams { /// The ID of the NL search model to retrieve - pub model_id: String + pub model_id: String, } /// struct for passing parameters to the method [`update_nl_search_model`] @@ -41,10 +40,9 @@ pub struct UpdateNlSearchModelParams { /// The ID of the NL search model to update pub model_id: String, /// The NL search model fields to update - pub body: models::NlSearchModelCreateSchema + pub body: models::NlSearchModelCreateSchema, } - /// struct for typed errors of method [`create_nl_search_model`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -85,21 +83,24 @@ pub enum UpdateNlSearchModelError { UnknownValue(serde_json::Value), } - /// Create a new NL search model. -pub async fn create_nl_search_model(configuration: &configuration::Configuration, params: CreateNlSearchModelParams) -> Result> { - +pub async fn create_nl_search_model( + configuration: &configuration::Configuration, + params: CreateNlSearchModelParams, +) -> Result> { let uri_str = format!("{}/nl_search_models", configuration.base_path); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -120,30 +121,50 @@ pub async fn create_nl_search_model(configuration: &configuration::Configuration let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::NlSearchModelSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::NlSearchModelSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Delete a specific NL search model by its ID. -pub async fn delete_nl_search_model(configuration: &configuration::Configuration, params: DeleteNlSearchModelParams) -> Result> { - - let uri_str = format!("{}/nl_search_models/{modelId}", configuration.base_path, modelId=crate::apis::urlencode(params.model_id)); - let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_nl_search_model( + configuration: &configuration::Configuration, + params: DeleteNlSearchModelParams, +) -> Result> { + let uri_str = format!( + "{}/nl_search_models/{modelId}", + configuration.base_path, + modelId = crate::apis::urlencode(params.model_id) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -163,19 +184,32 @@ pub async fn delete_nl_search_model(configuration: &configuration::Configuration let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::NlSearchModelDeleteSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelDeleteSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::NlSearchModelDeleteSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelDeleteSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve all NL search models. -pub async fn retrieve_all_nl_search_models(configuration: &configuration::Configuration) -> Result, Error> { - +pub async fn retrieve_all_nl_search_models( + configuration: &configuration::Configuration, +) -> Result, Error> { let uri_str = format!("{}/nl_search_models", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -183,10 +217,10 @@ pub async fn retrieve_all_nl_search_models(configuration: &configuration::Config req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -206,30 +240,48 @@ pub async fn retrieve_all_nl_search_models(configuration: &configuration::Config let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `Vec`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `Vec`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve a specific NL search model by its ID. -pub async fn retrieve_nl_search_model(configuration: &configuration::Configuration, params: RetrieveNlSearchModelParams) -> Result> { - - let uri_str = format!("{}/nl_search_models/{modelId}", configuration.base_path, modelId=crate::apis::urlencode(params.model_id)); +pub async fn retrieve_nl_search_model( + configuration: &configuration::Configuration, + params: RetrieveNlSearchModelParams, +) -> Result> { + let uri_str = format!( + "{}/nl_search_models/{modelId}", + configuration.base_path, + modelId = crate::apis::urlencode(params.model_id) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -249,30 +301,48 @@ pub async fn retrieve_nl_search_model(configuration: &configuration::Configurati let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::NlSearchModelSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::NlSearchModelSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Update an existing NL search model. -pub async fn update_nl_search_model(configuration: &configuration::Configuration, params: UpdateNlSearchModelParams) -> Result> { - - let uri_str = format!("{}/nl_search_models/{modelId}", configuration.base_path, modelId=crate::apis::urlencode(params.model_id)); +pub async fn update_nl_search_model( + configuration: &configuration::Configuration, + params: UpdateNlSearchModelParams, +) -> Result> { + let uri_str = format!( + "{}/nl_search_models/{modelId}", + configuration.base_path, + modelId = crate::apis::urlencode(params.model_id) + ); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -293,13 +363,24 @@ pub async fn update_nl_search_model(configuration: &configuration::Configuration let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::NlSearchModelSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::NlSearchModelSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } - diff --git a/typesense_codegen/src/apis/operations_api.rs b/typesense_codegen/src/apis/operations_api.rs index f80dcbd..971cddb 100644 --- a/typesense_codegen/src/apis/operations_api.rs +++ b/typesense_codegen/src/apis/operations_api.rs @@ -4,30 +4,28 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ - +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`take_snapshot`] #[derive(Clone, Debug)] pub struct TakeSnapshotParams { /// The directory on the server where the snapshot should be saved. - pub snapshot_path: String + pub snapshot_path: String, } /// struct for passing parameters to the method [`toggle_slow_request_log`] #[derive(Clone, Debug)] pub struct ToggleSlowRequestLogParams { - pub toggle_slow_request_log_request: Option + pub toggle_slow_request_log_request: Option, } - /// struct for typed errors of method [`clear_cache`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -84,21 +82,23 @@ pub enum VoteError { UnknownValue(serde_json::Value), } - /// Clear the cached responses of search requests that are sent with `use_cache` parameter in the LRU cache. -pub async fn clear_cache(configuration: &configuration::Configuration) -> Result> { - +pub async fn clear_cache( + configuration: &configuration::Configuration, +) -> Result> { let uri_str = format!("{}/operations/cache/clear", configuration.base_path); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -118,30 +118,45 @@ pub async fn clear_cache(configuration: &configuration::Configuration) -> Result let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Typesense uses RocksDB to store your documents on the disk. If you do frequent writes or updates, you could benefit from running a compaction of the underlying RocksDB database. This could reduce the size of the database and decrease read latency. While the database will not block during this operation, we recommend running it during off-peak hours. -pub async fn compact_db(configuration: &configuration::Configuration) -> Result> { - +pub async fn compact_db( + configuration: &configuration::Configuration, +) -> Result> { let uri_str = format!("{}/operations/db/compact", configuration.base_path); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -161,19 +176,32 @@ pub async fn compact_db(configuration: &configuration::Configuration) -> Result< let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Returns the status of any ongoing schema change operations. If no schema changes are in progress, returns an empty response. -pub async fn get_schema_changes(configuration: &configuration::Configuration) -> Result, Error> { - +pub async fn get_schema_changes( + configuration: &configuration::Configuration, +) -> Result, Error> { let uri_str = format!("{}/operations/schema_changes", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -181,10 +209,10 @@ pub async fn get_schema_changes(configuration: &configuration::Configuration) -> req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -204,19 +232,32 @@ pub async fn get_schema_changes(configuration: &configuration::Configuration) -> let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `Vec`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `Vec`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve the stats about API endpoints. -pub async fn retrieve_api_stats(configuration: &configuration::Configuration) -> Result> { - +pub async fn retrieve_api_stats( + configuration: &configuration::Configuration, +) -> Result> { let uri_str = format!("{}/stats.json", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -224,10 +265,10 @@ pub async fn retrieve_api_stats(configuration: &configuration::Configuration) -> req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -247,19 +288,32 @@ pub async fn retrieve_api_stats(configuration: &configuration::Configuration) -> let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ApiStatsResponse`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ApiStatsResponse`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::ApiStatsResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::ApiStatsResponse`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve the metrics. -pub async fn retrieve_metrics(configuration: &configuration::Configuration) -> Result> { - +pub async fn retrieve_metrics( + configuration: &configuration::Configuration, +) -> Result> { let uri_str = format!("{}/metrics.json", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -267,10 +321,10 @@ pub async fn retrieve_metrics(configuration: &configuration::Configuration) -> R req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -290,31 +344,47 @@ pub async fn retrieve_metrics(configuration: &configuration::Configuration) -> R let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `serde_json::Value`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `serde_json::Value`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Creates a point-in-time snapshot of a Typesense node's state and data in the specified directory. You can then backup the snapshot directory that gets created and later restore it as a data directory, as needed. -pub async fn take_snapshot(configuration: &configuration::Configuration, params: TakeSnapshotParams) -> Result> { - +pub async fn take_snapshot( + configuration: &configuration::Configuration, + params: TakeSnapshotParams, +) -> Result> { let uri_str = format!("{}/operations/snapshot", configuration.base_path); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); req_builder = req_builder.query(&[("snapshot_path", ¶ms.snapshot_path.to_string())]); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -334,30 +404,46 @@ pub async fn take_snapshot(configuration: &configuration::Configuration, params: let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Enable logging of requests that take over a defined threshold of time. Default is `-1` which disables slow request logging. Slow requests are logged to the primary log file, with the prefix SLOW REQUEST. -pub async fn toggle_slow_request_log(configuration: &configuration::Configuration, params: ToggleSlowRequestLogParams) -> Result> { - +pub async fn toggle_slow_request_log( + configuration: &configuration::Configuration, + params: ToggleSlowRequestLogParams, +) -> Result> { let uri_str = format!("{}/config", configuration.base_path); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -378,30 +464,45 @@ pub async fn toggle_slow_request_log(configuration: &configuration::Configuratio let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Triggers a follower node to initiate the raft voting process, which triggers leader re-election. The follower node that you run this operation against will become the new leader, once this command succeeds. -pub async fn vote(configuration: &configuration::Configuration) -> Result> { - +pub async fn vote( + configuration: &configuration::Configuration, +) -> Result> { let uri_str = format!("{}/operations/vote", configuration.base_path); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -421,13 +522,24 @@ pub async fn vote(configuration: &configuration::Configuration) -> Result serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } - diff --git a/typesense_codegen/src/apis/override_api.rs b/typesense_codegen/src/apis/override_api.rs index 0f8287f..07b8cb3 100644 --- a/typesense_codegen/src/apis/override_api.rs +++ b/typesense_codegen/src/apis/override_api.rs @@ -4,15 +4,14 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ - +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`get_search_override`] #[derive(Clone, Debug)] @@ -20,10 +19,9 @@ pub struct GetSearchOverrideParams { /// The name of the collection pub collection_name: String, /// The id of the search override - pub override_id: String + pub override_id: String, } - /// struct for typed errors of method [`get_search_override`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -31,21 +29,27 @@ pub enum GetSearchOverrideError { UnknownValue(serde_json::Value), } - /// Retrieve the details of a search override, given its id. -pub async fn get_search_override(configuration: &configuration::Configuration, params: GetSearchOverrideParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), overrideId=crate::apis::urlencode(params.override_id)); +pub async fn get_search_override( + configuration: &configuration::Configuration, + params: GetSearchOverrideParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/overrides/{overrideId}", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name), + overrideId = crate::apis::urlencode(params.override_id) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -65,13 +69,24 @@ pub async fn get_search_override(configuration: &configuration::Configuration, p let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverride`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SearchOverride`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } - diff --git a/typesense_codegen/src/apis/presets_api.rs b/typesense_codegen/src/apis/presets_api.rs index 5789d17..eaf1046 100644 --- a/typesense_codegen/src/apis/presets_api.rs +++ b/typesense_codegen/src/apis/presets_api.rs @@ -4,28 +4,27 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ - +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`delete_preset`] #[derive(Clone, Debug)] pub struct DeletePresetParams { /// The ID of the preset to delete. - pub preset_id: String + pub preset_id: String, } /// struct for passing parameters to the method [`retrieve_preset`] #[derive(Clone, Debug)] pub struct RetrievePresetParams { /// The ID of the preset to retrieve. - pub preset_id: String + pub preset_id: String, } /// struct for passing parameters to the method [`upsert_preset`] @@ -34,10 +33,9 @@ pub struct UpsertPresetParams { /// The name of the preset set to upsert. pub preset_id: String, /// The stopwords set to upsert. - pub preset_upsert_schema: models::PresetUpsertSchema + pub preset_upsert_schema: models::PresetUpsertSchema, } - /// struct for typed errors of method [`delete_preset`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -69,21 +67,28 @@ pub enum UpsertPresetError { UnknownValue(serde_json::Value), } - /// Permanently deletes a preset, given it's name. -pub async fn delete_preset(configuration: &configuration::Configuration, params: DeletePresetParams) -> Result> { - - let uri_str = format!("{}/presets/{presetId}", configuration.base_path, presetId=crate::apis::urlencode(params.preset_id)); - let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_preset( + configuration: &configuration::Configuration, + params: DeletePresetParams, +) -> Result> { + let uri_str = format!( + "{}/presets/{presetId}", + configuration.base_path, + presetId = crate::apis::urlencode(params.preset_id) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -103,19 +108,32 @@ pub async fn delete_preset(configuration: &configuration::Configuration, params: let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::PresetDeleteSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::PresetDeleteSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::PresetDeleteSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::PresetDeleteSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve the details of all presets -pub async fn retrieve_all_presets(configuration: &configuration::Configuration) -> Result> { - +pub async fn retrieve_all_presets( + configuration: &configuration::Configuration, +) -> Result> { let uri_str = format!("{}/presets", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -123,10 +141,10 @@ pub async fn retrieve_all_presets(configuration: &configuration::Configuration) req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -146,30 +164,48 @@ pub async fn retrieve_all_presets(configuration: &configuration::Configuration) let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::PresetsRetrieveSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::PresetsRetrieveSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::PresetsRetrieveSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::PresetsRetrieveSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve the details of a preset, given it's name. -pub async fn retrieve_preset(configuration: &configuration::Configuration, params: RetrievePresetParams) -> Result> { - - let uri_str = format!("{}/presets/{presetId}", configuration.base_path, presetId=crate::apis::urlencode(params.preset_id)); +pub async fn retrieve_preset( + configuration: &configuration::Configuration, + params: RetrievePresetParams, +) -> Result> { + let uri_str = format!( + "{}/presets/{presetId}", + configuration.base_path, + presetId = crate::apis::urlencode(params.preset_id) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -189,30 +225,48 @@ pub async fn retrieve_preset(configuration: &configuration::Configuration, param let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::PresetSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::PresetSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::PresetSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::PresetSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Create or update an existing preset. -pub async fn upsert_preset(configuration: &configuration::Configuration, params: UpsertPresetParams) -> Result> { - - let uri_str = format!("{}/presets/{presetId}", configuration.base_path, presetId=crate::apis::urlencode(params.preset_id)); +pub async fn upsert_preset( + configuration: &configuration::Configuration, + params: UpsertPresetParams, +) -> Result> { + let uri_str = format!( + "{}/presets/{presetId}", + configuration.base_path, + presetId = crate::apis::urlencode(params.preset_id) + ); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -233,13 +287,24 @@ pub async fn upsert_preset(configuration: &configuration::Configuration, params: let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::PresetSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::PresetSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::PresetSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::PresetSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } - diff --git a/typesense_codegen/src/apis/stemming_api.rs b/typesense_codegen/src/apis/stemming_api.rs index 847f35b..b477615 100644 --- a/typesense_codegen/src/apis/stemming_api.rs +++ b/typesense_codegen/src/apis/stemming_api.rs @@ -4,21 +4,20 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ - +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`get_stemming_dictionary`] #[derive(Clone, Debug)] pub struct GetStemmingDictionaryParams { /// The ID of the dictionary to retrieve - pub dictionary_id: String + pub dictionary_id: String, } /// struct for passing parameters to the method [`import_stemming_dictionary`] @@ -27,10 +26,9 @@ pub struct ImportStemmingDictionaryParams { /// The ID to assign to the dictionary pub id: String, /// The JSONL file containing word mappings - pub body: String + pub body: String, } - /// struct for typed errors of method [`get_stemming_dictionary`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -54,21 +52,26 @@ pub enum ListStemmingDictionariesError { UnknownValue(serde_json::Value), } - /// Fetch details of a specific stemming dictionary. -pub async fn get_stemming_dictionary(configuration: &configuration::Configuration, params: GetStemmingDictionaryParams) -> Result> { - - let uri_str = format!("{}/stemming/dictionaries/{dictionaryId}", configuration.base_path, dictionaryId=crate::apis::urlencode(params.dictionary_id)); +pub async fn get_stemming_dictionary( + configuration: &configuration::Configuration, + params: GetStemmingDictionaryParams, +) -> Result> { + let uri_str = format!( + "{}/stemming/dictionaries/{dictionaryId}", + configuration.base_path, + dictionaryId = crate::apis::urlencode(params.dictionary_id) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -88,31 +91,47 @@ pub async fn get_stemming_dictionary(configuration: &configuration::Configuratio let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::StemmingDictionary`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::StemmingDictionary`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::StemmingDictionary`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::StemmingDictionary`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Upload a JSONL file containing word mappings to create or update a stemming dictionary. -pub async fn import_stemming_dictionary(configuration: &configuration::Configuration, params: ImportStemmingDictionaryParams) -> Result> { - +pub async fn import_stemming_dictionary( + configuration: &configuration::Configuration, + params: ImportStemmingDictionaryParams, +) -> Result> { let uri_str = format!("{}/stemming/dictionaries/import", configuration.base_path); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); req_builder = req_builder.query(&[("id", ¶ms.id.to_string())]); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -133,19 +152,32 @@ pub async fn import_stemming_dictionary(configuration: &configuration::Configura let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `String`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `String`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `String`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `String`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve a list of all available stemming dictionaries. -pub async fn list_stemming_dictionaries(configuration: &configuration::Configuration) -> Result> { - +pub async fn list_stemming_dictionaries( + configuration: &configuration::Configuration, +) -> Result> { let uri_str = format!("{}/stemming/dictionaries", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -153,10 +185,10 @@ pub async fn list_stemming_dictionaries(configuration: &configuration::Configura req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -176,13 +208,24 @@ pub async fn list_stemming_dictionaries(configuration: &configuration::Configura let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ListStemmingDictionaries200Response`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ListStemmingDictionaries200Response`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::ListStemmingDictionaries200Response`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::ListStemmingDictionaries200Response`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } - diff --git a/typesense_codegen/src/apis/stopwords_api.rs b/typesense_codegen/src/apis/stopwords_api.rs index d80744a..c74b98d 100644 --- a/typesense_codegen/src/apis/stopwords_api.rs +++ b/typesense_codegen/src/apis/stopwords_api.rs @@ -4,28 +4,27 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ - +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`delete_stopwords_set`] #[derive(Clone, Debug)] pub struct DeleteStopwordsSetParams { /// The ID of the stopwords set to delete. - pub set_id: String + pub set_id: String, } /// struct for passing parameters to the method [`retrieve_stopwords_set`] #[derive(Clone, Debug)] pub struct RetrieveStopwordsSetParams { /// The ID of the stopwords set to retrieve. - pub set_id: String + pub set_id: String, } /// struct for passing parameters to the method [`upsert_stopwords_set`] @@ -34,10 +33,9 @@ pub struct UpsertStopwordsSetParams { /// The ID of the stopwords set to upsert. pub set_id: String, /// The stopwords set to upsert. - pub stopwords_set_upsert_schema: models::StopwordsSetUpsertSchema + pub stopwords_set_upsert_schema: models::StopwordsSetUpsertSchema, } - /// struct for typed errors of method [`delete_stopwords_set`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -69,21 +67,28 @@ pub enum UpsertStopwordsSetError { UnknownValue(serde_json::Value), } - /// Permanently deletes a stopwords set, given it's name. -pub async fn delete_stopwords_set(configuration: &configuration::Configuration, params: DeleteStopwordsSetParams) -> Result> { - - let uri_str = format!("{}/stopwords/{setId}", configuration.base_path, setId=crate::apis::urlencode(params.set_id)); - let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_stopwords_set( + configuration: &configuration::Configuration, + params: DeleteStopwordsSetParams, +) -> Result> { + let uri_str = format!( + "{}/stopwords/{setId}", + configuration.base_path, + setId = crate::apis::urlencode(params.set_id) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -103,30 +108,48 @@ pub async fn delete_stopwords_set(configuration: &configuration::Configuration, let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::DeleteStopwordsSet200Response`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::DeleteStopwordsSet200Response`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::DeleteStopwordsSet200Response`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::DeleteStopwordsSet200Response`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve the details of a stopwords set, given it's name. -pub async fn retrieve_stopwords_set(configuration: &configuration::Configuration, params: RetrieveStopwordsSetParams) -> Result> { - - let uri_str = format!("{}/stopwords/{setId}", configuration.base_path, setId=crate::apis::urlencode(params.set_id)); +pub async fn retrieve_stopwords_set( + configuration: &configuration::Configuration, + params: RetrieveStopwordsSetParams, +) -> Result> { + let uri_str = format!( + "{}/stopwords/{setId}", + configuration.base_path, + setId = crate::apis::urlencode(params.set_id) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -146,19 +169,32 @@ pub async fn retrieve_stopwords_set(configuration: &configuration::Configuration let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::StopwordsSetRetrieveSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::StopwordsSetRetrieveSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::StopwordsSetRetrieveSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::StopwordsSetRetrieveSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve the details of all stopwords sets -pub async fn retrieve_stopwords_sets(configuration: &configuration::Configuration) -> Result> { - +pub async fn retrieve_stopwords_sets( + configuration: &configuration::Configuration, +) -> Result> { let uri_str = format!("{}/stopwords", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -166,10 +202,10 @@ pub async fn retrieve_stopwords_sets(configuration: &configuration::Configuratio req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -189,30 +225,48 @@ pub async fn retrieve_stopwords_sets(configuration: &configuration::Configuratio let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::StopwordsSetsRetrieveAllSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::StopwordsSetsRetrieveAllSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::StopwordsSetsRetrieveAllSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::StopwordsSetsRetrieveAllSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// When an analytics rule is created, we give it a name and describe the type, the source collections and the destination collection. -pub async fn upsert_stopwords_set(configuration: &configuration::Configuration, params: UpsertStopwordsSetParams) -> Result> { - - let uri_str = format!("{}/stopwords/{setId}", configuration.base_path, setId=crate::apis::urlencode(params.set_id)); +pub async fn upsert_stopwords_set( + configuration: &configuration::Configuration, + params: UpsertStopwordsSetParams, +) -> Result> { + let uri_str = format!( + "{}/stopwords/{setId}", + configuration.base_path, + setId = crate::apis::urlencode(params.set_id) + ); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -233,13 +287,24 @@ pub async fn upsert_stopwords_set(configuration: &configuration::Configuration, let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::StopwordsSetSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::StopwordsSetSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::StopwordsSetSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::StopwordsSetSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } - diff --git a/typesense_codegen/src/apis/synonyms_api.rs b/typesense_codegen/src/apis/synonyms_api.rs index 27b259a..79ccdfc 100644 --- a/typesense_codegen/src/apis/synonyms_api.rs +++ b/typesense_codegen/src/apis/synonyms_api.rs @@ -4,28 +4,27 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ - +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`delete_synonym_set`] #[derive(Clone, Debug)] pub struct DeleteSynonymSetParams { /// The name of the synonym set to delete - pub synonym_set_name: String + pub synonym_set_name: String, } /// struct for passing parameters to the method [`retrieve_synonym_set`] #[derive(Clone, Debug)] pub struct RetrieveSynonymSetParams { /// The name of the synonym set to retrieve - pub synonym_set_name: String + pub synonym_set_name: String, } /// struct for passing parameters to the method [`upsert_synonym_set`] @@ -34,10 +33,9 @@ pub struct UpsertSynonymSetParams { /// The name of the synonym set to create/update pub synonym_set_name: String, /// The synonym set to be created/updated - pub synonym_set_create_schema: models::SynonymSetCreateSchema + pub synonym_set_create_schema: models::SynonymSetCreateSchema, } - /// struct for typed errors of method [`delete_synonym_set`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -69,21 +67,28 @@ pub enum UpsertSynonymSetError { UnknownValue(serde_json::Value), } - /// Delete a specific synonym set by its name -pub async fn delete_synonym_set(configuration: &configuration::Configuration, params: DeleteSynonymSetParams) -> Result> { - - let uri_str = format!("{}/synonym_sets/{synonymSetName}", configuration.base_path, synonymSetName=crate::apis::urlencode(params.synonym_set_name)); - let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_synonym_set( + configuration: &configuration::Configuration, + params: DeleteSynonymSetParams, +) -> Result> { + let uri_str = format!( + "{}/synonym_sets/{synonymSetName}", + configuration.base_path, + synonymSetName = crate::apis::urlencode(params.synonym_set_name) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -103,30 +108,48 @@ pub async fn delete_synonym_set(configuration: &configuration::Configuration, pa let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SynonymSetDeleteSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SynonymSetDeleteSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SynonymSetDeleteSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SynonymSetDeleteSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve a specific synonym set by its name -pub async fn retrieve_synonym_set(configuration: &configuration::Configuration, params: RetrieveSynonymSetParams) -> Result> { - - let uri_str = format!("{}/synonym_sets/{synonymSetName}", configuration.base_path, synonymSetName=crate::apis::urlencode(params.synonym_set_name)); +pub async fn retrieve_synonym_set( + configuration: &configuration::Configuration, + params: RetrieveSynonymSetParams, +) -> Result> { + let uri_str = format!( + "{}/synonym_sets/{synonymSetName}", + configuration.base_path, + synonymSetName = crate::apis::urlencode(params.synonym_set_name) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -146,19 +169,32 @@ pub async fn retrieve_synonym_set(configuration: &configuration::Configuration, let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SynonymSetCreateSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SynonymSetCreateSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SynonymSetCreateSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SynonymSetCreateSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve all synonym sets -pub async fn retrieve_synonym_sets(configuration: &configuration::Configuration) -> Result, Error> { - +pub async fn retrieve_synonym_sets( + configuration: &configuration::Configuration, +) -> Result, Error> { let uri_str = format!("{}/synonym_sets", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -166,10 +202,10 @@ pub async fn retrieve_synonym_sets(configuration: &configuration::Configuration) req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -189,30 +225,48 @@ pub async fn retrieve_synonym_sets(configuration: &configuration::Configuration) let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `Vec`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `Vec`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Create or update a synonym set with the given name -pub async fn upsert_synonym_set(configuration: &configuration::Configuration, params: UpsertSynonymSetParams) -> Result> { - - let uri_str = format!("{}/synonym_sets/{synonymSetName}", configuration.base_path, synonymSetName=crate::apis::urlencode(params.synonym_set_name)); +pub async fn upsert_synonym_set( + configuration: &configuration::Configuration, + params: UpsertSynonymSetParams, +) -> Result> { + let uri_str = format!( + "{}/synonym_sets/{synonymSetName}", + configuration.base_path, + synonymSetName = crate::apis::urlencode(params.synonym_set_name) + ); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); + let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + Some(ref prefix) => format!("{prefix} {key}"), + None => key.clone(), }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -233,13 +287,24 @@ pub async fn upsert_synonym_set(configuration: &configuration::Configuration, pa let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SynonymSetSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SynonymSetSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SynonymSetSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SynonymSetSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } - diff --git a/typesense_codegen/src/models/analytics_event.rs b/typesense_codegen/src/models/analytics_event.rs index 4559896..7ab05e0 100644 --- a/typesense_codegen/src/models/analytics_event.rs +++ b/typesense_codegen/src/models/analytics_event.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -24,7 +24,11 @@ pub struct AnalyticsEvent { } impl AnalyticsEvent { - pub fn new(name: String, event_type: String, data: models::AnalyticsEventData) -> AnalyticsEvent{ + pub fn new( + name: String, + event_type: String, + data: models::AnalyticsEventData, + ) -> AnalyticsEvent { AnalyticsEvent { name, event_type, @@ -32,4 +36,3 @@ impl AnalyticsEvent { } } } - diff --git a/typesense_codegen/src/models/analytics_event_create_response.rs b/typesense_codegen/src/models/analytics_event_create_response.rs index c15ca25..2018290 100644 --- a/typesense_codegen/src/models/analytics_event_create_response.rs +++ b/typesense_codegen/src/models/analytics_event_create_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +18,7 @@ pub struct AnalyticsEventCreateResponse { } impl AnalyticsEventCreateResponse { - pub fn new(ok: bool) -> AnalyticsEventCreateResponse{ - AnalyticsEventCreateResponse { - ok, - } + pub fn new(ok: bool) -> AnalyticsEventCreateResponse { + AnalyticsEventCreateResponse { ok } } } - diff --git a/typesense_codegen/src/models/analytics_event_data.rs b/typesense_codegen/src/models/analytics_event_data.rs index 75b44f9..7c28241 100644 --- a/typesense_codegen/src/models/analytics_event_data.rs +++ b/typesense_codegen/src/models/analytics_event_data.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -28,7 +28,7 @@ pub struct AnalyticsEventData { impl AnalyticsEventData { /// Event payload - pub fn new() -> AnalyticsEventData{ + pub fn new() -> AnalyticsEventData { AnalyticsEventData { user_id: None, doc_id: None, @@ -38,4 +38,3 @@ impl AnalyticsEventData { } } } - diff --git a/typesense_codegen/src/models/analytics_events_response.rs b/typesense_codegen/src/models/analytics_events_response.rs index fafd98b..a0de4e0 100644 --- a/typesense_codegen/src/models/analytics_events_response.rs +++ b/typesense_codegen/src/models/analytics_events_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +18,7 @@ pub struct AnalyticsEventsResponse { } impl AnalyticsEventsResponse { - pub fn new(events: Vec) -> AnalyticsEventsResponse{ - AnalyticsEventsResponse { - events, - } + pub fn new(events: Vec) -> AnalyticsEventsResponse { + AnalyticsEventsResponse { events } } } - diff --git a/typesense_codegen/src/models/analytics_events_response_events_inner.rs b/typesense_codegen/src/models/analytics_events_response_events_inner.rs index 93f9dfc..9744a20 100644 --- a/typesense_codegen/src/models/analytics_events_response_events_inner.rs +++ b/typesense_codegen/src/models/analytics_events_response_events_inner.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -32,7 +32,7 @@ pub struct AnalyticsEventsResponseEventsInner { } impl AnalyticsEventsResponseEventsInner { - pub fn new() -> AnalyticsEventsResponseEventsInner{ + pub fn new() -> AnalyticsEventsResponseEventsInner { AnalyticsEventsResponseEventsInner { name: None, event_type: None, @@ -45,4 +45,3 @@ impl AnalyticsEventsResponseEventsInner { } } } - diff --git a/typesense_codegen/src/models/analytics_rule.rs b/typesense_codegen/src/models/analytics_rule.rs index cc15a1d..4c01197 100644 --- a/typesense_codegen/src/models/analytics_rule.rs +++ b/typesense_codegen/src/models/analytics_rule.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -28,7 +28,12 @@ pub struct AnalyticsRule { } impl AnalyticsRule { - pub fn new(name: String, r#type: Type, collection: String, event_type: String) -> AnalyticsRule{ + pub fn new( + name: String, + r#type: Type, + collection: String, + event_type: String, + ) -> AnalyticsRule { AnalyticsRule { name, r#type, @@ -39,7 +44,7 @@ impl AnalyticsRule { } } } -/// +/// #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum Type { #[serde(rename = "popular_queries")] @@ -57,4 +62,3 @@ impl Default for Type { Self::PopularQueries } } - diff --git a/typesense_codegen/src/models/analytics_rule_create.rs b/typesense_codegen/src/models/analytics_rule_create.rs index 9373230..b9f8993 100644 --- a/typesense_codegen/src/models/analytics_rule_create.rs +++ b/typesense_codegen/src/models/analytics_rule_create.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -28,7 +28,12 @@ pub struct AnalyticsRuleCreate { } impl AnalyticsRuleCreate { - pub fn new(name: String, r#type: Type, collection: String, event_type: String) -> AnalyticsRuleCreate{ + pub fn new( + name: String, + r#type: Type, + collection: String, + event_type: String, + ) -> AnalyticsRuleCreate { AnalyticsRuleCreate { name, r#type, @@ -39,7 +44,7 @@ impl AnalyticsRuleCreate { } } } -/// +/// #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum Type { #[serde(rename = "popular_queries")] @@ -57,4 +62,3 @@ impl Default for Type { Self::PopularQueries } } - diff --git a/typesense_codegen/src/models/analytics_rule_create_params.rs b/typesense_codegen/src/models/analytics_rule_create_params.rs index de7cf5a..6127dd3 100644 --- a/typesense_codegen/src/models/analytics_rule_create_params.rs +++ b/typesense_codegen/src/models/analytics_rule_create_params.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -13,11 +13,17 @@ use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct AnalyticsRuleCreateParams { - #[serde(rename = "destination_collection", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "destination_collection", + skip_serializing_if = "Option::is_none" + )] pub destination_collection: Option, #[serde(rename = "limit", skip_serializing_if = "Option::is_none")] pub limit: Option, - #[serde(rename = "capture_search_requests", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "capture_search_requests", + skip_serializing_if = "Option::is_none" + )] pub capture_search_requests: Option, #[serde(rename = "meta_fields", skip_serializing_if = "Option::is_none")] pub meta_fields: Option>, @@ -30,7 +36,7 @@ pub struct AnalyticsRuleCreateParams { } impl AnalyticsRuleCreateParams { - pub fn new() -> AnalyticsRuleCreateParams{ + pub fn new() -> AnalyticsRuleCreateParams { AnalyticsRuleCreateParams { destination_collection: None, limit: None, @@ -42,4 +48,3 @@ impl AnalyticsRuleCreateParams { } } } - diff --git a/typesense_codegen/src/models/analytics_rule_update.rs b/typesense_codegen/src/models/analytics_rule_update.rs index 66ad385..3a42cc4 100644 --- a/typesense_codegen/src/models/analytics_rule_update.rs +++ b/typesense_codegen/src/models/analytics_rule_update.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -24,7 +24,7 @@ pub struct AnalyticsRuleUpdate { impl AnalyticsRuleUpdate { /// Fields allowed to update on an analytics rule - pub fn new() -> AnalyticsRuleUpdate{ + pub fn new() -> AnalyticsRuleUpdate { AnalyticsRuleUpdate { name: None, rule_tag: None, @@ -32,4 +32,3 @@ impl AnalyticsRuleUpdate { } } } - diff --git a/typesense_codegen/src/models/analytics_status.rs b/typesense_codegen/src/models/analytics_status.rs index 9d1b6bf..ee3f151 100644 --- a/typesense_codegen/src/models/analytics_status.rs +++ b/typesense_codegen/src/models/analytics_status.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -13,15 +13,24 @@ use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct AnalyticsStatus { - #[serde(rename = "popular_prefix_queries", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "popular_prefix_queries", + skip_serializing_if = "Option::is_none" + )] pub popular_prefix_queries: Option, - #[serde(rename = "nohits_prefix_queries", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "nohits_prefix_queries", + skip_serializing_if = "Option::is_none" + )] pub nohits_prefix_queries: Option, #[serde(rename = "log_prefix_queries", skip_serializing_if = "Option::is_none")] pub log_prefix_queries: Option, #[serde(rename = "query_log_events", skip_serializing_if = "Option::is_none")] pub query_log_events: Option, - #[serde(rename = "query_counter_events", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "query_counter_events", + skip_serializing_if = "Option::is_none" + )] pub query_counter_events: Option, #[serde(rename = "doc_log_events", skip_serializing_if = "Option::is_none")] pub doc_log_events: Option, @@ -30,7 +39,7 @@ pub struct AnalyticsStatus { } impl AnalyticsStatus { - pub fn new() -> AnalyticsStatus{ + pub fn new() -> AnalyticsStatus { AnalyticsStatus { popular_prefix_queries: None, nohits_prefix_queries: None, @@ -42,4 +51,3 @@ impl AnalyticsStatus { } } } - diff --git a/typesense_codegen/src/models/api_key.rs b/typesense_codegen/src/models/api_key.rs index f108ead..511f8b9 100644 --- a/typesense_codegen/src/models/api_key.rs +++ b/typesense_codegen/src/models/api_key.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -30,7 +30,7 @@ pub struct ApiKey { } impl ApiKey { - pub fn new(description: String, actions: Vec, collections: Vec) -> ApiKey{ + pub fn new(description: String, actions: Vec, collections: Vec) -> ApiKey { ApiKey { value: None, description, @@ -42,4 +42,3 @@ impl ApiKey { } } } - diff --git a/typesense_codegen/src/models/api_key_delete_response.rs b/typesense_codegen/src/models/api_key_delete_response.rs index c12440d..b9b453e 100644 --- a/typesense_codegen/src/models/api_key_delete_response.rs +++ b/typesense_codegen/src/models/api_key_delete_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,10 +19,7 @@ pub struct ApiKeyDeleteResponse { } impl ApiKeyDeleteResponse { - pub fn new(id: i64) -> ApiKeyDeleteResponse{ - ApiKeyDeleteResponse { - id, - } + pub fn new(id: i64) -> ApiKeyDeleteResponse { + ApiKeyDeleteResponse { id } } } - diff --git a/typesense_codegen/src/models/api_key_schema.rs b/typesense_codegen/src/models/api_key_schema.rs index 3e8c2ab..095e5ec 100644 --- a/typesense_codegen/src/models/api_key_schema.rs +++ b/typesense_codegen/src/models/api_key_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -26,7 +26,11 @@ pub struct ApiKeySchema { } impl ApiKeySchema { - pub fn new(description: String, actions: Vec, collections: Vec) -> ApiKeySchema{ + pub fn new( + description: String, + actions: Vec, + collections: Vec, + ) -> ApiKeySchema { ApiKeySchema { value: None, description, @@ -36,4 +40,3 @@ impl ApiKeySchema { } } } - diff --git a/typesense_codegen/src/models/api_keys_response.rs b/typesense_codegen/src/models/api_keys_response.rs index ca7686c..784a6bf 100644 --- a/typesense_codegen/src/models/api_keys_response.rs +++ b/typesense_codegen/src/models/api_keys_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +18,7 @@ pub struct ApiKeysResponse { } impl ApiKeysResponse { - pub fn new(keys: Vec) -> ApiKeysResponse{ - ApiKeysResponse { - keys, - } + pub fn new(keys: Vec) -> ApiKeysResponse { + ApiKeysResponse { keys } } } - diff --git a/typesense_codegen/src/models/api_response.rs b/typesense_codegen/src/models/api_response.rs index 08c2c11..0a27c4f 100644 --- a/typesense_codegen/src/models/api_response.rs +++ b/typesense_codegen/src/models/api_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +18,7 @@ pub struct ApiResponse { } impl ApiResponse { - pub fn new(message: String) -> ApiResponse{ - ApiResponse { - message, - } + pub fn new(message: String) -> ApiResponse { + ApiResponse { message } } } - diff --git a/typesense_codegen/src/models/api_stats_response.rs b/typesense_codegen/src/models/api_stats_response.rs index d8d2933..c35c77a 100644 --- a/typesense_codegen/src/models/api_stats_response.rs +++ b/typesense_codegen/src/models/api_stats_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -15,34 +15,58 @@ use serde::{Deserialize, Serialize}; pub struct ApiStatsResponse { #[serde(rename = "delete_latency_ms", skip_serializing_if = "Option::is_none")] pub delete_latency_ms: Option, - #[serde(rename = "delete_requests_per_second", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "delete_requests_per_second", + skip_serializing_if = "Option::is_none" + )] pub delete_requests_per_second: Option, #[serde(rename = "import_latency_ms", skip_serializing_if = "Option::is_none")] pub import_latency_ms: Option, - #[serde(rename = "import_requests_per_second", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "import_requests_per_second", + skip_serializing_if = "Option::is_none" + )] pub import_requests_per_second: Option, #[serde(rename = "latency_ms", skip_serializing_if = "Option::is_none")] pub latency_ms: Option, - #[serde(rename = "overloaded_requests_per_second", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "overloaded_requests_per_second", + skip_serializing_if = "Option::is_none" + )] pub overloaded_requests_per_second: Option, - #[serde(rename = "pending_write_batches", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "pending_write_batches", + skip_serializing_if = "Option::is_none" + )] pub pending_write_batches: Option, - #[serde(rename = "requests_per_second", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "requests_per_second", + skip_serializing_if = "Option::is_none" + )] pub requests_per_second: Option, #[serde(rename = "search_latency_ms", skip_serializing_if = "Option::is_none")] pub search_latency_ms: Option, - #[serde(rename = "search_requests_per_second", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "search_requests_per_second", + skip_serializing_if = "Option::is_none" + )] pub search_requests_per_second: Option, - #[serde(rename = "total_requests_per_second", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "total_requests_per_second", + skip_serializing_if = "Option::is_none" + )] pub total_requests_per_second: Option, #[serde(rename = "write_latency_ms", skip_serializing_if = "Option::is_none")] pub write_latency_ms: Option, - #[serde(rename = "write_requests_per_second", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "write_requests_per_second", + skip_serializing_if = "Option::is_none" + )] pub write_requests_per_second: Option, } impl ApiStatsResponse { - pub fn new() -> ApiStatsResponse{ + pub fn new() -> ApiStatsResponse { ApiStatsResponse { delete_latency_ms: None, delete_requests_per_second: None, @@ -60,4 +84,3 @@ impl ApiStatsResponse { } } } - diff --git a/typesense_codegen/src/models/collection_alias.rs b/typesense_codegen/src/models/collection_alias.rs index f94f6a2..b5a61fe 100644 --- a/typesense_codegen/src/models/collection_alias.rs +++ b/typesense_codegen/src/models/collection_alias.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -22,11 +22,10 @@ pub struct CollectionAlias { } impl CollectionAlias { - pub fn new(name: String, collection_name: String) -> CollectionAlias{ + pub fn new(name: String, collection_name: String) -> CollectionAlias { CollectionAlias { name, collection_name, } } } - diff --git a/typesense_codegen/src/models/collection_alias_schema.rs b/typesense_codegen/src/models/collection_alias_schema.rs index 3a67ea0..b35d641 100644 --- a/typesense_codegen/src/models/collection_alias_schema.rs +++ b/typesense_codegen/src/models/collection_alias_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,10 +19,7 @@ pub struct CollectionAliasSchema { } impl CollectionAliasSchema { - pub fn new(collection_name: String) -> CollectionAliasSchema{ - CollectionAliasSchema { - collection_name, - } + pub fn new(collection_name: String) -> CollectionAliasSchema { + CollectionAliasSchema { collection_name } } } - diff --git a/typesense_codegen/src/models/collection_aliases_response.rs b/typesense_codegen/src/models/collection_aliases_response.rs index 0db53a1..3cf2d25 100644 --- a/typesense_codegen/src/models/collection_aliases_response.rs +++ b/typesense_codegen/src/models/collection_aliases_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +18,7 @@ pub struct CollectionAliasesResponse { } impl CollectionAliasesResponse { - pub fn new(aliases: Vec) -> CollectionAliasesResponse{ - CollectionAliasesResponse { - aliases, - } + pub fn new(aliases: Vec) -> CollectionAliasesResponse { + CollectionAliasesResponse { aliases } } } - diff --git a/typesense_codegen/src/models/collection_response.rs b/typesense_codegen/src/models/collection_response.rs index d664428..1039909 100644 --- a/typesense_codegen/src/models/collection_response.rs +++ b/typesense_codegen/src/models/collection_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -20,23 +20,29 @@ pub struct CollectionResponse { #[serde(rename = "fields")] pub fields: Vec, /// The name of an int32 / float field that determines the order in which the search results are ranked when a sort_by clause is not provided during searching. This field must indicate some kind of popularity. - #[serde(rename = "default_sorting_field", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "default_sorting_field", + skip_serializing_if = "Option::is_none" + )] pub default_sorting_field: Option, - /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. + /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. #[serde(rename = "token_separators", skip_serializing_if = "Option::is_none")] pub token_separators: Option>, /// List of synonym set names to associate with this collection #[serde(rename = "synonym_sets", skip_serializing_if = "Option::is_none")] pub synonym_sets: Option>, /// Enables experimental support at a collection level for nested object or object array fields. This field is only available if the Typesense server is version `0.24.0.rcn34` or later. - #[serde(rename = "enable_nested_fields", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "enable_nested_fields", + skip_serializing_if = "Option::is_none" + )] pub enable_nested_fields: Option, - /// List of symbols or special characters to be indexed. + /// List of symbols or special characters to be indexed. #[serde(rename = "symbols_to_index", skip_serializing_if = "Option::is_none")] pub symbols_to_index: Option>, #[serde(rename = "voice_query_model", skip_serializing_if = "Option::is_none")] pub voice_query_model: Option>, - /// Optional details about the collection, e.g., when it was created, who created it etc. + /// Optional details about the collection, e.g., when it was created, who created it etc. #[serde(rename = "metadata", skip_serializing_if = "Option::is_none")] pub metadata: Option, /// Number of documents in the collection @@ -48,7 +54,12 @@ pub struct CollectionResponse { } impl CollectionResponse { - pub fn new(name: String, fields: Vec, num_documents: i64, created_at: i64) -> CollectionResponse{ + pub fn new( + name: String, + fields: Vec, + num_documents: i64, + created_at: i64, + ) -> CollectionResponse { CollectionResponse { name, fields, @@ -64,4 +75,3 @@ impl CollectionResponse { } } } - diff --git a/typesense_codegen/src/models/collection_schema.rs b/typesense_codegen/src/models/collection_schema.rs index 7e2c754..b861bee 100644 --- a/typesense_codegen/src/models/collection_schema.rs +++ b/typesense_codegen/src/models/collection_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -22,29 +22,35 @@ pub struct CollectionSchema { #[serde(rename = "fields")] pub fields: Vec, /// The name of an int32 / float field that determines the order in which the search results are ranked when a sort_by clause is not provided during searching. This field must indicate some kind of popularity. - #[serde(rename = "default_sorting_field", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "default_sorting_field", + skip_serializing_if = "Option::is_none" + )] pub default_sorting_field: Option, - /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. + /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. #[serde(rename = "token_separators", skip_serializing_if = "Option::is_none")] pub token_separators: Option>, /// List of synonym set names to associate with this collection #[serde(rename = "synonym_sets", skip_serializing_if = "Option::is_none")] pub synonym_sets: Option>, /// Enables experimental support at a collection level for nested object or object array fields. This field is only available if the Typesense server is version `0.24.0.rcn34` or later. - #[serde(rename = "enable_nested_fields", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "enable_nested_fields", + skip_serializing_if = "Option::is_none" + )] pub enable_nested_fields: Option, - /// List of symbols or special characters to be indexed. + /// List of symbols or special characters to be indexed. #[serde(rename = "symbols_to_index", skip_serializing_if = "Option::is_none")] pub symbols_to_index: Option>, #[serde(rename = "voice_query_model", skip_serializing_if = "Option::is_none")] pub voice_query_model: Option>, - /// Optional details about the collection, e.g., when it was created, who created it etc. + /// Optional details about the collection, e.g., when it was created, who created it etc. #[serde(rename = "metadata", skip_serializing_if = "Option::is_none")] pub metadata: Option, } impl CollectionSchema { - pub fn new(name: String, fields: Vec) -> CollectionSchema{ + pub fn new(name: String, fields: Vec) -> CollectionSchema { CollectionSchema { name, fields, @@ -58,4 +64,3 @@ impl CollectionSchema { } } } - diff --git a/typesense_codegen/src/models/collection_update_schema.rs b/typesense_codegen/src/models/collection_update_schema.rs index ca45a78..27a4d09 100644 --- a/typesense_codegen/src/models/collection_update_schema.rs +++ b/typesense_codegen/src/models/collection_update_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,13 +19,13 @@ pub struct CollectionUpdateSchema { /// List of synonym set names to associate with this collection #[serde(rename = "synonym_sets", skip_serializing_if = "Option::is_none")] pub synonym_sets: Option>, - /// Optional details about the collection, e.g., when it was created, who created it etc. + /// Optional details about the collection, e.g., when it was created, who created it etc. #[serde(rename = "metadata", skip_serializing_if = "Option::is_none")] pub metadata: Option, } impl CollectionUpdateSchema { - pub fn new(fields: Vec) -> CollectionUpdateSchema{ + pub fn new(fields: Vec) -> CollectionUpdateSchema { CollectionUpdateSchema { fields, synonym_sets: None, @@ -33,4 +33,3 @@ impl CollectionUpdateSchema { } } } - diff --git a/typesense_codegen/src/models/conversation_model_create_schema.rs b/typesense_codegen/src/models/conversation_model_create_schema.rs index 3a2ed5b..fc587c3 100644 --- a/typesense_codegen/src/models/conversation_model_create_schema.rs +++ b/typesense_codegen/src/models/conversation_model_create_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -31,10 +31,10 @@ pub struct ConversationModelCreateSchema { /// The system prompt that contains special instructions to the LLM #[serde(rename = "system_prompt", skip_serializing_if = "Option::is_none")] pub system_prompt: Option, - /// Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) + /// Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) #[serde(rename = "ttl", skip_serializing_if = "Option::is_none")] pub ttl: Option, - /// The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. + /// The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. #[serde(rename = "max_bytes")] pub max_bytes: i32, /// URL of vLLM service @@ -43,7 +43,11 @@ pub struct ConversationModelCreateSchema { } impl ConversationModelCreateSchema { - pub fn new(model_name: String, history_collection: String, max_bytes: i32) -> ConversationModelCreateSchema{ + pub fn new( + model_name: String, + history_collection: String, + max_bytes: i32, + ) -> ConversationModelCreateSchema { ConversationModelCreateSchema { id: None, model_name, @@ -57,4 +61,3 @@ impl ConversationModelCreateSchema { } } } - diff --git a/typesense_codegen/src/models/conversation_model_schema.rs b/typesense_codegen/src/models/conversation_model_schema.rs index 828988d..1738f77 100644 --- a/typesense_codegen/src/models/conversation_model_schema.rs +++ b/typesense_codegen/src/models/conversation_model_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -31,10 +31,10 @@ pub struct ConversationModelSchema { /// The system prompt that contains special instructions to the LLM #[serde(rename = "system_prompt", skip_serializing_if = "Option::is_none")] pub system_prompt: Option, - /// Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) + /// Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) #[serde(rename = "ttl", skip_serializing_if = "Option::is_none")] pub ttl: Option, - /// The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. + /// The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. #[serde(rename = "max_bytes")] pub max_bytes: i32, /// URL of vLLM service @@ -43,7 +43,12 @@ pub struct ConversationModelSchema { } impl ConversationModelSchema { - pub fn new(id: String, model_name: String, history_collection: String, max_bytes: i32) -> ConversationModelSchema{ + pub fn new( + id: String, + model_name: String, + history_collection: String, + max_bytes: i32, + ) -> ConversationModelSchema { ConversationModelSchema { id, model_name, @@ -57,4 +62,3 @@ impl ConversationModelSchema { } } } - diff --git a/typesense_codegen/src/models/conversation_model_update_schema.rs b/typesense_codegen/src/models/conversation_model_update_schema.rs index 7ac5e40..1335019 100644 --- a/typesense_codegen/src/models/conversation_model_update_schema.rs +++ b/typesense_codegen/src/models/conversation_model_update_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -31,10 +31,10 @@ pub struct ConversationModelUpdateSchema { /// The system prompt that contains special instructions to the LLM #[serde(rename = "system_prompt", skip_serializing_if = "Option::is_none")] pub system_prompt: Option, - /// Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) + /// Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) #[serde(rename = "ttl", skip_serializing_if = "Option::is_none")] pub ttl: Option, - /// The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. + /// The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. #[serde(rename = "max_bytes", skip_serializing_if = "Option::is_none")] pub max_bytes: Option, /// URL of vLLM service @@ -43,7 +43,7 @@ pub struct ConversationModelUpdateSchema { } impl ConversationModelUpdateSchema { - pub fn new() -> ConversationModelUpdateSchema{ + pub fn new() -> ConversationModelUpdateSchema { ConversationModelUpdateSchema { id: None, model_name: None, @@ -57,4 +57,3 @@ impl ConversationModelUpdateSchema { } } } - diff --git a/typesense_codegen/src/models/create_analytics_rule_200_response.rs b/typesense_codegen/src/models/create_analytics_rule_200_response.rs index 6d45dca..80053ca 100644 --- a/typesense_codegen/src/models/create_analytics_rule_200_response.rs +++ b/typesense_codegen/src/models/create_analytics_rule_200_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -23,7 +23,7 @@ impl Default for CreateAnalyticsRule200Response { Self::AnalyticsRule(Default::default()) } } -/// +/// #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum Type { #[serde(rename = "popular_queries")] @@ -41,4 +41,3 @@ impl Default for Type { Self::PopularQueries } } - diff --git a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs index 8e773e2..bb9f001 100644 --- a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs +++ b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -30,7 +30,12 @@ pub struct CreateAnalyticsRule200ResponseOneOfInner { } impl CreateAnalyticsRule200ResponseOneOfInner { - pub fn new(name: String, r#type: Type, collection: String, event_type: String) -> CreateAnalyticsRule200ResponseOneOfInner{ + pub fn new( + name: String, + r#type: Type, + collection: String, + event_type: String, + ) -> CreateAnalyticsRule200ResponseOneOfInner { CreateAnalyticsRule200ResponseOneOfInner { name, r#type, @@ -42,7 +47,7 @@ impl CreateAnalyticsRule200ResponseOneOfInner { } } } -/// +/// #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum Type { #[serde(rename = "popular_queries")] @@ -60,4 +65,3 @@ impl Default for Type { Self::PopularQueries } } - diff --git a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs index 12f7422..08500ef 100644 --- a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs +++ b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +18,7 @@ pub struct CreateAnalyticsRule200ResponseOneOfInnerAnyOf { } impl CreateAnalyticsRule200ResponseOneOfInnerAnyOf { - pub fn new() -> CreateAnalyticsRule200ResponseOneOfInnerAnyOf{ - CreateAnalyticsRule200ResponseOneOfInnerAnyOf { - error: None, - } + pub fn new() -> CreateAnalyticsRule200ResponseOneOfInnerAnyOf { + CreateAnalyticsRule200ResponseOneOfInnerAnyOf { error: None } } } - diff --git a/typesense_codegen/src/models/create_analytics_rule_request.rs b/typesense_codegen/src/models/create_analytics_rule_request.rs index 597dec9..262570e 100644 --- a/typesense_codegen/src/models/create_analytics_rule_request.rs +++ b/typesense_codegen/src/models/create_analytics_rule_request.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -23,7 +23,7 @@ impl Default for CreateAnalyticsRuleRequest { Self::AnalyticsRuleCreate(Default::default()) } } -/// +/// #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum Type { #[serde(rename = "popular_queries")] @@ -41,4 +41,3 @@ impl Default for Type { Self::PopularQueries } } - diff --git a/typesense_codegen/src/models/debug_200_response.rs b/typesense_codegen/src/models/debug_200_response.rs index 0c88dd7..946d84e 100644 --- a/typesense_codegen/src/models/debug_200_response.rs +++ b/typesense_codegen/src/models/debug_200_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +18,7 @@ pub struct Debug200Response { } impl Debug200Response { - pub fn new() -> Debug200Response{ - Debug200Response { - version: None, - } + pub fn new() -> Debug200Response { + Debug200Response { version: None } } } - diff --git a/typesense_codegen/src/models/delete_documents_200_response.rs b/typesense_codegen/src/models/delete_documents_200_response.rs index 5779adf..169020c 100644 --- a/typesense_codegen/src/models/delete_documents_200_response.rs +++ b/typesense_codegen/src/models/delete_documents_200_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +18,7 @@ pub struct DeleteDocuments200Response { } impl DeleteDocuments200Response { - pub fn new(num_deleted: i32) -> DeleteDocuments200Response{ - DeleteDocuments200Response { - num_deleted, - } + pub fn new(num_deleted: i32) -> DeleteDocuments200Response { + DeleteDocuments200Response { num_deleted } } } - diff --git a/typesense_codegen/src/models/delete_documents_parameters.rs b/typesense_codegen/src/models/delete_documents_parameters.rs index 903d717..55e8241 100644 --- a/typesense_codegen/src/models/delete_documents_parameters.rs +++ b/typesense_codegen/src/models/delete_documents_parameters.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -26,7 +26,7 @@ pub struct DeleteDocumentsParameters { } impl DeleteDocumentsParameters { - pub fn new(filter_by: String) -> DeleteDocumentsParameters{ + pub fn new(filter_by: String) -> DeleteDocumentsParameters { DeleteDocumentsParameters { filter_by, batch_size: None, @@ -35,4 +35,3 @@ impl DeleteDocumentsParameters { } } } - diff --git a/typesense_codegen/src/models/delete_stopwords_set_200_response.rs b/typesense_codegen/src/models/delete_stopwords_set_200_response.rs index 87fa748..03b93ef 100644 --- a/typesense_codegen/src/models/delete_stopwords_set_200_response.rs +++ b/typesense_codegen/src/models/delete_stopwords_set_200_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +18,7 @@ pub struct DeleteStopwordsSet200Response { } impl DeleteStopwordsSet200Response { - pub fn new(id: String) -> DeleteStopwordsSet200Response{ - DeleteStopwordsSet200Response { - id, - } + pub fn new(id: String) -> DeleteStopwordsSet200Response { + DeleteStopwordsSet200Response { id } } } - diff --git a/typesense_codegen/src/models/dirty_values.rs b/typesense_codegen/src/models/dirty_values.rs index 5c3a422..8caeab9 100644 --- a/typesense_codegen/src/models/dirty_values.rs +++ b/typesense_codegen/src/models/dirty_values.rs @@ -4,14 +4,14 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ use crate::models; use serde::{Deserialize, Serialize}; -/// +/// #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum DirtyValues { #[serde(rename = "coerce_or_reject")] @@ -22,7 +22,6 @@ pub enum DirtyValues { Drop, #[serde(rename = "reject")] Reject, - } impl std::fmt::Display for DirtyValues { @@ -41,4 +40,3 @@ impl Default for DirtyValues { Self::CoerceOrReject } } - diff --git a/typesense_codegen/src/models/drop_tokens_mode.rs b/typesense_codegen/src/models/drop_tokens_mode.rs index 9769869..5b8ba01 100644 --- a/typesense_codegen/src/models/drop_tokens_mode.rs +++ b/typesense_codegen/src/models/drop_tokens_mode.rs @@ -4,15 +4,15 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ use crate::models; use serde::{Deserialize, Serialize}; -/// DropTokensMode : Dictates the direction in which the words in the query must be dropped when the original words in the query do not appear in any document. Values: right_to_left (default), left_to_right, both_sides:3 A note on both_sides:3 - for queries up to 3 tokens (words) in length, this mode will drop tokens from both sides and exhaustively rank all matching results. If query length is greater than 3 words, Typesense will just fallback to default behavior of right_to_left -/// Dictates the direction in which the words in the query must be dropped when the original words in the query do not appear in any document. Values: right_to_left (default), left_to_right, both_sides:3 A note on both_sides:3 - for queries up to 3 tokens (words) in length, this mode will drop tokens from both sides and exhaustively rank all matching results. If query length is greater than 3 words, Typesense will just fallback to default behavior of right_to_left +/// DropTokensMode : Dictates the direction in which the words in the query must be dropped when the original words in the query do not appear in any document. Values: right_to_left (default), left_to_right, both_sides:3 A note on both_sides:3 - for queries up to 3 tokens (words) in length, this mode will drop tokens from both sides and exhaustively rank all matching results. If query length is greater than 3 words, Typesense will just fallback to default behavior of right_to_left +/// Dictates the direction in which the words in the query must be dropped when the original words in the query do not appear in any document. Values: right_to_left (default), left_to_right, both_sides:3 A note on both_sides:3 - for queries up to 3 tokens (words) in length, this mode will drop tokens from both sides and exhaustively rank all matching results. If query length is greater than 3 words, Typesense will just fallback to default behavior of right_to_left #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum DropTokensMode { #[serde(rename = "right_to_left")] @@ -21,7 +21,6 @@ pub enum DropTokensMode { LeftToRight, #[serde(rename = "both_sides:3")] BothSidesColon3, - } impl std::fmt::Display for DropTokensMode { @@ -39,4 +38,3 @@ impl Default for DropTokensMode { Self::RightToLeft } } - diff --git a/typesense_codegen/src/models/export_documents_parameters.rs b/typesense_codegen/src/models/export_documents_parameters.rs index b1defbb..36984f8 100644 --- a/typesense_codegen/src/models/export_documents_parameters.rs +++ b/typesense_codegen/src/models/export_documents_parameters.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -25,7 +25,7 @@ pub struct ExportDocumentsParameters { } impl ExportDocumentsParameters { - pub fn new() -> ExportDocumentsParameters{ + pub fn new() -> ExportDocumentsParameters { ExportDocumentsParameters { filter_by: None, include_fields: None, @@ -33,4 +33,3 @@ impl ExportDocumentsParameters { } } } - diff --git a/typesense_codegen/src/models/facet_counts.rs b/typesense_codegen/src/models/facet_counts.rs index a56913a..d9cbdf3 100644 --- a/typesense_codegen/src/models/facet_counts.rs +++ b/typesense_codegen/src/models/facet_counts.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -22,7 +22,7 @@ pub struct FacetCounts { } impl FacetCounts { - pub fn new() -> FacetCounts{ + pub fn new() -> FacetCounts { FacetCounts { counts: None, field_name: None, @@ -30,4 +30,3 @@ impl FacetCounts { } } } - diff --git a/typesense_codegen/src/models/facet_counts_counts_inner.rs b/typesense_codegen/src/models/facet_counts_counts_inner.rs index 9b732a5..bc6ede2 100644 --- a/typesense_codegen/src/models/facet_counts_counts_inner.rs +++ b/typesense_codegen/src/models/facet_counts_counts_inner.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -24,7 +24,7 @@ pub struct FacetCountsCountsInner { } impl FacetCountsCountsInner { - pub fn new() -> FacetCountsCountsInner{ + pub fn new() -> FacetCountsCountsInner { FacetCountsCountsInner { count: None, highlighted: None, @@ -33,4 +33,3 @@ impl FacetCountsCountsInner { } } } - diff --git a/typesense_codegen/src/models/facet_counts_stats.rs b/typesense_codegen/src/models/facet_counts_stats.rs index 24a8e63..7f0d9dd 100644 --- a/typesense_codegen/src/models/facet_counts_stats.rs +++ b/typesense_codegen/src/models/facet_counts_stats.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -26,7 +26,7 @@ pub struct FacetCountsStats { } impl FacetCountsStats { - pub fn new() -> FacetCountsStats{ + pub fn new() -> FacetCountsStats { FacetCountsStats { max: None, min: None, @@ -36,4 +36,3 @@ impl FacetCountsStats { } } } - diff --git a/typesense_codegen/src/models/field.rs b/typesense_codegen/src/models/field.rs index b3fd4d7..39bacbb 100644 --- a/typesense_codegen/src/models/field.rs +++ b/typesense_codegen/src/models/field.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -31,32 +31,32 @@ pub struct Field { pub sort: Option, #[serde(rename = "infix", skip_serializing_if = "Option::is_none")] pub infix: Option, - /// Name of a field in another collection that should be linked to this collection so that it can be joined during query. + /// Name of a field in another collection that should be linked to this collection so that it can be joined during query. #[serde(rename = "reference", skip_serializing_if = "Option::is_none")] pub reference: Option, #[serde(rename = "num_dim", skip_serializing_if = "Option::is_none")] pub num_dim: Option, #[serde(rename = "drop", skip_serializing_if = "Option::is_none")] pub drop: Option, - /// When set to false, the field value will not be stored on disk. Default: true. + /// When set to false, the field value will not be stored on disk. Default: true. #[serde(rename = "store", skip_serializing_if = "Option::is_none")] pub store: Option, - /// The distance metric to be used for vector search. Default: `cosine`. You can also use `ip` for inner product. + /// The distance metric to be used for vector search. Default: `cosine`. You can also use `ip` for inner product. #[serde(rename = "vec_dist", skip_serializing_if = "Option::is_none")] pub vec_dist: Option, - /// Enables an index optimized for range filtering on numerical fields (e.g. rating:>3.5). Default: false. + /// Enables an index optimized for range filtering on numerical fields (e.g. rating:>3.5). Default: false. #[serde(rename = "range_index", skip_serializing_if = "Option::is_none")] pub range_index: Option, - /// Values are stemmed before indexing in-memory. Default: false. + /// Values are stemmed before indexing in-memory. Default: false. #[serde(rename = "stem", skip_serializing_if = "Option::is_none")] pub stem: Option, /// Name of the stemming dictionary to use for this field #[serde(rename = "stem_dictionary", skip_serializing_if = "Option::is_none")] pub stem_dictionary: Option, - /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. + /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. #[serde(rename = "token_separators", skip_serializing_if = "Option::is_none")] pub token_separators: Option>, - /// List of symbols or special characters to be indexed. + /// List of symbols or special characters to be indexed. #[serde(rename = "symbols_to_index", skip_serializing_if = "Option::is_none")] pub symbols_to_index: Option>, #[serde(rename = "embed", skip_serializing_if = "Option::is_none")] @@ -64,7 +64,7 @@ pub struct Field { } impl Field { - pub fn new(name: String, r#type: String) -> Field{ + pub fn new(name: String, r#type: String) -> Field { Field { name, r#type, @@ -88,4 +88,3 @@ impl Field { } } } - diff --git a/typesense_codegen/src/models/field_embed.rs b/typesense_codegen/src/models/field_embed.rs index 2b9b203..0e84fd9 100644 --- a/typesense_codegen/src/models/field_embed.rs +++ b/typesense_codegen/src/models/field_embed.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -20,11 +20,10 @@ pub struct FieldEmbed { } impl FieldEmbed { - pub fn new(from: Vec, model_config: models::FieldEmbedModelConfig) -> FieldEmbed{ + pub fn new(from: Vec, model_config: models::FieldEmbedModelConfig) -> FieldEmbed { FieldEmbed { from, model_config: Box::new(model_config), } } } - diff --git a/typesense_codegen/src/models/field_embed_model_config.rs b/typesense_codegen/src/models/field_embed_model_config.rs index 407e32f..ee40bea 100644 --- a/typesense_codegen/src/models/field_embed_model_config.rs +++ b/typesense_codegen/src/models/field_embed_model_config.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -36,7 +36,7 @@ pub struct FieldEmbedModelConfig { } impl FieldEmbedModelConfig { - pub fn new(model_name: String) -> FieldEmbedModelConfig{ + pub fn new(model_name: String) -> FieldEmbedModelConfig { FieldEmbedModelConfig { model_name, api_key: None, @@ -51,4 +51,3 @@ impl FieldEmbedModelConfig { } } } - diff --git a/typesense_codegen/src/models/get_collections_parameters.rs b/typesense_codegen/src/models/get_collections_parameters.rs index 01226a7..02497f6 100644 --- a/typesense_codegen/src/models/get_collections_parameters.rs +++ b/typesense_codegen/src/models/get_collections_parameters.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -16,7 +16,7 @@ pub struct GetCollectionsParameters { /// Comma-separated list of fields from the collection to exclude from the response #[serde(rename = "exclude_fields", skip_serializing_if = "Option::is_none")] pub exclude_fields: Option, - /// Number of collections to fetch. Default: returns all collections. + /// Number of collections to fetch. Default: returns all collections. #[serde(rename = "limit", skip_serializing_if = "Option::is_none")] pub limit: Option, /// Identifies the starting point to return collections when paginating. @@ -25,7 +25,7 @@ pub struct GetCollectionsParameters { } impl GetCollectionsParameters { - pub fn new() -> GetCollectionsParameters{ + pub fn new() -> GetCollectionsParameters { GetCollectionsParameters { exclude_fields: None, limit: None, @@ -33,4 +33,3 @@ impl GetCollectionsParameters { } } } - diff --git a/typesense_codegen/src/models/health_status.rs b/typesense_codegen/src/models/health_status.rs index 82a4489..66cdf6b 100644 --- a/typesense_codegen/src/models/health_status.rs +++ b/typesense_codegen/src/models/health_status.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +18,7 @@ pub struct HealthStatus { } impl HealthStatus { - pub fn new(ok: bool) -> HealthStatus{ - HealthStatus { - ok, - } + pub fn new(ok: bool) -> HealthStatus { + HealthStatus { ok } } } - diff --git a/typesense_codegen/src/models/import_documents_parameters.rs b/typesense_codegen/src/models/import_documents_parameters.rs index 0b7abab..e17494a 100644 --- a/typesense_codegen/src/models/import_documents_parameters.rs +++ b/typesense_codegen/src/models/import_documents_parameters.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,7 +18,10 @@ pub struct ImportDocumentsParameters { /// Returning the id of the imported documents. If you want the import response to return the ingested document's id in the response, you can use the return_id parameter. #[serde(rename = "return_id", skip_serializing_if = "Option::is_none")] pub return_id: Option, - #[serde(rename = "remote_embedding_batch_size", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "remote_embedding_batch_size", + skip_serializing_if = "Option::is_none" + )] pub remote_embedding_batch_size: Option, #[serde(rename = "return_doc", skip_serializing_if = "Option::is_none")] pub return_doc: Option, @@ -29,7 +32,7 @@ pub struct ImportDocumentsParameters { } impl ImportDocumentsParameters { - pub fn new() -> ImportDocumentsParameters{ + pub fn new() -> ImportDocumentsParameters { ImportDocumentsParameters { batch_size: None, return_id: None, @@ -40,4 +43,3 @@ impl ImportDocumentsParameters { } } } - diff --git a/typesense_codegen/src/models/index_action.rs b/typesense_codegen/src/models/index_action.rs index 7bce745..eb52174 100644 --- a/typesense_codegen/src/models/index_action.rs +++ b/typesense_codegen/src/models/index_action.rs @@ -4,14 +4,14 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ use crate::models; use serde::{Deserialize, Serialize}; -/// +/// #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum IndexAction { #[serde(rename = "create")] @@ -22,7 +22,6 @@ pub enum IndexAction { Upsert, #[serde(rename = "emplace")] Emplace, - } impl std::fmt::Display for IndexAction { @@ -41,4 +40,3 @@ impl Default for IndexAction { Self::Create } } - diff --git a/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs b/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs index 75a8ddf..9985e0d 100644 --- a/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs +++ b/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +18,7 @@ pub struct ListStemmingDictionaries200Response { } impl ListStemmingDictionaries200Response { - pub fn new() -> ListStemmingDictionaries200Response{ - ListStemmingDictionaries200Response { - dictionaries: None, - } + pub fn new() -> ListStemmingDictionaries200Response { + ListStemmingDictionaries200Response { dictionaries: None } } } - diff --git a/typesense_codegen/src/models/multi_search_collection_parameters.rs b/typesense_codegen/src/models/multi_search_collection_parameters.rs index cc5a457..76f99e0 100644 --- a/typesense_codegen/src/models/multi_search_collection_parameters.rs +++ b/typesense_codegen/src/models/multi_search_collection_parameters.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -54,7 +54,7 @@ pub struct MultiSearchCollectionParameters { /// Facet values that are returned can now be filtered via this parameter. The matching facet text is also highlighted. For example, when faceting by `category`, you can set `facet_query=category:shoe` to return only facet values that contain the prefix \"shoe\". #[serde(rename = "facet_query", skip_serializing_if = "Option::is_none")] pub facet_query: Option, - /// The number of typographical errors (1 or 2) that would be tolerated. Default: 2 + /// The number of typographical errors (1 or 2) that would be tolerated. Default: 2 #[serde(rename = "num_typos", skip_serializing_if = "Option::is_none")] pub num_typos: Option, /// Results from this specific page number would be fetched. @@ -63,7 +63,7 @@ pub struct MultiSearchCollectionParameters { /// Number of results to fetch per page. Default: 10 #[serde(rename = "per_page", skip_serializing_if = "Option::is_none")] pub per_page: Option, - /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. + /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. #[serde(rename = "limit", skip_serializing_if = "Option::is_none")] pub limit: Option, /// Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. @@ -72,11 +72,14 @@ pub struct MultiSearchCollectionParameters { /// You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. #[serde(rename = "group_by", skip_serializing_if = "Option::is_none")] pub group_by: Option, - /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 + /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 #[serde(rename = "group_limit", skip_serializing_if = "Option::is_none")] pub group_limit: Option, - /// Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true - #[serde(rename = "group_missing_values", skip_serializing_if = "Option::is_none")] + /// Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true + #[serde( + rename = "group_missing_values", + skip_serializing_if = "Option::is_none" + )] pub group_missing_values: Option, /// List of fields from the document to include in the search result #[serde(rename = "include_fields", skip_serializing_if = "Option::is_none")] @@ -85,140 +88,194 @@ pub struct MultiSearchCollectionParameters { #[serde(rename = "exclude_fields", skip_serializing_if = "Option::is_none")] pub exclude_fields: Option, /// List of fields which should be highlighted fully without snippeting - #[serde(rename = "highlight_full_fields", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "highlight_full_fields", + skip_serializing_if = "Option::is_none" + )] pub highlight_full_fields: Option, - /// The number of tokens that should surround the highlighted text on each side. Default: 4 - #[serde(rename = "highlight_affix_num_tokens", skip_serializing_if = "Option::is_none")] + /// The number of tokens that should surround the highlighted text on each side. Default: 4 + #[serde( + rename = "highlight_affix_num_tokens", + skip_serializing_if = "Option::is_none" + )] pub highlight_affix_num_tokens: Option, - /// The start tag used for the highlighted snippets. Default: `` - #[serde(rename = "highlight_start_tag", skip_serializing_if = "Option::is_none")] + /// The start tag used for the highlighted snippets. Default: `` + #[serde( + rename = "highlight_start_tag", + skip_serializing_if = "Option::is_none" + )] pub highlight_start_tag: Option, - /// The end tag used for the highlighted snippets. Default: `` + /// The end tag used for the highlighted snippets. Default: `` #[serde(rename = "highlight_end_tag", skip_serializing_if = "Option::is_none")] pub highlight_end_tag: Option, - /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 + /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 #[serde(rename = "snippet_threshold", skip_serializing_if = "Option::is_none")] pub snippet_threshold: Option, - /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 - #[serde(rename = "drop_tokens_threshold", skip_serializing_if = "Option::is_none")] + /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 + #[serde( + rename = "drop_tokens_threshold", + skip_serializing_if = "Option::is_none" + )] pub drop_tokens_threshold: Option, #[serde(rename = "drop_tokens_mode", skip_serializing_if = "Option::is_none")] pub drop_tokens_mode: Option, - /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 - #[serde(rename = "typo_tokens_threshold", skip_serializing_if = "Option::is_none")] + /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 + #[serde( + rename = "typo_tokens_threshold", + skip_serializing_if = "Option::is_none" + )] pub typo_tokens_threshold: Option, - /// Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. - #[serde(rename = "enable_typos_for_alpha_numerical_tokens", skip_serializing_if = "Option::is_none")] + /// Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + #[serde( + rename = "enable_typos_for_alpha_numerical_tokens", + skip_serializing_if = "Option::is_none" + )] pub enable_typos_for_alpha_numerical_tokens: Option, - /// Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false - #[serde(rename = "filter_curated_hits", skip_serializing_if = "Option::is_none")] + /// Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + #[serde( + rename = "filter_curated_hits", + skip_serializing_if = "Option::is_none" + )] pub filter_curated_hits: Option, - /// If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + /// If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true #[serde(rename = "enable_synonyms", skip_serializing_if = "Option::is_none")] pub enable_synonyms: Option, - /// Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). + /// Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). #[serde(rename = "enable_analytics", skip_serializing_if = "Option::is_none")] pub enable_analytics: Option, - /// Allow synonym resolution on word prefixes in the query. Default: false + /// Allow synonym resolution on word prefixes in the query. Default: false #[serde(rename = "synonym_prefix", skip_serializing_if = "Option::is_none")] pub synonym_prefix: Option, - /// Allow synonym resolution on typo-corrected words in the query. Default: 0 + /// Allow synonym resolution on typo-corrected words in the query. Default: 0 #[serde(rename = "synonym_num_typos", skip_serializing_if = "Option::is_none")] pub synonym_num_typos: Option, - /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "pinned_hits", skip_serializing_if = "Option::is_none")] pub pinned_hits: Option, - /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "hidden_hits", skip_serializing_if = "Option::is_none")] pub hidden_hits: Option, /// Comma separated list of tags to trigger the curations rules that match the tags. #[serde(rename = "override_tags", skip_serializing_if = "Option::is_none")] pub override_tags: Option, - /// A list of custom fields that must be highlighted even if you don't query for them + /// A list of custom fields that must be highlighted even if you don't query for them #[serde(rename = "highlight_fields", skip_serializing_if = "Option::is_none")] pub highlight_fields: Option, - /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same - #[serde(rename = "pre_segmented_query", skip_serializing_if = "Option::is_none")] + /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same + #[serde( + rename = "pre_segmented_query", + skip_serializing_if = "Option::is_none" + )] pub pre_segmented_query: Option, - /// Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. + /// Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. #[serde(rename = "preset", skip_serializing_if = "Option::is_none")] pub preset: Option, - /// If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false + /// If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false #[serde(rename = "enable_overrides", skip_serializing_if = "Option::is_none")] pub enable_overrides: Option, - /// Set this parameter to true to ensure that an exact match is ranked above the others - #[serde(rename = "prioritize_exact_match", skip_serializing_if = "Option::is_none")] + /// Set this parameter to true to ensure that an exact match is ranked above the others + #[serde( + rename = "prioritize_exact_match", + skip_serializing_if = "Option::is_none" + )] pub prioritize_exact_match: Option, - /// Make Typesense prioritize documents where the query words appear earlier in the text. - #[serde(rename = "prioritize_token_position", skip_serializing_if = "Option::is_none")] + /// Make Typesense prioritize documents where the query words appear earlier in the text. + #[serde( + rename = "prioritize_token_position", + skip_serializing_if = "Option::is_none" + )] pub prioritize_token_position: Option, - /// Make Typesense prioritize documents where the query words appear in more number of fields. - #[serde(rename = "prioritize_num_matching_fields", skip_serializing_if = "Option::is_none")] + /// Make Typesense prioritize documents where the query words appear in more number of fields. + #[serde( + rename = "prioritize_num_matching_fields", + skip_serializing_if = "Option::is_none" + )] pub prioritize_num_matching_fields: Option, - /// Make Typesense disable typos for numerical tokens. - #[serde(rename = "enable_typos_for_numerical_tokens", skip_serializing_if = "Option::is_none")] + /// Make Typesense disable typos for numerical tokens. + #[serde( + rename = "enable_typos_for_numerical_tokens", + skip_serializing_if = "Option::is_none" + )] pub enable_typos_for_numerical_tokens: Option, - /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). + /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). #[serde(rename = "exhaustive_search", skip_serializing_if = "Option::is_none")] pub exhaustive_search: Option, - /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. + /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. #[serde(rename = "search_cutoff_ms", skip_serializing_if = "Option::is_none")] pub search_cutoff_ms: Option, - /// Enable server side caching of search query results. By default, caching is disabled. + /// Enable server side caching of search query results. By default, caching is disabled. #[serde(rename = "use_cache", skip_serializing_if = "Option::is_none")] pub use_cache: Option, - /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. + /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. #[serde(rename = "cache_ttl", skip_serializing_if = "Option::is_none")] pub cache_ttl: Option, - /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_1typo", skip_serializing_if = "Option::is_none")] pub min_len_1typo: Option, - /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_2typo", skip_serializing_if = "Option::is_none")] pub min_len_2typo: Option, - /// Vector query expression for fetching documents \"closest\" to a given query/document vector. + /// Vector query expression for fetching documents \"closest\" to a given query/document vector. #[serde(rename = "vector_query", skip_serializing_if = "Option::is_none")] pub vector_query: Option, - /// Timeout (in milliseconds) for fetching remote embeddings. - #[serde(rename = "remote_embedding_timeout_ms", skip_serializing_if = "Option::is_none")] + /// Timeout (in milliseconds) for fetching remote embeddings. + #[serde( + rename = "remote_embedding_timeout_ms", + skip_serializing_if = "Option::is_none" + )] pub remote_embedding_timeout_ms: Option, - /// Number of times to retry fetching remote embeddings. - #[serde(rename = "remote_embedding_num_tries", skip_serializing_if = "Option::is_none")] + /// Number of times to retry fetching remote embeddings. + #[serde( + rename = "remote_embedding_num_tries", + skip_serializing_if = "Option::is_none" + )] pub remote_embedding_num_tries: Option, - /// Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). + /// Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). #[serde(rename = "facet_strategy", skip_serializing_if = "Option::is_none")] pub facet_strategy: Option, - /// Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. + /// Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. #[serde(rename = "stopwords", skip_serializing_if = "Option::is_none")] pub stopwords: Option, - /// Comma separated string of nested facet fields whose parent object should be returned in facet response. - #[serde(rename = "facet_return_parent", skip_serializing_if = "Option::is_none")] + /// Comma separated string of nested facet fields whose parent object should be returned in facet response. + #[serde( + rename = "facet_return_parent", + skip_serializing_if = "Option::is_none" + )] pub facet_return_parent: Option, - /// The base64 encoded audio file in 16 khz 16-bit WAV format. + /// The base64 encoded audio file in 16 khz 16-bit WAV format. #[serde(rename = "voice_query", skip_serializing_if = "Option::is_none")] pub voice_query: Option, - /// Enable conversational search. + /// Enable conversational search. #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] pub conversation: Option, - /// The Id of Conversation Model to be used. - #[serde(rename = "conversation_model_id", skip_serializing_if = "Option::is_none")] + /// The Id of Conversation Model to be used. + #[serde( + rename = "conversation_model_id", + skip_serializing_if = "Option::is_none" + )] pub conversation_model_id: Option, - /// The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + /// The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. #[serde(rename = "conversation_id", skip_serializing_if = "Option::is_none")] pub conversation_id: Option, - /// The collection to search in. + /// The collection to search in. #[serde(rename = "collection", skip_serializing_if = "Option::is_none")] pub collection: Option, /// A separate search API key for each search within a multi_search request - #[serde(rename = "x-typesense-api-key", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "x-typesense-api-key", + skip_serializing_if = "Option::is_none" + )] pub x_typesense_api_key: Option, - /// When true, computes both text match and vector distance scores for all matches in hybrid search. Documents found only through keyword search will get a vector distance score, and documents found only through vector search will get a text match score. - #[serde(rename = "rerank_hybrid_matches", skip_serializing_if = "Option::is_none")] + /// When true, computes both text match and vector distance scores for all matches in hybrid search. Documents found only through keyword search will get a vector distance score, and documents found only through vector search will get a text match score. + #[serde( + rename = "rerank_hybrid_matches", + skip_serializing_if = "Option::is_none" + )] pub rerank_hybrid_matches: Option, } impl MultiSearchCollectionParameters { - pub fn new() -> MultiSearchCollectionParameters{ + pub fn new() -> MultiSearchCollectionParameters { MultiSearchCollectionParameters { q: None, query_by: None, @@ -290,4 +347,3 @@ impl MultiSearchCollectionParameters { } } } - diff --git a/typesense_codegen/src/models/multi_search_parameters.rs b/typesense_codegen/src/models/multi_search_parameters.rs index 7602ca5..21b2db0 100644 --- a/typesense_codegen/src/models/multi_search_parameters.rs +++ b/typesense_codegen/src/models/multi_search_parameters.rs @@ -4,14 +4,14 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ use crate::models; use serde::{Deserialize, Serialize}; -/// MultiSearchParameters : Parameters for the multi search API. +/// MultiSearchParameters : Parameters for the multi search API. #[derive(bon::Builder)] #[builder(on(String, into))] #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] @@ -55,7 +55,7 @@ pub struct MultiSearchParameters { /// Facet values that are returned can now be filtered via this parameter. The matching facet text is also highlighted. For example, when faceting by `category`, you can set `facet_query=category:shoe` to return only facet values that contain the prefix \"shoe\". #[serde(rename = "facet_query", skip_serializing_if = "Option::is_none")] pub facet_query: Option, - /// The number of typographical errors (1 or 2) that would be tolerated. Default: 2 + /// The number of typographical errors (1 or 2) that would be tolerated. Default: 2 #[serde(rename = "num_typos", skip_serializing_if = "Option::is_none")] pub num_typos: Option, /// Results from this specific page number would be fetched. @@ -64,7 +64,7 @@ pub struct MultiSearchParameters { /// Number of results to fetch per page. Default: 10 #[serde(rename = "per_page", skip_serializing_if = "Option::is_none")] pub per_page: Option, - /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. + /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. #[serde(rename = "limit", skip_serializing_if = "Option::is_none")] pub limit: Option, /// Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. @@ -73,11 +73,14 @@ pub struct MultiSearchParameters { /// You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. #[serde(rename = "group_by", skip_serializing_if = "Option::is_none")] pub group_by: Option, - /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 + /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 #[serde(rename = "group_limit", skip_serializing_if = "Option::is_none")] pub group_limit: Option, - /// Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true - #[serde(rename = "group_missing_values", skip_serializing_if = "Option::is_none")] + /// Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true + #[serde( + rename = "group_missing_values", + skip_serializing_if = "Option::is_none" + )] pub group_missing_values: Option, /// List of fields from the document to include in the search result #[serde(rename = "include_fields", skip_serializing_if = "Option::is_none")] @@ -86,132 +89,180 @@ pub struct MultiSearchParameters { #[serde(rename = "exclude_fields", skip_serializing_if = "Option::is_none")] pub exclude_fields: Option, /// List of fields which should be highlighted fully without snippeting - #[serde(rename = "highlight_full_fields", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "highlight_full_fields", + skip_serializing_if = "Option::is_none" + )] pub highlight_full_fields: Option, - /// The number of tokens that should surround the highlighted text on each side. Default: 4 - #[serde(rename = "highlight_affix_num_tokens", skip_serializing_if = "Option::is_none")] + /// The number of tokens that should surround the highlighted text on each side. Default: 4 + #[serde( + rename = "highlight_affix_num_tokens", + skip_serializing_if = "Option::is_none" + )] pub highlight_affix_num_tokens: Option, - /// The start tag used for the highlighted snippets. Default: `` - #[serde(rename = "highlight_start_tag", skip_serializing_if = "Option::is_none")] + /// The start tag used for the highlighted snippets. Default: `` + #[serde( + rename = "highlight_start_tag", + skip_serializing_if = "Option::is_none" + )] pub highlight_start_tag: Option, - /// The end tag used for the highlighted snippets. Default: `` + /// The end tag used for the highlighted snippets. Default: `` #[serde(rename = "highlight_end_tag", skip_serializing_if = "Option::is_none")] pub highlight_end_tag: Option, - /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 + /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 #[serde(rename = "snippet_threshold", skip_serializing_if = "Option::is_none")] pub snippet_threshold: Option, - /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 - #[serde(rename = "drop_tokens_threshold", skip_serializing_if = "Option::is_none")] + /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 + #[serde( + rename = "drop_tokens_threshold", + skip_serializing_if = "Option::is_none" + )] pub drop_tokens_threshold: Option, #[serde(rename = "drop_tokens_mode", skip_serializing_if = "Option::is_none")] pub drop_tokens_mode: Option, - /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 - #[serde(rename = "typo_tokens_threshold", skip_serializing_if = "Option::is_none")] + /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 + #[serde( + rename = "typo_tokens_threshold", + skip_serializing_if = "Option::is_none" + )] pub typo_tokens_threshold: Option, - /// Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. - #[serde(rename = "enable_typos_for_alpha_numerical_tokens", skip_serializing_if = "Option::is_none")] + /// Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + #[serde( + rename = "enable_typos_for_alpha_numerical_tokens", + skip_serializing_if = "Option::is_none" + )] pub enable_typos_for_alpha_numerical_tokens: Option, - /// Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false - #[serde(rename = "filter_curated_hits", skip_serializing_if = "Option::is_none")] + /// Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + #[serde( + rename = "filter_curated_hits", + skip_serializing_if = "Option::is_none" + )] pub filter_curated_hits: Option, - /// If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + /// If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true #[serde(rename = "enable_synonyms", skip_serializing_if = "Option::is_none")] pub enable_synonyms: Option, - /// Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). + /// Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). #[serde(rename = "enable_analytics", skip_serializing_if = "Option::is_none")] pub enable_analytics: Option, - /// Allow synonym resolution on word prefixes in the query. Default: false + /// Allow synonym resolution on word prefixes in the query. Default: false #[serde(rename = "synonym_prefix", skip_serializing_if = "Option::is_none")] pub synonym_prefix: Option, - /// Allow synonym resolution on typo-corrected words in the query. Default: 0 + /// Allow synonym resolution on typo-corrected words in the query. Default: 0 #[serde(rename = "synonym_num_typos", skip_serializing_if = "Option::is_none")] pub synonym_num_typos: Option, - /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "pinned_hits", skip_serializing_if = "Option::is_none")] pub pinned_hits: Option, - /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "hidden_hits", skip_serializing_if = "Option::is_none")] pub hidden_hits: Option, /// Comma separated list of tags to trigger the curations rules that match the tags. #[serde(rename = "override_tags", skip_serializing_if = "Option::is_none")] pub override_tags: Option, - /// A list of custom fields that must be highlighted even if you don't query for them + /// A list of custom fields that must be highlighted even if you don't query for them #[serde(rename = "highlight_fields", skip_serializing_if = "Option::is_none")] pub highlight_fields: Option, - /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same - #[serde(rename = "pre_segmented_query", skip_serializing_if = "Option::is_none")] + /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same + #[serde( + rename = "pre_segmented_query", + skip_serializing_if = "Option::is_none" + )] pub pre_segmented_query: Option, - /// Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. + /// Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. #[serde(rename = "preset", skip_serializing_if = "Option::is_none")] pub preset: Option, - /// If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false + /// If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false #[serde(rename = "enable_overrides", skip_serializing_if = "Option::is_none")] pub enable_overrides: Option, - /// Set this parameter to true to ensure that an exact match is ranked above the others - #[serde(rename = "prioritize_exact_match", skip_serializing_if = "Option::is_none")] + /// Set this parameter to true to ensure that an exact match is ranked above the others + #[serde( + rename = "prioritize_exact_match", + skip_serializing_if = "Option::is_none" + )] pub prioritize_exact_match: Option, - /// Make Typesense prioritize documents where the query words appear earlier in the text. - #[serde(rename = "prioritize_token_position", skip_serializing_if = "Option::is_none")] + /// Make Typesense prioritize documents where the query words appear earlier in the text. + #[serde( + rename = "prioritize_token_position", + skip_serializing_if = "Option::is_none" + )] pub prioritize_token_position: Option, - /// Make Typesense prioritize documents where the query words appear in more number of fields. - #[serde(rename = "prioritize_num_matching_fields", skip_serializing_if = "Option::is_none")] + /// Make Typesense prioritize documents where the query words appear in more number of fields. + #[serde( + rename = "prioritize_num_matching_fields", + skip_serializing_if = "Option::is_none" + )] pub prioritize_num_matching_fields: Option, - /// Make Typesense disable typos for numerical tokens. - #[serde(rename = "enable_typos_for_numerical_tokens", skip_serializing_if = "Option::is_none")] + /// Make Typesense disable typos for numerical tokens. + #[serde( + rename = "enable_typos_for_numerical_tokens", + skip_serializing_if = "Option::is_none" + )] pub enable_typos_for_numerical_tokens: Option, - /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). + /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). #[serde(rename = "exhaustive_search", skip_serializing_if = "Option::is_none")] pub exhaustive_search: Option, - /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. + /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. #[serde(rename = "search_cutoff_ms", skip_serializing_if = "Option::is_none")] pub search_cutoff_ms: Option, - /// Enable server side caching of search query results. By default, caching is disabled. + /// Enable server side caching of search query results. By default, caching is disabled. #[serde(rename = "use_cache", skip_serializing_if = "Option::is_none")] pub use_cache: Option, - /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. + /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. #[serde(rename = "cache_ttl", skip_serializing_if = "Option::is_none")] pub cache_ttl: Option, - /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_1typo", skip_serializing_if = "Option::is_none")] pub min_len_1typo: Option, - /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_2typo", skip_serializing_if = "Option::is_none")] pub min_len_2typo: Option, - /// Vector query expression for fetching documents \"closest\" to a given query/document vector. + /// Vector query expression for fetching documents \"closest\" to a given query/document vector. #[serde(rename = "vector_query", skip_serializing_if = "Option::is_none")] pub vector_query: Option, - /// Timeout (in milliseconds) for fetching remote embeddings. - #[serde(rename = "remote_embedding_timeout_ms", skip_serializing_if = "Option::is_none")] + /// Timeout (in milliseconds) for fetching remote embeddings. + #[serde( + rename = "remote_embedding_timeout_ms", + skip_serializing_if = "Option::is_none" + )] pub remote_embedding_timeout_ms: Option, - /// Number of times to retry fetching remote embeddings. - #[serde(rename = "remote_embedding_num_tries", skip_serializing_if = "Option::is_none")] + /// Number of times to retry fetching remote embeddings. + #[serde( + rename = "remote_embedding_num_tries", + skip_serializing_if = "Option::is_none" + )] pub remote_embedding_num_tries: Option, - /// Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). + /// Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). #[serde(rename = "facet_strategy", skip_serializing_if = "Option::is_none")] pub facet_strategy: Option, - /// Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. + /// Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. #[serde(rename = "stopwords", skip_serializing_if = "Option::is_none")] pub stopwords: Option, - /// Comma separated string of nested facet fields whose parent object should be returned in facet response. - #[serde(rename = "facet_return_parent", skip_serializing_if = "Option::is_none")] + /// Comma separated string of nested facet fields whose parent object should be returned in facet response. + #[serde( + rename = "facet_return_parent", + skip_serializing_if = "Option::is_none" + )] pub facet_return_parent: Option, - /// The base64 encoded audio file in 16 khz 16-bit WAV format. + /// The base64 encoded audio file in 16 khz 16-bit WAV format. #[serde(rename = "voice_query", skip_serializing_if = "Option::is_none")] pub voice_query: Option, - /// Enable conversational search. + /// Enable conversational search. #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] pub conversation: Option, - /// The Id of Conversation Model to be used. - #[serde(rename = "conversation_model_id", skip_serializing_if = "Option::is_none")] + /// The Id of Conversation Model to be used. + #[serde( + rename = "conversation_model_id", + skip_serializing_if = "Option::is_none" + )] pub conversation_model_id: Option, - /// The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + /// The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. #[serde(rename = "conversation_id", skip_serializing_if = "Option::is_none")] pub conversation_id: Option, } impl MultiSearchParameters { - /// Parameters for the multi search API. - pub fn new() -> MultiSearchParameters{ + /// Parameters for the multi search API. + pub fn new() -> MultiSearchParameters { MultiSearchParameters { q: None, query_by: None, @@ -280,4 +331,3 @@ impl MultiSearchParameters { } } } - diff --git a/typesense_codegen/src/models/multi_search_result.rs b/typesense_codegen/src/models/multi_search_result.rs index d3ffd67..bef6780 100644 --- a/typesense_codegen/src/models/multi_search_result.rs +++ b/typesense_codegen/src/models/multi_search_result.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -20,11 +20,10 @@ pub struct MultiSearchResult { } impl MultiSearchResult { - pub fn new(results: Vec>) -> MultiSearchResult{ + pub fn new(results: Vec>) -> MultiSearchResult { MultiSearchResult { results, conversation: None, } } } - diff --git a/typesense_codegen/src/models/multi_search_result_item.rs b/typesense_codegen/src/models/multi_search_result_item.rs index 6f4c8bc..64794c8 100644 --- a/typesense_codegen/src/models/multi_search_result_item.rs +++ b/typesense_codegen/src/models/multi_search_result_item.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -42,7 +42,10 @@ pub struct MultiSearchResultItem { #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] pub conversation: Option>, /// Returned only for union query response. - #[serde(rename = "union_request_params", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "union_request_params", + skip_serializing_if = "Option::is_none" + )] pub union_request_params: Option>, /// HTTP error code #[serde(rename = "code", skip_serializing_if = "Option::is_none")] @@ -53,7 +56,7 @@ pub struct MultiSearchResultItem { } impl MultiSearchResultItem { - pub fn new() -> MultiSearchResultItem{ + pub fn new() -> MultiSearchResultItem { MultiSearchResultItem { facet_counts: None, found: None, @@ -72,4 +75,3 @@ impl MultiSearchResultItem { } } } - diff --git a/typesense_codegen/src/models/multi_search_searches_parameter.rs b/typesense_codegen/src/models/multi_search_searches_parameter.rs index f8e69d3..36cd062 100644 --- a/typesense_codegen/src/models/multi_search_searches_parameter.rs +++ b/typesense_codegen/src/models/multi_search_searches_parameter.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -21,11 +21,12 @@ pub struct MultiSearchSearchesParameter { } impl MultiSearchSearchesParameter { - pub fn new(searches: Vec) -> MultiSearchSearchesParameter{ + pub fn new( + searches: Vec, + ) -> MultiSearchSearchesParameter { MultiSearchSearchesParameter { union: None, searches, } } } - diff --git a/typesense_codegen/src/models/nl_search_model_base.rs b/typesense_codegen/src/models/nl_search_model_base.rs index 4e08735..5bb066f 100644 --- a/typesense_codegen/src/models/nl_search_model_base.rs +++ b/typesense_codegen/src/models/nl_search_model_base.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -70,7 +70,7 @@ pub struct NlSearchModelBase { } impl NlSearchModelBase { - pub fn new() -> NlSearchModelBase{ + pub fn new() -> NlSearchModelBase { NlSearchModelBase { model_name: None, api_key: None, @@ -93,4 +93,3 @@ impl NlSearchModelBase { } } } - diff --git a/typesense_codegen/src/models/nl_search_model_create_schema.rs b/typesense_codegen/src/models/nl_search_model_create_schema.rs index 4259d0a..34cb2d4 100644 --- a/typesense_codegen/src/models/nl_search_model_create_schema.rs +++ b/typesense_codegen/src/models/nl_search_model_create_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -73,7 +73,7 @@ pub struct NlSearchModelCreateSchema { } impl NlSearchModelCreateSchema { - pub fn new() -> NlSearchModelCreateSchema{ + pub fn new() -> NlSearchModelCreateSchema { NlSearchModelCreateSchema { model_name: None, api_key: None, @@ -97,4 +97,3 @@ impl NlSearchModelCreateSchema { } } } - diff --git a/typesense_codegen/src/models/nl_search_model_delete_schema.rs b/typesense_codegen/src/models/nl_search_model_delete_schema.rs index 20dbf83..f31df7d 100644 --- a/typesense_codegen/src/models/nl_search_model_delete_schema.rs +++ b/typesense_codegen/src/models/nl_search_model_delete_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,10 +19,7 @@ pub struct NlSearchModelDeleteSchema { } impl NlSearchModelDeleteSchema { - pub fn new(id: String) -> NlSearchModelDeleteSchema{ - NlSearchModelDeleteSchema { - id, - } + pub fn new(id: String) -> NlSearchModelDeleteSchema { + NlSearchModelDeleteSchema { id } } } - diff --git a/typesense_codegen/src/models/nl_search_model_schema.rs b/typesense_codegen/src/models/nl_search_model_schema.rs index 9a24637..b2066e0 100644 --- a/typesense_codegen/src/models/nl_search_model_schema.rs +++ b/typesense_codegen/src/models/nl_search_model_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -73,7 +73,7 @@ pub struct NlSearchModelSchema { } impl NlSearchModelSchema { - pub fn new(id: String) -> NlSearchModelSchema{ + pub fn new(id: String) -> NlSearchModelSchema { NlSearchModelSchema { model_name: None, api_key: None, @@ -97,4 +97,3 @@ impl NlSearchModelSchema { } } } - diff --git a/typesense_codegen/src/models/preset_delete_schema.rs b/typesense_codegen/src/models/preset_delete_schema.rs index 77294d0..5203796 100644 --- a/typesense_codegen/src/models/preset_delete_schema.rs +++ b/typesense_codegen/src/models/preset_delete_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +18,7 @@ pub struct PresetDeleteSchema { } impl PresetDeleteSchema { - pub fn new(name: String) -> PresetDeleteSchema{ - PresetDeleteSchema { - name, - } + pub fn new(name: String) -> PresetDeleteSchema { + PresetDeleteSchema { name } } } - diff --git a/typesense_codegen/src/models/preset_schema.rs b/typesense_codegen/src/models/preset_schema.rs index 8c9352c..c12caca 100644 --- a/typesense_codegen/src/models/preset_schema.rs +++ b/typesense_codegen/src/models/preset_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -20,11 +20,10 @@ pub struct PresetSchema { } impl PresetSchema { - pub fn new(value: models::PresetUpsertSchemaValue, name: String) -> PresetSchema{ + pub fn new(value: models::PresetUpsertSchemaValue, name: String) -> PresetSchema { PresetSchema { value: Box::new(value), name, } } } - diff --git a/typesense_codegen/src/models/preset_upsert_schema.rs b/typesense_codegen/src/models/preset_upsert_schema.rs index 92203f8..92eff0d 100644 --- a/typesense_codegen/src/models/preset_upsert_schema.rs +++ b/typesense_codegen/src/models/preset_upsert_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +18,9 @@ pub struct PresetUpsertSchema { } impl PresetUpsertSchema { - pub fn new(value: models::PresetUpsertSchemaValue) -> PresetUpsertSchema{ + pub fn new(value: models::PresetUpsertSchemaValue) -> PresetUpsertSchema { PresetUpsertSchema { value: Box::new(value), } } } - diff --git a/typesense_codegen/src/models/preset_upsert_schema_value.rs b/typesense_codegen/src/models/preset_upsert_schema_value.rs index f6a502f..43335aa 100644 --- a/typesense_codegen/src/models/preset_upsert_schema_value.rs +++ b/typesense_codegen/src/models/preset_upsert_schema_value.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -23,4 +23,3 @@ impl Default for PresetUpsertSchemaValue { Self::SearchParameters(Default::default()) } } - diff --git a/typesense_codegen/src/models/presets_retrieve_schema.rs b/typesense_codegen/src/models/presets_retrieve_schema.rs index e13bc93..e64ecf1 100644 --- a/typesense_codegen/src/models/presets_retrieve_schema.rs +++ b/typesense_codegen/src/models/presets_retrieve_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +18,7 @@ pub struct PresetsRetrieveSchema { } impl PresetsRetrieveSchema { - pub fn new(presets: Vec) -> PresetsRetrieveSchema{ - PresetsRetrieveSchema { - presets, - } + pub fn new(presets: Vec) -> PresetsRetrieveSchema { + PresetsRetrieveSchema { presets } } } - diff --git a/typesense_codegen/src/models/schema_change_status.rs b/typesense_codegen/src/models/schema_change_status.rs index f051a9b..22bb410 100644 --- a/typesense_codegen/src/models/schema_change_status.rs +++ b/typesense_codegen/src/models/schema_change_status.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -25,7 +25,7 @@ pub struct SchemaChangeStatus { } impl SchemaChangeStatus { - pub fn new() -> SchemaChangeStatus{ + pub fn new() -> SchemaChangeStatus { SchemaChangeStatus { collection: None, validated_docs: None, @@ -33,4 +33,3 @@ impl SchemaChangeStatus { } } } - diff --git a/typesense_codegen/src/models/search_grouped_hit.rs b/typesense_codegen/src/models/search_grouped_hit.rs index 73d9292..434b8fc 100644 --- a/typesense_codegen/src/models/search_grouped_hit.rs +++ b/typesense_codegen/src/models/search_grouped_hit.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -23,7 +23,10 @@ pub struct SearchGroupedHit { } impl SearchGroupedHit { - pub fn new(group_key: Vec, hits: Vec>) -> SearchGroupedHit{ + pub fn new( + group_key: Vec, + hits: Vec>, + ) -> SearchGroupedHit { SearchGroupedHit { found: None, group_key, @@ -31,4 +34,3 @@ impl SearchGroupedHit { } } } - diff --git a/typesense_codegen/src/models/search_highlight.rs b/typesense_codegen/src/models/search_highlight.rs index 0b5101d..c45afcc 100644 --- a/typesense_codegen/src/models/search_highlight.rs +++ b/typesense_codegen/src/models/search_highlight.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -35,7 +35,7 @@ pub struct SearchHighlight { } impl SearchHighlight { - pub fn new() -> SearchHighlight{ + pub fn new() -> SearchHighlight { SearchHighlight { field: None, snippet: None, @@ -47,4 +47,3 @@ impl SearchHighlight { } } } - diff --git a/typesense_codegen/src/models/search_override.rs b/typesense_codegen/src/models/search_override.rs index 0740e2d..b1f8353 100644 --- a/typesense_codegen/src/models/search_override.rs +++ b/typesense_codegen/src/models/search_override.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -21,31 +21,37 @@ pub struct SearchOverride { /// List of document `id`s that should be excluded from the search results. #[serde(rename = "excludes", skip_serializing_if = "Option::is_none")] pub excludes: Option>, - /// A filter by clause that is applied to any search query that matches the override rule. + /// A filter by clause that is applied to any search query that matches the override rule. #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] pub filter_by: Option, - /// Indicates whether search query tokens that exist in the override's rule should be removed from the search query. - #[serde(rename = "remove_matched_tokens", skip_serializing_if = "Option::is_none")] + /// Indicates whether search query tokens that exist in the override's rule should be removed from the search query. + #[serde( + rename = "remove_matched_tokens", + skip_serializing_if = "Option::is_none" + )] pub remove_matched_tokens: Option, - /// Return a custom JSON object in the Search API response, when this rule is triggered. This can can be used to display a pre-defined message (eg: a promotion banner) on the front-end when a particular rule is triggered. + /// Return a custom JSON object in the Search API response, when this rule is triggered. This can can be used to display a pre-defined message (eg: a promotion banner) on the front-end when a particular rule is triggered. #[serde(rename = "metadata", skip_serializing_if = "Option::is_none")] pub metadata: Option, - /// A sort by clause that is applied to any search query that matches the override rule. + /// A sort by clause that is applied to any search query that matches the override rule. #[serde(rename = "sort_by", skip_serializing_if = "Option::is_none")] pub sort_by: Option, - /// Replaces the current search query with this value, when the search query matches the override rule. + /// Replaces the current search query with this value, when the search query matches the override rule. #[serde(rename = "replace_query", skip_serializing_if = "Option::is_none")] pub replace_query: Option, - /// When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. - #[serde(rename = "filter_curated_hits", skip_serializing_if = "Option::is_none")] + /// When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. + #[serde( + rename = "filter_curated_hits", + skip_serializing_if = "Option::is_none" + )] pub filter_curated_hits: Option, - /// A Unix timestamp that indicates the date/time from which the override will be active. You can use this to create override rules that start applying from a future point in time. + /// A Unix timestamp that indicates the date/time from which the override will be active. You can use this to create override rules that start applying from a future point in time. #[serde(rename = "effective_from_ts", skip_serializing_if = "Option::is_none")] pub effective_from_ts: Option, - /// A Unix timestamp that indicates the date/time until which the override will be active. You can use this to create override rules that stop applying after a period of time. + /// A Unix timestamp that indicates the date/time until which the override will be active. You can use this to create override rules that stop applying after a period of time. #[serde(rename = "effective_to_ts", skip_serializing_if = "Option::is_none")] pub effective_to_ts: Option, - /// When set to true, override processing will stop at the first matching rule. When set to false override processing will continue and multiple override actions will be triggered in sequence. Overrides are processed in the lexical sort order of their id field. Default: true. + /// When set to true, override processing will stop at the first matching rule. When set to false override processing will continue and multiple override actions will be triggered in sequence. Overrides are processed in the lexical sort order of their id field. Default: true. #[serde(rename = "stop_processing", skip_serializing_if = "Option::is_none")] pub stop_processing: Option, #[serde(rename = "id")] @@ -53,7 +59,7 @@ pub struct SearchOverride { } impl SearchOverride { - pub fn new(rule: models::SearchOverrideRule, id: String) -> SearchOverride{ + pub fn new(rule: models::SearchOverrideRule, id: String) -> SearchOverride { SearchOverride { rule: Box::new(rule), includes: None, @@ -71,4 +77,3 @@ impl SearchOverride { } } } - diff --git a/typesense_codegen/src/models/search_override_delete_response.rs b/typesense_codegen/src/models/search_override_delete_response.rs index 23bc8f4..3949320 100644 --- a/typesense_codegen/src/models/search_override_delete_response.rs +++ b/typesense_codegen/src/models/search_override_delete_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,10 +19,7 @@ pub struct SearchOverrideDeleteResponse { } impl SearchOverrideDeleteResponse { - pub fn new(id: String) -> SearchOverrideDeleteResponse{ - SearchOverrideDeleteResponse { - id, - } + pub fn new(id: String) -> SearchOverrideDeleteResponse { + SearchOverrideDeleteResponse { id } } } - diff --git a/typesense_codegen/src/models/search_override_exclude.rs b/typesense_codegen/src/models/search_override_exclude.rs index e6c0dee..58b01b9 100644 --- a/typesense_codegen/src/models/search_override_exclude.rs +++ b/typesense_codegen/src/models/search_override_exclude.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,10 +19,7 @@ pub struct SearchOverrideExclude { } impl SearchOverrideExclude { - pub fn new(id: String) -> SearchOverrideExclude{ - SearchOverrideExclude { - id, - } + pub fn new(id: String) -> SearchOverrideExclude { + SearchOverrideExclude { id } } } - diff --git a/typesense_codegen/src/models/search_override_include.rs b/typesense_codegen/src/models/search_override_include.rs index 5344b55..7756358 100644 --- a/typesense_codegen/src/models/search_override_include.rs +++ b/typesense_codegen/src/models/search_override_include.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -22,11 +22,7 @@ pub struct SearchOverrideInclude { } impl SearchOverrideInclude { - pub fn new(id: String, position: i32) -> SearchOverrideInclude{ - SearchOverrideInclude { - id, - position, - } + pub fn new(id: String, position: i32) -> SearchOverrideInclude { + SearchOverrideInclude { id, position } } } - diff --git a/typesense_codegen/src/models/search_override_rule.rs b/typesense_codegen/src/models/search_override_rule.rs index 3ce37a4..de9ebf5 100644 --- a/typesense_codegen/src/models/search_override_rule.rs +++ b/typesense_codegen/src/models/search_override_rule.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,16 +19,16 @@ pub struct SearchOverrideRule { /// Indicates what search queries should be overridden #[serde(rename = "query", skip_serializing_if = "Option::is_none")] pub query: Option, - /// Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. + /// Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. #[serde(rename = "match", skip_serializing_if = "Option::is_none")] pub r#match: Option, - /// Indicates that the override should apply when the filter_by parameter in a search query exactly matches the string specified here (including backticks, spaces, brackets, etc). + /// Indicates that the override should apply when the filter_by parameter in a search query exactly matches the string specified here (including backticks, spaces, brackets, etc). #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] pub filter_by: Option, } impl SearchOverrideRule { - pub fn new() -> SearchOverrideRule{ + pub fn new() -> SearchOverrideRule { SearchOverrideRule { tags: None, query: None, @@ -37,7 +37,7 @@ impl SearchOverrideRule { } } } -/// Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. +/// Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum Match { #[serde(rename = "exact")] @@ -51,4 +51,3 @@ impl Default for Match { Self::Exact } } - diff --git a/typesense_codegen/src/models/search_override_schema.rs b/typesense_codegen/src/models/search_override_schema.rs index 8dfdd8c..1b0eede 100644 --- a/typesense_codegen/src/models/search_override_schema.rs +++ b/typesense_codegen/src/models/search_override_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -21,37 +21,43 @@ pub struct SearchOverrideSchema { /// List of document `id`s that should be excluded from the search results. #[serde(rename = "excludes", skip_serializing_if = "Option::is_none")] pub excludes: Option>, - /// A filter by clause that is applied to any search query that matches the override rule. + /// A filter by clause that is applied to any search query that matches the override rule. #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] pub filter_by: Option, - /// Indicates whether search query tokens that exist in the override's rule should be removed from the search query. - #[serde(rename = "remove_matched_tokens", skip_serializing_if = "Option::is_none")] + /// Indicates whether search query tokens that exist in the override's rule should be removed from the search query. + #[serde( + rename = "remove_matched_tokens", + skip_serializing_if = "Option::is_none" + )] pub remove_matched_tokens: Option, - /// Return a custom JSON object in the Search API response, when this rule is triggered. This can can be used to display a pre-defined message (eg: a promotion banner) on the front-end when a particular rule is triggered. + /// Return a custom JSON object in the Search API response, when this rule is triggered. This can can be used to display a pre-defined message (eg: a promotion banner) on the front-end when a particular rule is triggered. #[serde(rename = "metadata", skip_serializing_if = "Option::is_none")] pub metadata: Option, - /// A sort by clause that is applied to any search query that matches the override rule. + /// A sort by clause that is applied to any search query that matches the override rule. #[serde(rename = "sort_by", skip_serializing_if = "Option::is_none")] pub sort_by: Option, - /// Replaces the current search query with this value, when the search query matches the override rule. + /// Replaces the current search query with this value, when the search query matches the override rule. #[serde(rename = "replace_query", skip_serializing_if = "Option::is_none")] pub replace_query: Option, - /// When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. - #[serde(rename = "filter_curated_hits", skip_serializing_if = "Option::is_none")] + /// When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. + #[serde( + rename = "filter_curated_hits", + skip_serializing_if = "Option::is_none" + )] pub filter_curated_hits: Option, - /// A Unix timestamp that indicates the date/time from which the override will be active. You can use this to create override rules that start applying from a future point in time. + /// A Unix timestamp that indicates the date/time from which the override will be active. You can use this to create override rules that start applying from a future point in time. #[serde(rename = "effective_from_ts", skip_serializing_if = "Option::is_none")] pub effective_from_ts: Option, - /// A Unix timestamp that indicates the date/time until which the override will be active. You can use this to create override rules that stop applying after a period of time. + /// A Unix timestamp that indicates the date/time until which the override will be active. You can use this to create override rules that stop applying after a period of time. #[serde(rename = "effective_to_ts", skip_serializing_if = "Option::is_none")] pub effective_to_ts: Option, - /// When set to true, override processing will stop at the first matching rule. When set to false override processing will continue and multiple override actions will be triggered in sequence. Overrides are processed in the lexical sort order of their id field. Default: true. + /// When set to true, override processing will stop at the first matching rule. When set to false override processing will continue and multiple override actions will be triggered in sequence. Overrides are processed in the lexical sort order of their id field. Default: true. #[serde(rename = "stop_processing", skip_serializing_if = "Option::is_none")] pub stop_processing: Option, } impl SearchOverrideSchema { - pub fn new(rule: models::SearchOverrideRule) -> SearchOverrideSchema{ + pub fn new(rule: models::SearchOverrideRule) -> SearchOverrideSchema { SearchOverrideSchema { rule: Box::new(rule), includes: None, @@ -68,4 +74,3 @@ impl SearchOverrideSchema { } } } - diff --git a/typesense_codegen/src/models/search_overrides_response.rs b/typesense_codegen/src/models/search_overrides_response.rs index eaef52b..fd8aba3 100644 --- a/typesense_codegen/src/models/search_overrides_response.rs +++ b/typesense_codegen/src/models/search_overrides_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +18,7 @@ pub struct SearchOverridesResponse { } impl SearchOverridesResponse { - pub fn new(overrides: Vec) -> SearchOverridesResponse{ - SearchOverridesResponse { - overrides, - } + pub fn new(overrides: Vec) -> SearchOverridesResponse { + SearchOverridesResponse { overrides } } } - diff --git a/typesense_codegen/src/models/search_parameters.rs b/typesense_codegen/src/models/search_parameters.rs index d1f8f89..860beff 100644 --- a/typesense_codegen/src/models/search_parameters.rs +++ b/typesense_codegen/src/models/search_parameters.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -49,7 +49,10 @@ pub struct SearchParameters { #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] pub filter_by: Option, /// Controls the number of similar words that Typesense considers during fuzzy search on filter_by values. Useful for controlling prefix matches like company_name:Acm*. - #[serde(rename = "max_filter_by_candidates", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "max_filter_by_candidates", + skip_serializing_if = "Option::is_none" + )] pub max_filter_by_candidates: Option, /// A list of numerical fields and their corresponding sort orders that will be used for ordering your results. Up to 3 sort fields can be specified. The text similarity score is exposed as a special `_text_match` field that you can use in the list of sorting fields. If no `sort_by` parameter is specified, results are sorted by `_text_match:desc,default_sorting_field:desc` #[serde(rename = "sort_by", skip_serializing_if = "Option::is_none")] @@ -63,7 +66,7 @@ pub struct SearchParameters { /// Facet values that are returned can now be filtered via this parameter. The matching facet text is also highlighted. For example, when faceting by `category`, you can set `facet_query=category:shoe` to return only facet values that contain the prefix \"shoe\". #[serde(rename = "facet_query", skip_serializing_if = "Option::is_none")] pub facet_query: Option, - /// The number of typographical errors (1 or 2) that would be tolerated. Default: 2 + /// The number of typographical errors (1 or 2) that would be tolerated. Default: 2 #[serde(rename = "num_typos", skip_serializing_if = "Option::is_none")] pub num_typos: Option, /// Results from this specific page number would be fetched. @@ -72,7 +75,7 @@ pub struct SearchParameters { /// Number of results to fetch per page. Default: 10 #[serde(rename = "per_page", skip_serializing_if = "Option::is_none")] pub per_page: Option, - /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. + /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. #[serde(rename = "limit", skip_serializing_if = "Option::is_none")] pub limit: Option, /// Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. @@ -81,11 +84,14 @@ pub struct SearchParameters { /// You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. #[serde(rename = "group_by", skip_serializing_if = "Option::is_none")] pub group_by: Option, - /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 + /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 #[serde(rename = "group_limit", skip_serializing_if = "Option::is_none")] pub group_limit: Option, - /// Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true - #[serde(rename = "group_missing_values", skip_serializing_if = "Option::is_none")] + /// Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true + #[serde( + rename = "group_missing_values", + skip_serializing_if = "Option::is_none" + )] pub group_missing_values: Option, /// List of fields from the document to include in the search result #[serde(rename = "include_fields", skip_serializing_if = "Option::is_none")] @@ -94,143 +100,194 @@ pub struct SearchParameters { #[serde(rename = "exclude_fields", skip_serializing_if = "Option::is_none")] pub exclude_fields: Option, /// List of fields which should be highlighted fully without snippeting - #[serde(rename = "highlight_full_fields", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "highlight_full_fields", + skip_serializing_if = "Option::is_none" + )] pub highlight_full_fields: Option, - /// The number of tokens that should surround the highlighted text on each side. Default: 4 - #[serde(rename = "highlight_affix_num_tokens", skip_serializing_if = "Option::is_none")] + /// The number of tokens that should surround the highlighted text on each side. Default: 4 + #[serde( + rename = "highlight_affix_num_tokens", + skip_serializing_if = "Option::is_none" + )] pub highlight_affix_num_tokens: Option, - /// The start tag used for the highlighted snippets. Default: `` - #[serde(rename = "highlight_start_tag", skip_serializing_if = "Option::is_none")] + /// The start tag used for the highlighted snippets. Default: `` + #[serde( + rename = "highlight_start_tag", + skip_serializing_if = "Option::is_none" + )] pub highlight_start_tag: Option, - /// The end tag used for the highlighted snippets. Default: `` + /// The end tag used for the highlighted snippets. Default: `` #[serde(rename = "highlight_end_tag", skip_serializing_if = "Option::is_none")] pub highlight_end_tag: Option, - /// Flag for enabling/disabling the deprecated, old highlight structure in the response. Default: true - #[serde(rename = "enable_highlight_v1", skip_serializing_if = "Option::is_none")] + /// Flag for enabling/disabling the deprecated, old highlight structure in the response. Default: true + #[serde( + rename = "enable_highlight_v1", + skip_serializing_if = "Option::is_none" + )] pub enable_highlight_v1: Option, - /// Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). + /// Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). #[serde(rename = "enable_analytics", skip_serializing_if = "Option::is_none")] pub enable_analytics: Option, - /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 + /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 #[serde(rename = "snippet_threshold", skip_serializing_if = "Option::is_none")] pub snippet_threshold: Option, /// List of synonym set names to associate with this search query #[serde(rename = "synonym_sets", skip_serializing_if = "Option::is_none")] pub synonym_sets: Option, - /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 - #[serde(rename = "drop_tokens_threshold", skip_serializing_if = "Option::is_none")] + /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 + #[serde( + rename = "drop_tokens_threshold", + skip_serializing_if = "Option::is_none" + )] pub drop_tokens_threshold: Option, #[serde(rename = "drop_tokens_mode", skip_serializing_if = "Option::is_none")] pub drop_tokens_mode: Option, - /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 - #[serde(rename = "typo_tokens_threshold", skip_serializing_if = "Option::is_none")] + /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 + #[serde( + rename = "typo_tokens_threshold", + skip_serializing_if = "Option::is_none" + )] pub typo_tokens_threshold: Option, - /// Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. - #[serde(rename = "enable_typos_for_alpha_numerical_tokens", skip_serializing_if = "Option::is_none")] + /// Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + #[serde( + rename = "enable_typos_for_alpha_numerical_tokens", + skip_serializing_if = "Option::is_none" + )] pub enable_typos_for_alpha_numerical_tokens: Option, - /// Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false - #[serde(rename = "filter_curated_hits", skip_serializing_if = "Option::is_none")] + /// Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + #[serde( + rename = "filter_curated_hits", + skip_serializing_if = "Option::is_none" + )] pub filter_curated_hits: Option, - /// If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + /// If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true #[serde(rename = "enable_synonyms", skip_serializing_if = "Option::is_none")] pub enable_synonyms: Option, - /// Allow synonym resolution on word prefixes in the query. Default: false + /// Allow synonym resolution on word prefixes in the query. Default: false #[serde(rename = "synonym_prefix", skip_serializing_if = "Option::is_none")] pub synonym_prefix: Option, - /// Allow synonym resolution on typo-corrected words in the query. Default: 0 + /// Allow synonym resolution on typo-corrected words in the query. Default: 0 #[serde(rename = "synonym_num_typos", skip_serializing_if = "Option::is_none")] pub synonym_num_typos: Option, - /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "pinned_hits", skip_serializing_if = "Option::is_none")] pub pinned_hits: Option, - /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "hidden_hits", skip_serializing_if = "Option::is_none")] pub hidden_hits: Option, /// Comma separated list of tags to trigger the curations rules that match the tags. #[serde(rename = "override_tags", skip_serializing_if = "Option::is_none")] pub override_tags: Option, - /// A list of custom fields that must be highlighted even if you don't query for them + /// A list of custom fields that must be highlighted even if you don't query for them #[serde(rename = "highlight_fields", skip_serializing_if = "Option::is_none")] pub highlight_fields: Option, - /// Treat space as typo: search for q=basket ball if q=basketball is not found or vice-versa. Splitting/joining of tokens will only be attempted if the original query produces no results. To always trigger this behavior, set value to `always``. To disable, set value to `off`. Default is `fallback`. + /// Treat space as typo: search for q=basket ball if q=basketball is not found or vice-versa. Splitting/joining of tokens will only be attempted if the original query produces no results. To always trigger this behavior, set value to `always``. To disable, set value to `off`. Default is `fallback`. #[serde(rename = "split_join_tokens", skip_serializing_if = "Option::is_none")] pub split_join_tokens: Option, - /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same - #[serde(rename = "pre_segmented_query", skip_serializing_if = "Option::is_none")] + /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same + #[serde( + rename = "pre_segmented_query", + skip_serializing_if = "Option::is_none" + )] pub pre_segmented_query: Option, - /// Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. + /// Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. #[serde(rename = "preset", skip_serializing_if = "Option::is_none")] pub preset: Option, - /// If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false + /// If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false #[serde(rename = "enable_overrides", skip_serializing_if = "Option::is_none")] pub enable_overrides: Option, - /// Set this parameter to true to ensure that an exact match is ranked above the others - #[serde(rename = "prioritize_exact_match", skip_serializing_if = "Option::is_none")] + /// Set this parameter to true to ensure that an exact match is ranked above the others + #[serde( + rename = "prioritize_exact_match", + skip_serializing_if = "Option::is_none" + )] pub prioritize_exact_match: Option, - /// Control the number of words that Typesense considers for typo and prefix searching. + /// Control the number of words that Typesense considers for typo and prefix searching. #[serde(rename = "max_candidates", skip_serializing_if = "Option::is_none")] pub max_candidates: Option, - /// Make Typesense prioritize documents where the query words appear earlier in the text. - #[serde(rename = "prioritize_token_position", skip_serializing_if = "Option::is_none")] + /// Make Typesense prioritize documents where the query words appear earlier in the text. + #[serde( + rename = "prioritize_token_position", + skip_serializing_if = "Option::is_none" + )] pub prioritize_token_position: Option, - /// Make Typesense prioritize documents where the query words appear in more number of fields. - #[serde(rename = "prioritize_num_matching_fields", skip_serializing_if = "Option::is_none")] + /// Make Typesense prioritize documents where the query words appear in more number of fields. + #[serde( + rename = "prioritize_num_matching_fields", + skip_serializing_if = "Option::is_none" + )] pub prioritize_num_matching_fields: Option, - /// Make Typesense disable typos for numerical tokens. - #[serde(rename = "enable_typos_for_numerical_tokens", skip_serializing_if = "Option::is_none")] + /// Make Typesense disable typos for numerical tokens. + #[serde( + rename = "enable_typos_for_numerical_tokens", + skip_serializing_if = "Option::is_none" + )] pub enable_typos_for_numerical_tokens: Option, - /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). + /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). #[serde(rename = "exhaustive_search", skip_serializing_if = "Option::is_none")] pub exhaustive_search: Option, - /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. + /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. #[serde(rename = "search_cutoff_ms", skip_serializing_if = "Option::is_none")] pub search_cutoff_ms: Option, - /// Enable server side caching of search query results. By default, caching is disabled. + /// Enable server side caching of search query results. By default, caching is disabled. #[serde(rename = "use_cache", skip_serializing_if = "Option::is_none")] pub use_cache: Option, - /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. + /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. #[serde(rename = "cache_ttl", skip_serializing_if = "Option::is_none")] pub cache_ttl: Option, - /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_1typo", skip_serializing_if = "Option::is_none")] pub min_len_1typo: Option, - /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_2typo", skip_serializing_if = "Option::is_none")] pub min_len_2typo: Option, - /// Vector query expression for fetching documents \"closest\" to a given query/document vector. + /// Vector query expression for fetching documents \"closest\" to a given query/document vector. #[serde(rename = "vector_query", skip_serializing_if = "Option::is_none")] pub vector_query: Option, - /// Timeout (in milliseconds) for fetching remote embeddings. - #[serde(rename = "remote_embedding_timeout_ms", skip_serializing_if = "Option::is_none")] + /// Timeout (in milliseconds) for fetching remote embeddings. + #[serde( + rename = "remote_embedding_timeout_ms", + skip_serializing_if = "Option::is_none" + )] pub remote_embedding_timeout_ms: Option, - /// Number of times to retry fetching remote embeddings. - #[serde(rename = "remote_embedding_num_tries", skip_serializing_if = "Option::is_none")] + /// Number of times to retry fetching remote embeddings. + #[serde( + rename = "remote_embedding_num_tries", + skip_serializing_if = "Option::is_none" + )] pub remote_embedding_num_tries: Option, - /// Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). + /// Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). #[serde(rename = "facet_strategy", skip_serializing_if = "Option::is_none")] pub facet_strategy: Option, - /// Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. + /// Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. #[serde(rename = "stopwords", skip_serializing_if = "Option::is_none")] pub stopwords: Option, - /// Comma separated string of nested facet fields whose parent object should be returned in facet response. - #[serde(rename = "facet_return_parent", skip_serializing_if = "Option::is_none")] + /// Comma separated string of nested facet fields whose parent object should be returned in facet response. + #[serde( + rename = "facet_return_parent", + skip_serializing_if = "Option::is_none" + )] pub facet_return_parent: Option, - /// The base64 encoded audio file in 16 khz 16-bit WAV format. + /// The base64 encoded audio file in 16 khz 16-bit WAV format. #[serde(rename = "voice_query", skip_serializing_if = "Option::is_none")] pub voice_query: Option, - /// Enable conversational search. + /// Enable conversational search. #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] pub conversation: Option, - /// The Id of Conversation Model to be used. - #[serde(rename = "conversation_model_id", skip_serializing_if = "Option::is_none")] + /// The Id of Conversation Model to be used. + #[serde( + rename = "conversation_model_id", + skip_serializing_if = "Option::is_none" + )] pub conversation_model_id: Option, - /// The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + /// The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. #[serde(rename = "conversation_id", skip_serializing_if = "Option::is_none")] pub conversation_id: Option, } impl SearchParameters { - pub fn new() -> SearchParameters{ + pub fn new() -> SearchParameters { SearchParameters { q: None, query_by: None, @@ -306,4 +363,3 @@ impl SearchParameters { } } } - diff --git a/typesense_codegen/src/models/search_request_params.rs b/typesense_codegen/src/models/search_request_params.rs index 727ebb7..7e67048 100644 --- a/typesense_codegen/src/models/search_request_params.rs +++ b/typesense_codegen/src/models/search_request_params.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -24,7 +24,7 @@ pub struct SearchRequestParams { } impl SearchRequestParams { - pub fn new(collection_name: String, q: String, per_page: i32) -> SearchRequestParams{ + pub fn new(collection_name: String, q: String, per_page: i32) -> SearchRequestParams { SearchRequestParams { collection_name, q, @@ -33,4 +33,3 @@ impl SearchRequestParams { } } } - diff --git a/typesense_codegen/src/models/search_request_params_voice_query.rs b/typesense_codegen/src/models/search_request_params_voice_query.rs index b5fd5a3..97e78ef 100644 --- a/typesense_codegen/src/models/search_request_params_voice_query.rs +++ b/typesense_codegen/src/models/search_request_params_voice_query.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +18,9 @@ pub struct SearchRequestParamsVoiceQuery { } impl SearchRequestParamsVoiceQuery { - pub fn new() -> SearchRequestParamsVoiceQuery{ + pub fn new() -> SearchRequestParamsVoiceQuery { SearchRequestParamsVoiceQuery { transcribed_query: None, } } } - diff --git a/typesense_codegen/src/models/search_result.rs b/typesense_codegen/src/models/search_result.rs index b1630c9..f5ea5b5 100644 --- a/typesense_codegen/src/models/search_result.rs +++ b/typesense_codegen/src/models/search_result.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -42,12 +42,15 @@ pub struct SearchResult { #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] pub conversation: Option>, /// Returned only for union query response. - #[serde(rename = "union_request_params", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "union_request_params", + skip_serializing_if = "Option::is_none" + )] pub union_request_params: Option>, } impl SearchResult { - pub fn new() -> SearchResult{ + pub fn new() -> SearchResult { SearchResult { facet_counts: None, found: None, @@ -64,4 +67,3 @@ impl SearchResult { } } } - diff --git a/typesense_codegen/src/models/search_result_conversation.rs b/typesense_codegen/src/models/search_result_conversation.rs index c47f800..380be44 100644 --- a/typesense_codegen/src/models/search_result_conversation.rs +++ b/typesense_codegen/src/models/search_result_conversation.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -24,7 +24,12 @@ pub struct SearchResultConversation { } impl SearchResultConversation { - pub fn new(answer: String, conversation_history: Vec, conversation_id: String, query: String) -> SearchResultConversation{ + pub fn new( + answer: String, + conversation_history: Vec, + conversation_id: String, + query: String, + ) -> SearchResultConversation { SearchResultConversation { answer, conversation_history, @@ -33,4 +38,3 @@ impl SearchResultConversation { } } } - diff --git a/typesense_codegen/src/models/search_result_hit.rs b/typesense_codegen/src/models/search_result_hit.rs index 8ffb5e4..abe92e4 100644 --- a/typesense_codegen/src/models/search_result_hit.rs +++ b/typesense_codegen/src/models/search_result_hit.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -27,7 +27,10 @@ pub struct SearchResultHit { #[serde(rename = "text_match_info", skip_serializing_if = "Option::is_none")] pub text_match_info: Option>, /// Can be any key-value pair - #[serde(rename = "geo_distance_meters", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "geo_distance_meters", + skip_serializing_if = "Option::is_none" + )] pub geo_distance_meters: Option>, /// Distance between the query vector and matching document's vector value #[serde(rename = "vector_distance", skip_serializing_if = "Option::is_none")] @@ -40,7 +43,7 @@ pub struct SearchResultHit { } impl SearchResultHit { - pub fn new() -> SearchResultHit{ + pub fn new() -> SearchResultHit { SearchResultHit { highlights: None, highlight: None, @@ -54,4 +57,3 @@ impl SearchResultHit { } } } - diff --git a/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs b/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs index def14c5..ed0bea0 100644 --- a/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs +++ b/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -21,10 +21,9 @@ pub struct SearchResultHitHybridSearchInfo { impl SearchResultHitHybridSearchInfo { /// Information about hybrid search scoring - pub fn new() -> SearchResultHitHybridSearchInfo{ + pub fn new() -> SearchResultHitHybridSearchInfo { SearchResultHitHybridSearchInfo { rank_fusion_score: None, } } } - diff --git a/typesense_codegen/src/models/search_result_hit_text_match_info.rs b/typesense_codegen/src/models/search_result_hit_text_match_info.rs index 6ad7736..e77c40f 100644 --- a/typesense_codegen/src/models/search_result_hit_text_match_info.rs +++ b/typesense_codegen/src/models/search_result_hit_text_match_info.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -30,7 +30,7 @@ pub struct SearchResultHitTextMatchInfo { } impl SearchResultHitTextMatchInfo { - pub fn new() -> SearchResultHitTextMatchInfo{ + pub fn new() -> SearchResultHitTextMatchInfo { SearchResultHitTextMatchInfo { best_field_score: None, best_field_weight: None, @@ -42,4 +42,3 @@ impl SearchResultHitTextMatchInfo { } } } - diff --git a/typesense_codegen/src/models/search_synonym.rs b/typesense_codegen/src/models/search_synonym.rs index 4310dab..3d81eb7 100644 --- a/typesense_codegen/src/models/search_synonym.rs +++ b/typesense_codegen/src/models/search_synonym.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -30,7 +30,7 @@ pub struct SearchSynonym { } impl SearchSynonym { - pub fn new(synonyms: Vec, id: String) -> SearchSynonym{ + pub fn new(synonyms: Vec, id: String) -> SearchSynonym { SearchSynonym { root: None, synonyms, @@ -40,4 +40,3 @@ impl SearchSynonym { } } } - diff --git a/typesense_codegen/src/models/search_synonym_delete_response.rs b/typesense_codegen/src/models/search_synonym_delete_response.rs index d138eab..c69e47b 100644 --- a/typesense_codegen/src/models/search_synonym_delete_response.rs +++ b/typesense_codegen/src/models/search_synonym_delete_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,10 +19,7 @@ pub struct SearchSynonymDeleteResponse { } impl SearchSynonymDeleteResponse { - pub fn new(id: String) -> SearchSynonymDeleteResponse{ - SearchSynonymDeleteResponse { - id, - } + pub fn new(id: String) -> SearchSynonymDeleteResponse { + SearchSynonymDeleteResponse { id } } } - diff --git a/typesense_codegen/src/models/search_synonym_schema.rs b/typesense_codegen/src/models/search_synonym_schema.rs index 99a96a9..192829f 100644 --- a/typesense_codegen/src/models/search_synonym_schema.rs +++ b/typesense_codegen/src/models/search_synonym_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -28,7 +28,7 @@ pub struct SearchSynonymSchema { } impl SearchSynonymSchema { - pub fn new(synonyms: Vec) -> SearchSynonymSchema{ + pub fn new(synonyms: Vec) -> SearchSynonymSchema { SearchSynonymSchema { root: None, synonyms, @@ -37,4 +37,3 @@ impl SearchSynonymSchema { } } } - diff --git a/typesense_codegen/src/models/search_synonyms_response.rs b/typesense_codegen/src/models/search_synonyms_response.rs index eab2311..40434ca 100644 --- a/typesense_codegen/src/models/search_synonyms_response.rs +++ b/typesense_codegen/src/models/search_synonyms_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +18,7 @@ pub struct SearchSynonymsResponse { } impl SearchSynonymsResponse { - pub fn new(synonyms: Vec) -> SearchSynonymsResponse{ - SearchSynonymsResponse { - synonyms, - } + pub fn new(synonyms: Vec) -> SearchSynonymsResponse { + SearchSynonymsResponse { synonyms } } } - diff --git a/typesense_codegen/src/models/stemming_dictionary.rs b/typesense_codegen/src/models/stemming_dictionary.rs index 3976e9c..e90942c 100644 --- a/typesense_codegen/src/models/stemming_dictionary.rs +++ b/typesense_codegen/src/models/stemming_dictionary.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -22,11 +22,7 @@ pub struct StemmingDictionary { } impl StemmingDictionary { - pub fn new(id: String, words: Vec) -> StemmingDictionary{ - StemmingDictionary { - id, - words, - } + pub fn new(id: String, words: Vec) -> StemmingDictionary { + StemmingDictionary { id, words } } } - diff --git a/typesense_codegen/src/models/stemming_dictionary_words_inner.rs b/typesense_codegen/src/models/stemming_dictionary_words_inner.rs index c712b4b..30cbd40 100644 --- a/typesense_codegen/src/models/stemming_dictionary_words_inner.rs +++ b/typesense_codegen/src/models/stemming_dictionary_words_inner.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -22,11 +22,7 @@ pub struct StemmingDictionaryWordsInner { } impl StemmingDictionaryWordsInner { - pub fn new(word: String, root: String) -> StemmingDictionaryWordsInner{ - StemmingDictionaryWordsInner { - word, - root, - } + pub fn new(word: String, root: String) -> StemmingDictionaryWordsInner { + StemmingDictionaryWordsInner { word, root } } } - diff --git a/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs b/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs index c3b7b9c..b1b6913 100644 --- a/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs +++ b/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +18,9 @@ pub struct StopwordsSetRetrieveSchema { } impl StopwordsSetRetrieveSchema { - pub fn new(stopwords: models::StopwordsSetSchema) -> StopwordsSetRetrieveSchema{ + pub fn new(stopwords: models::StopwordsSetSchema) -> StopwordsSetRetrieveSchema { StopwordsSetRetrieveSchema { stopwords: Box::new(stopwords), } } } - diff --git a/typesense_codegen/src/models/stopwords_set_schema.rs b/typesense_codegen/src/models/stopwords_set_schema.rs index bf1dace..8f13dee 100644 --- a/typesense_codegen/src/models/stopwords_set_schema.rs +++ b/typesense_codegen/src/models/stopwords_set_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -22,7 +22,7 @@ pub struct StopwordsSetSchema { } impl StopwordsSetSchema { - pub fn new(id: String, stopwords: Vec) -> StopwordsSetSchema{ + pub fn new(id: String, stopwords: Vec) -> StopwordsSetSchema { StopwordsSetSchema { id, stopwords, @@ -30,4 +30,3 @@ impl StopwordsSetSchema { } } } - diff --git a/typesense_codegen/src/models/stopwords_set_upsert_schema.rs b/typesense_codegen/src/models/stopwords_set_upsert_schema.rs index 2feb7f1..1facab5 100644 --- a/typesense_codegen/src/models/stopwords_set_upsert_schema.rs +++ b/typesense_codegen/src/models/stopwords_set_upsert_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -20,11 +20,10 @@ pub struct StopwordsSetUpsertSchema { } impl StopwordsSetUpsertSchema { - pub fn new(stopwords: Vec) -> StopwordsSetUpsertSchema{ + pub fn new(stopwords: Vec) -> StopwordsSetUpsertSchema { StopwordsSetUpsertSchema { stopwords, locale: None, } } } - diff --git a/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs b/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs index 8e26e17..84703ac 100644 --- a/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs +++ b/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +18,7 @@ pub struct StopwordsSetsRetrieveAllSchema { } impl StopwordsSetsRetrieveAllSchema { - pub fn new(stopwords: Vec) -> StopwordsSetsRetrieveAllSchema{ - StopwordsSetsRetrieveAllSchema { - stopwords, - } + pub fn new(stopwords: Vec) -> StopwordsSetsRetrieveAllSchema { + StopwordsSetsRetrieveAllSchema { stopwords } } } - diff --git a/typesense_codegen/src/models/success_status.rs b/typesense_codegen/src/models/success_status.rs index 9b1f636..c88ecb9 100644 --- a/typesense_codegen/src/models/success_status.rs +++ b/typesense_codegen/src/models/success_status.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +18,7 @@ pub struct SuccessStatus { } impl SuccessStatus { - pub fn new(success: bool) -> SuccessStatus{ - SuccessStatus { - success, - } + pub fn new(success: bool) -> SuccessStatus { + SuccessStatus { success } } } - diff --git a/typesense_codegen/src/models/synonym_item_schema.rs b/typesense_codegen/src/models/synonym_item_schema.rs index 8b1d84b..bb03da3 100644 --- a/typesense_codegen/src/models/synonym_item_schema.rs +++ b/typesense_codegen/src/models/synonym_item_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -31,7 +31,7 @@ pub struct SynonymItemSchema { } impl SynonymItemSchema { - pub fn new(id: String, synonyms: Vec) -> SynonymItemSchema{ + pub fn new(id: String, synonyms: Vec) -> SynonymItemSchema { SynonymItemSchema { id, synonyms, @@ -41,4 +41,3 @@ impl SynonymItemSchema { } } } - diff --git a/typesense_codegen/src/models/synonym_set_create_schema.rs b/typesense_codegen/src/models/synonym_set_create_schema.rs index c52dac9..818ae98 100644 --- a/typesense_codegen/src/models/synonym_set_create_schema.rs +++ b/typesense_codegen/src/models/synonym_set_create_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,10 +19,7 @@ pub struct SynonymSetCreateSchema { } impl SynonymSetCreateSchema { - pub fn new(items: Vec) -> SynonymSetCreateSchema{ - SynonymSetCreateSchema { - items, - } + pub fn new(items: Vec) -> SynonymSetCreateSchema { + SynonymSetCreateSchema { items } } } - diff --git a/typesense_codegen/src/models/synonym_set_delete_schema.rs b/typesense_codegen/src/models/synonym_set_delete_schema.rs index e345e32..e127040 100644 --- a/typesense_codegen/src/models/synonym_set_delete_schema.rs +++ b/typesense_codegen/src/models/synonym_set_delete_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,10 +19,7 @@ pub struct SynonymSetDeleteSchema { } impl SynonymSetDeleteSchema { - pub fn new(name: String) -> SynonymSetDeleteSchema{ - SynonymSetDeleteSchema { - name, - } + pub fn new(name: String) -> SynonymSetDeleteSchema { + SynonymSetDeleteSchema { name } } } - diff --git a/typesense_codegen/src/models/synonym_set_schema.rs b/typesense_codegen/src/models/synonym_set_schema.rs index b500baf..f9e171c 100644 --- a/typesense_codegen/src/models/synonym_set_schema.rs +++ b/typesense_codegen/src/models/synonym_set_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -22,11 +22,7 @@ pub struct SynonymSetSchema { } impl SynonymSetSchema { - pub fn new(items: Vec, name: String) -> SynonymSetSchema{ - SynonymSetSchema { - items, - name, - } + pub fn new(items: Vec, name: String) -> SynonymSetSchema { + SynonymSetSchema { items, name } } } - diff --git a/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs b/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs index ac28af6..612c1a5 100644 --- a/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs +++ b/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,10 +19,7 @@ pub struct SynonymSetsRetrieveSchema { } impl SynonymSetsRetrieveSchema { - pub fn new(synonym_sets: Vec) -> SynonymSetsRetrieveSchema{ - SynonymSetsRetrieveSchema { - synonym_sets, - } + pub fn new(synonym_sets: Vec) -> SynonymSetsRetrieveSchema { + SynonymSetsRetrieveSchema { synonym_sets } } } - diff --git a/typesense_codegen/src/models/toggle_slow_request_log_request.rs b/typesense_codegen/src/models/toggle_slow_request_log_request.rs index fdce446..2957298 100644 --- a/typesense_codegen/src/models/toggle_slow_request_log_request.rs +++ b/typesense_codegen/src/models/toggle_slow_request_log_request.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +18,9 @@ pub struct ToggleSlowRequestLogRequest { } impl ToggleSlowRequestLogRequest { - pub fn new(log_slow_requests_time_ms: i32) -> ToggleSlowRequestLogRequest{ + pub fn new(log_slow_requests_time_ms: i32) -> ToggleSlowRequestLogRequest { ToggleSlowRequestLogRequest { log_slow_requests_time_ms, } } } - diff --git a/typesense_codegen/src/models/update_documents_200_response.rs b/typesense_codegen/src/models/update_documents_200_response.rs index 48d8905..88cc7b4 100644 --- a/typesense_codegen/src/models/update_documents_200_response.rs +++ b/typesense_codegen/src/models/update_documents_200_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,10 +19,7 @@ pub struct UpdateDocuments200Response { } impl UpdateDocuments200Response { - pub fn new(num_updated: i32) -> UpdateDocuments200Response{ - UpdateDocuments200Response { - num_updated, - } + pub fn new(num_updated: i32) -> UpdateDocuments200Response { + UpdateDocuments200Response { num_updated } } } - diff --git a/typesense_codegen/src/models/update_documents_parameters.rs b/typesense_codegen/src/models/update_documents_parameters.rs index 36ce061..cf49cbb 100644 --- a/typesense_codegen/src/models/update_documents_parameters.rs +++ b/typesense_codegen/src/models/update_documents_parameters.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +18,7 @@ pub struct UpdateDocumentsParameters { } impl UpdateDocumentsParameters { - pub fn new() -> UpdateDocumentsParameters{ - UpdateDocumentsParameters { - filter_by: None, - } + pub fn new() -> UpdateDocumentsParameters { + UpdateDocumentsParameters { filter_by: None } } } - diff --git a/typesense_codegen/src/models/voice_query_model_collection_config.rs b/typesense_codegen/src/models/voice_query_model_collection_config.rs index 99cb770..38044c9 100644 --- a/typesense_codegen/src/models/voice_query_model_collection_config.rs +++ b/typesense_codegen/src/models/voice_query_model_collection_config.rs @@ -4,14 +4,14 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ use crate::models; use serde::{Deserialize, Serialize}; -/// VoiceQueryModelCollectionConfig : Configuration for the voice query model +/// VoiceQueryModelCollectionConfig : Configuration for the voice query model #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct VoiceQueryModelCollectionConfig { #[serde(rename = "model_name", skip_serializing_if = "Option::is_none")] @@ -19,11 +19,8 @@ pub struct VoiceQueryModelCollectionConfig { } impl VoiceQueryModelCollectionConfig { - /// Configuration for the voice query model - pub fn new() -> VoiceQueryModelCollectionConfig{ - VoiceQueryModelCollectionConfig { - model_name: None, - } + /// Configuration for the voice query model + pub fn new() -> VoiceQueryModelCollectionConfig { + VoiceQueryModelCollectionConfig { model_name: None } } } - diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 9b3ab05..dfb3d1f 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -1,8 +1,6 @@ use anyhow::{Context, Result}; use clap::{Parser, ValueEnum}; -use std::env; -use std::fs; -use std::process::Command; +use std::{env, fs, process::Command}; mod preprocess_openapi; use preprocess_openapi::preprocess_openapi_file; From b83084c096302de034e457ab36153c9e30d33aed Mon Sep 17 00:00:00 2001 From: RoDmitry Date: Thu, 11 Sep 2025 16:14:07 +0000 Subject: [PATCH 21/41] inline --- typesense/src/client/keys.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/typesense/src/client/keys.rs b/typesense/src/client/keys.rs index ef4f57f..70dd976 100644 --- a/typesense/src/client/keys.rs +++ b/typesense/src/client/keys.rs @@ -32,6 +32,7 @@ impl<'a> Keys<'a> { /// /// # Arguments /// * `schema` - An `ApiKeySchema` object describing the key's permissions. + #[inline] pub async fn create( &self, schema: models::ApiKeySchema, @@ -43,6 +44,7 @@ impl<'a> Keys<'a> { } /// Lists all API keys and their metadata. + #[inline] pub async fn retrieve(&self) -> Result> { execute_wrapper!(self, keys_api::get_keys) } From 7d7e1c9d0d0bd2400293a02c52617d8a9ec01e00 Mon Sep 17 00:00:00 2001 From: RoDmitry Date: Thu, 11 Sep 2025 16:40:04 +0000 Subject: [PATCH 22/41] Get next node faster for a single node config --- typesense/src/client/mod.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/typesense/src/client/mod.rs b/typesense/src/client/mod.rs index 7a70e97..9fb6df0 100644 --- a/typesense/src/client/mod.rs +++ b/typesense/src/client/mod.rs @@ -199,7 +199,9 @@ impl Client { )] nodes: Vec, #[builder(into)] - /// An optional, preferred node to try first for every request. This is for your server-side load balancer. + /// An optional, preferred node to try first for every request. + /// This is for your server-side load balancer. + /// Do not add this node to all nodes list, should be a separate one. nearest_node: Option, #[builder(default = Duration::from_secs(60))] /// The duration after which an unhealthy node will be retried for requests. @@ -268,6 +270,11 @@ impl Client { /// Selects the next node to use for a request based on health and priority. fn get_next_node(&self) -> &Node { + // if only one node (including nearest) + if self.nodes.len() == 1 { + return self.nodes.first().unwrap_safe_unchecked(); + } + let (nodes_len, mut index) = if self.is_nearest_node_set { let last_node_index = self.nodes.len() - 1; (last_node_index, last_node_index) From f16f30f8cf3a7f3777017eb5af0ad4f941303ec4 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Fri, 12 Sep 2025 14:56:57 +0700 Subject: [PATCH 23/41] feat: add openapi vendor attributes directly through xtask --- openapi.yml | 21 - preprocessed_openapi.yml | 34 +- typesense_codegen/src/apis/analytics_api.rs | 272 +++------ typesense_codegen/src/apis/collections_api.rs | 293 +++------- .../src/apis/conversations_api.rs | 166 ++---- typesense_codegen/src/apis/curation_api.rs | 112 +--- typesense_codegen/src/apis/debug_api.rs | 33 +- typesense_codegen/src/apis/documents_api.rs | 529 ++++-------------- typesense_codegen/src/apis/health_api.rs | 33 +- typesense_codegen/src/apis/keys_api.rs | 131 ++--- .../src/apis/nl_search_models_api.rs | 163 ++---- typesense_codegen/src/apis/operations_api.rs | 220 ++------ typesense_codegen/src/apis/override_api.rs | 43 +- typesense_codegen/src/apis/presets_api.rs | 133 ++--- typesense_codegen/src/apis/stemming_api.rs | 95 +--- typesense_codegen/src/apis/stopwords_api.rs | 133 ++--- typesense_codegen/src/apis/synonyms_api.rs | 133 ++--- .../src/models/analytics_event.rs | 9 +- .../models/analytics_event_create_response.rs | 9 +- .../src/models/analytics_event_data.rs | 5 +- .../src/models/analytics_events_response.rs | 9 +- .../analytics_events_response_events_inner.rs | 5 +- .../src/models/analytics_rule.rs | 12 +- .../src/models/analytics_rule_create.rs | 12 +- .../models/analytics_rule_create_params.rs | 15 +- .../src/models/analytics_rule_update.rs | 5 +- .../src/models/analytics_status.rs | 20 +- typesense_codegen/src/models/api_key.rs | 5 +- .../src/models/api_key_delete_response.rs | 9 +- .../src/models/api_key_schema.rs | 9 +- .../src/models/api_keys_response.rs | 9 +- typesense_codegen/src/models/api_response.rs | 9 +- .../src/models/api_stats_response.rs | 45 +- .../src/models/collection_alias.rs | 5 +- .../src/models/collection_alias_schema.rs | 9 +- .../src/models/collection_aliases_response.rs | 9 +- .../src/models/collection_response.rs | 26 +- .../src/models/collection_schema.rs | 21 +- .../src/models/collection_update_schema.rs | 7 +- .../conversation_model_create_schema.rs | 13 +- .../src/models/conversation_model_schema.rs | 14 +- .../conversation_model_update_schema.rs | 9 +- .../create_analytics_rule_200_response.rs | 5 +- ...nalytics_rule_200_response_one_of_inner.rs | 12 +- ...s_rule_200_response_one_of_inner_any_of.rs | 9 +- .../models/create_analytics_rule_request.rs | 5 +- .../src/models/debug_200_response.rs | 9 +- .../models/delete_documents_200_response.rs | 9 +- .../src/models/delete_documents_parameters.rs | 5 +- .../delete_stopwords_set_200_response.rs | 9 +- typesense_codegen/src/models/dirty_values.rs | 6 +- .../src/models/drop_tokens_mode.rs | 8 +- .../src/models/export_documents_parameters.rs | 5 +- typesense_codegen/src/models/facet_counts.rs | 5 +- .../src/models/facet_counts_counts_inner.rs | 5 +- .../src/models/facet_counts_stats.rs | 5 +- typesense_codegen/src/models/field.rs | 19 +- typesense_codegen/src/models/field_embed.rs | 5 +- .../src/models/field_embed_model_config.rs | 5 +- .../src/models/get_collections_parameters.rs | 7 +- typesense_codegen/src/models/health_status.rs | 9 +- .../src/models/import_documents_parameters.rs | 10 +- typesense_codegen/src/models/index_action.rs | 6 +- ...list_stemming_dictionaries_200_response.rs | 9 +- .../multi_search_collection_parameters.rs | 188 +++---- .../src/models/multi_search_parameters.rs | 178 +++--- .../src/models/multi_search_result.rs | 5 +- .../src/models/multi_search_result_item.rs | 10 +- .../models/multi_search_searches_parameter.rs | 7 +- .../src/models/nl_search_model_base.rs | 5 +- .../models/nl_search_model_create_schema.rs | 5 +- .../models/nl_search_model_delete_schema.rs | 9 +- .../src/models/nl_search_model_schema.rs | 5 +- .../src/models/preset_delete_schema.rs | 9 +- typesense_codegen/src/models/preset_schema.rs | 5 +- .../src/models/preset_upsert_schema.rs | 5 +- .../src/models/preset_upsert_schema_value.rs | 3 +- .../src/models/presets_retrieve_schema.rs | 9 +- .../src/models/schema_change_status.rs | 5 +- .../src/models/search_grouped_hit.rs | 8 +- .../src/models/search_highlight.rs | 5 +- .../src/models/search_override.rs | 33 +- .../models/search_override_delete_response.rs | 9 +- .../src/models/search_override_exclude.rs | 9 +- .../src/models/search_override_include.rs | 10 +- .../src/models/search_override_rule.rs | 11 +- .../src/models/search_override_schema.rs | 33 +- .../src/models/search_overrides_response.rs | 9 +- .../src/models/search_parameters.rs | 190 +++---- .../src/models/search_request_params.rs | 5 +- .../search_request_params_voice_query.rs | 5 +- typesense_codegen/src/models/search_result.rs | 10 +- .../src/models/search_result_conversation.rs | 10 +- .../src/models/search_result_hit.rs | 10 +- .../search_result_hit_hybrid_search_info.rs | 5 +- .../search_result_hit_text_match_info.rs | 5 +- .../src/models/search_synonym.rs | 5 +- .../models/search_synonym_delete_response.rs | 9 +- .../src/models/search_synonym_schema.rs | 5 +- .../src/models/search_synonyms_response.rs | 9 +- .../src/models/stemming_dictionary.rs | 10 +- .../models/stemming_dictionary_words_inner.rs | 10 +- .../models/stopwords_set_retrieve_schema.rs | 5 +- .../src/models/stopwords_set_schema.rs | 5 +- .../src/models/stopwords_set_upsert_schema.rs | 5 +- .../stopwords_sets_retrieve_all_schema.rs | 9 +- .../src/models/success_status.rs | 9 +- .../src/models/synonym_item_schema.rs | 5 +- .../src/models/synonym_set_create_schema.rs | 9 +- .../src/models/synonym_set_delete_schema.rs | 9 +- .../src/models/synonym_set_schema.rs | 10 +- .../models/synonym_sets_retrieve_schema.rs | 9 +- .../models/toggle_slow_request_log_request.rs | 5 +- .../models/update_documents_200_response.rs | 9 +- .../src/models/update_documents_parameters.rs | 9 +- .../voice_query_model_collection_config.rs | 13 +- xtask/src/add_vendor_attributes.rs | 66 +++ xtask/src/main.rs | 2 + xtask/src/preprocess_openapi.rs | 6 + xtask/src/vendor_attributes.rs | 196 +++++++ 120 files changed, 1576 insertions(+), 2679 deletions(-) create mode 100644 xtask/src/add_vendor_attributes.rs create mode 100644 xtask/src/vendor_attributes.rs diff --git a/openapi.yml b/openapi.yml index a331198..2eb7936 100644 --- a/openapi.yml +++ b/openapi.yml @@ -429,8 +429,6 @@ paths: summary: Search for documents in a collection description: Search for documents in a collection that match the search criteria. operationId: searchCollection - x-rust-generic-parameter: " serde::Deserialize<'de> + Serialize>" - x-rust-return-type: "models::SearchResult" parameters: - name: collectionName in: path @@ -697,7 +695,6 @@ paths: summary: Export all documents in a collection description: Export all documents in a collection in JSON lines format. operationId: exportDocuments - x-supports-plain-text: true parameters: - name: collectionName in: path @@ -749,8 +746,6 @@ paths: JSON structure. You can feed the output file from a Typesense export operation directly as import. operationId: importDocuments - x-rust-body-is-raw-text: true - x-supports-plain-text: true parameters: - name: collectionName in: path @@ -1417,7 +1412,6 @@ paths: description: This is especially useful to avoid round-trip network latencies incurred otherwise if each of these requests are sent in separate HTTP requests. You can also use this feature to do a federated search across multiple collections in a single HTTP request. - x-rust-return-type: "serde_json::Value" parameters: - name: multiSearchParameters required: true @@ -2165,7 +2159,6 @@ components: - name - fields type: object - x-rust-builder: true properties: name: type: string @@ -2289,7 +2282,6 @@ components: - name - type type: object - x-rust-builder: true properties: name: type: string @@ -2447,7 +2439,6 @@ components: $ref: "#/components/schemas/CollectionAlias" SearchResult: type: object - x-rust-generic-parameter: "" properties: facet_counts: type: array @@ -2474,13 +2465,11 @@ components: type: array items: $ref: "#/components/schemas/SearchGroupedHit" - x-rust-type: "Option>>" hits: type: array description: The documents that matched the search query items: $ref: "#/components/schemas/SearchResultHit" - x-rust-type: "Option>>" request_params: $ref: "#/components/schemas/SearchRequestParams" conversation: @@ -2531,7 +2520,6 @@ components: required: - group_key - hits - x-rust-generic-parameter: "" properties: found: type: integer @@ -2543,10 +2531,8 @@ components: description: The documents that matched the search query items: $ref: "#/components/schemas/SearchResultHit" - x-rust-type: "Vec>" SearchResultHit: type: object - x-rust-generic-parameter: "" properties: highlights: type: array @@ -2559,7 +2545,6 @@ components: additionalProperties: true document: type: object - x-rust-type: "Option" description: Can be any key-value pair additionalProperties: type: object @@ -2925,7 +2910,6 @@ components: items: $ref: "#/components/schemas/ApiKey" MultiSearchResult: - x-rust-generic-parameter: "" type: object required: - results @@ -2934,11 +2918,9 @@ components: type: array items: $ref: "#/components/schemas/MultiSearchResultItem" - x-rust-type: "Vec>" conversation: $ref: "#/components/schemas/SearchResultConversation" MultiSearchResultItem: - x-rust-generic-parameter: "" allOf: - $ref: "#/components/schemas/SearchResult" - type: object @@ -2952,7 +2934,6 @@ components: description: Error description SearchParameters: type: object - x-rust-builder: true properties: q: description: The query text to search for in the collection. @@ -3364,7 +3345,6 @@ components: description: > Parameters for the multi search API. type: object - x-rust-builder: true properties: q: description: The query text to search for in the collection. @@ -3752,7 +3732,6 @@ components: items: $ref: "#/components/schemas/MultiSearchCollectionParameters" MultiSearchCollectionParameters: - x-rust-builder: true allOf: - $ref: "#/components/schemas/MultiSearchParameters" - type: object diff --git a/preprocessed_openapi.yml b/preprocessed_openapi.yml index 0a034f3..5bbf988 100644 --- a/preprocessed_openapi.yml +++ b/preprocessed_openapi.yml @@ -405,8 +405,6 @@ paths: summary: Search for documents in a collection description: Search for documents in a collection that match the search criteria. operationId: searchCollection - x-rust-generic-parameter: ' serde::Deserialize<''de> + Serialize>' - x-rust-return-type: models::SearchResult parameters: - name: collectionName in: path @@ -845,6 +843,8 @@ paths: application/json: schema: $ref: '#/components/schemas/ApiResponse' + x-rust-generic-parameter: ' serde::Deserialize<''de> + Serialize>' + x-rust-return-type: models::SearchResult /collections/{collectionName}/overrides: get: tags: @@ -1075,7 +1075,6 @@ paths: summary: Export all documents in a collection description: Export all documents in a collection in JSON lines format. operationId: exportDocuments - x-supports-plain-text: true parameters: - name: collectionName in: path @@ -1115,6 +1114,7 @@ paths: application/json: schema: $ref: '#/components/schemas/ApiResponse' + x-supports-plain-text: true /collections/{collectionName}/documents/import: post: tags: @@ -1122,8 +1122,6 @@ paths: summary: Import documents into a collection description: The documents to be imported must be formatted in a newline delimited JSON structure. You can feed the output file from a Typesense export operation directly as import. operationId: importDocuments - x-rust-body-is-raw-text: true - x-supports-plain-text: true parameters: - name: collectionName in: path @@ -1186,6 +1184,8 @@ paths: application/json: schema: $ref: '#/components/schemas/ApiResponse' + x-rust-body-is-raw-text: true + x-supports-plain-text: true /collections/{collectionName}/documents/{documentId}: get: tags: @@ -1760,7 +1760,6 @@ paths: - documents summary: send multiple search requests in a single HTTP request description: This is especially useful to avoid round-trip network latencies incurred otherwise if each of these requests are sent in separate HTTP requests. You can also use this feature to do a federated search across multiple collections in a single HTTP request. - x-rust-return-type: serde_json::Value parameters: - name: q in: query @@ -2152,6 +2151,7 @@ paths: application/json: schema: $ref: '#/components/schemas/ApiResponse' + x-rust-return-type: serde_json::Value /analytics/events: post: tags: @@ -2864,7 +2864,6 @@ components: - name - fields type: object - x-rust-builder: true properties: name: type: string @@ -2925,6 +2924,7 @@ components: type: object description: | Optional details about the collection, e.g., when it was created, who created it etc. + x-rust-builder: true CollectionUpdateSchema: required: - fields @@ -2978,7 +2978,6 @@ components: - name - type type: object - x-rust-builder: true properties: name: type: string @@ -3089,6 +3088,7 @@ components: type: string query_prefix: type: string + x-rust-builder: true VoiceQueryModelCollectionConfig: type: object description: | @@ -3130,7 +3130,6 @@ components: $ref: '#/components/schemas/CollectionAlias' SearchResult: type: object - x-rust-generic-parameter: properties: facet_counts: type: array @@ -3173,6 +3172,7 @@ components: description: Returned only for union query response. items: $ref: '#/components/schemas/SearchRequestParams' + x-rust-generic-parameter: SearchRequestParams: type: object required: @@ -3214,7 +3214,6 @@ components: required: - group_key - hits - x-rust-generic-parameter: properties: found: type: integer @@ -3227,9 +3226,9 @@ components: items: $ref: '#/components/schemas/SearchResultHit' x-rust-type: Vec> + x-rust-generic-parameter: SearchResultHit: type: object - x-rust-generic-parameter: properties: highlights: type: array @@ -3242,10 +3241,10 @@ components: additionalProperties: true document: type: object - x-rust-type: Option description: Can be any key-value pair additionalProperties: type: object + x-rust-type: Option text_match: type: integer format: int64 @@ -3299,6 +3298,7 @@ components: num_employees: 5215 country: USA text_match: 1234556 + x-rust-generic-parameter: SearchHighlight: type: object properties: @@ -3599,7 +3599,6 @@ components: items: $ref: '#/components/schemas/ApiKey' MultiSearchResult: - x-rust-generic-parameter: type: object required: - results @@ -3611,8 +3610,8 @@ components: x-rust-type: Vec> conversation: $ref: '#/components/schemas/SearchResultConversation' - MultiSearchResultItem: x-rust-generic-parameter: + MultiSearchResultItem: allOf: - $ref: '#/components/schemas/SearchResult' - type: object @@ -3624,9 +3623,9 @@ components: error: type: string description: Error description + x-rust-generic-parameter: SearchParameters: type: object - x-rust-builder: true properties: q: description: The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. @@ -3898,11 +3897,11 @@ components: description: | The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. type: string + x-rust-builder: true MultiSearchParameters: description: | Parameters for the multi search API. type: object - x-rust-builder: true properties: q: description: The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. @@ -4148,6 +4147,7 @@ components: description: | The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. type: string + x-rust-builder: true MultiSearchSearchesParameter: type: object required: @@ -4162,7 +4162,6 @@ components: items: $ref: '#/components/schemas/MultiSearchCollectionParameters' MultiSearchCollectionParameters: - x-rust-builder: true allOf: - $ref: '#/components/schemas/MultiSearchParameters' - type: object @@ -4179,6 +4178,7 @@ components: description: | When true, computes both text match and vector distance scores for all matches in hybrid search. Documents found only through keyword search will get a vector distance score, and documents found only through vector search will get a text match score. default: false + x-rust-builder: true FacetCounts: type: object properties: diff --git a/typesense_codegen/src/apis/analytics_api.rs b/typesense_codegen/src/apis/analytics_api.rs index 97910c7..5dd7ee3 100644 --- a/typesense_codegen/src/apis/analytics_api.rs +++ b/typesense_codegen/src/apis/analytics_api.rs @@ -4,34 +4,35 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ -use super::{ContentType, Error, configuration}; -use crate::{apis::ResponseContent, models}; + use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`create_analytics_event`] #[derive(Clone, Debug)] pub struct CreateAnalyticsEventParams { /// The analytics event to be created - pub analytics_event: models::AnalyticsEvent, + pub analytics_event: models::AnalyticsEvent } /// struct for passing parameters to the method [`create_analytics_rule`] #[derive(Clone, Debug)] pub struct CreateAnalyticsRuleParams { /// The analytics rule(s) to be created - pub create_analytics_rule_request: models::CreateAnalyticsRuleRequest, + pub create_analytics_rule_request: models::CreateAnalyticsRuleRequest } /// struct for passing parameters to the method [`delete_analytics_rule`] #[derive(Clone, Debug)] pub struct DeleteAnalyticsRuleParams { /// The name of the analytics rule to delete - pub rule_name: String, + pub rule_name: String } /// struct for passing parameters to the method [`get_analytics_events`] @@ -41,21 +42,21 @@ pub struct GetAnalyticsEventsParams { /// Analytics rule name pub name: String, /// Number of events to return (max 1000) - pub n: i32, + pub n: i32 } /// struct for passing parameters to the method [`retrieve_analytics_rule`] #[derive(Clone, Debug)] pub struct RetrieveAnalyticsRuleParams { /// The name of the analytics rule to retrieve - pub rule_name: String, + pub rule_name: String } /// struct for passing parameters to the method [`retrieve_analytics_rules`] #[derive(Clone, Debug)] pub struct RetrieveAnalyticsRulesParams { /// Filter rules by rule_tag - pub rule_tag: Option, + pub rule_tag: Option } /// struct for passing parameters to the method [`upsert_analytics_rule`] @@ -64,9 +65,10 @@ pub struct UpsertAnalyticsRuleParams { /// The name of the analytics rule to upsert pub rule_name: String, /// The Analytics rule to be upserted - pub analytics_rule_update: models::AnalyticsRuleUpdate, + pub analytics_rule_update: models::AnalyticsRuleUpdate } + /// struct for typed errors of method [`create_analytics_event`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -136,15 +138,12 @@ pub enum UpsertAnalyticsRuleError { UnknownValue(serde_json::Value), } + /// Submit a single analytics event. The event must correspond to an existing analytics rule by name. -pub async fn create_analytics_event( - configuration: &configuration::Configuration, - params: CreateAnalyticsEventParams, -) -> Result> { +pub async fn create_analytics_event(configuration: &configuration::Configuration, params: CreateAnalyticsEventParams) -> Result> { + let uri_str = format!("{}/analytics/events", configuration.base_path); - let mut req_builder = configuration - .client - .request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -174,37 +173,21 @@ pub async fn create_analytics_event( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Create one or more analytics rules. You can send a single rule object or an array of rule objects. -pub async fn create_analytics_rule( - configuration: &configuration::Configuration, - params: CreateAnalyticsRuleParams, -) -> Result> { +pub async fn create_analytics_rule(configuration: &configuration::Configuration, params: CreateAnalyticsRuleParams) -> Result> { + let uri_str = format!("{}/analytics/rules", configuration.base_path); - let mut req_builder = configuration - .client - .request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -234,41 +217,21 @@ pub async fn create_analytics_rule( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::CreateAnalyticsRule200Response`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::CreateAnalyticsRule200Response`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CreateAnalyticsRule200Response`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CreateAnalyticsRule200Response`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Permanently deletes an analytics rule, given it's name -pub async fn delete_analytics_rule( - configuration: &configuration::Configuration, - params: DeleteAnalyticsRuleParams, -) -> Result> { - let uri_str = format!( - "{}/analytics/rules/{ruleName}", - configuration.base_path, - ruleName = crate::apis::urlencode(params.rule_name) - ); - let mut req_builder = configuration - .client - .request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_analytics_rule(configuration: &configuration::Configuration, params: DeleteAnalyticsRuleParams) -> Result> { + + let uri_str = format!("{}/analytics/rules/{ruleName}", configuration.base_path, ruleName=crate::apis::urlencode(params.rule_name)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -297,36 +260,21 @@ pub async fn delete_analytics_rule( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::AnalyticsRule`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsRule`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsRule`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsRule`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Triggers a flush of analytics data to persistent storage. -pub async fn flush_analytics( - configuration: &configuration::Configuration, -) -> Result> { +pub async fn flush_analytics(configuration: &configuration::Configuration) -> Result> { + let uri_str = format!("{}/analytics/flush", configuration.base_path); - let mut req_builder = configuration - .client - .request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -355,33 +303,19 @@ pub async fn flush_analytics( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Retrieve the most recent events for a user and rule. -pub async fn get_analytics_events( - configuration: &configuration::Configuration, - params: GetAnalyticsEventsParams, -) -> Result> { +pub async fn get_analytics_events(configuration: &configuration::Configuration, params: GetAnalyticsEventsParams) -> Result> { + let uri_str = format!("{}/analytics/events", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -415,32 +349,19 @@ pub async fn get_analytics_events( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::AnalyticsEventsResponse`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsEventsResponse`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsEventsResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsEventsResponse`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Returns sizes of internal analytics buffers and queues. -pub async fn get_analytics_status( - configuration: &configuration::Configuration, -) -> Result> { +pub async fn get_analytics_status(configuration: &configuration::Configuration) -> Result> { + let uri_str = format!("{}/analytics/status", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -471,38 +392,20 @@ pub async fn get_analytics_status( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::AnalyticsStatus`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsStatus`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsStatus`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsStatus`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Retrieve the details of an analytics rule, given it's name -pub async fn retrieve_analytics_rule( - configuration: &configuration::Configuration, - params: RetrieveAnalyticsRuleParams, -) -> Result> { - let uri_str = format!( - "{}/analytics/rules/{ruleName}", - configuration.base_path, - ruleName = crate::apis::urlencode(params.rule_name) - ); +pub async fn retrieve_analytics_rule(configuration: &configuration::Configuration, params: RetrieveAnalyticsRuleParams) -> Result> { + + let uri_str = format!("{}/analytics/rules/{ruleName}", configuration.base_path, ruleName=crate::apis::urlencode(params.rule_name)); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -532,33 +435,19 @@ pub async fn retrieve_analytics_rule( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::AnalyticsRule`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsRule`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsRule`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsRule`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Retrieve all analytics rules. Use the optional rule_tag filter to narrow down results. -pub async fn retrieve_analytics_rules( - configuration: &configuration::Configuration, - params: RetrieveAnalyticsRulesParams, -) -> Result, Error> { +pub async fn retrieve_analytics_rules(configuration: &configuration::Configuration, params: RetrieveAnalyticsRulesParams) -> Result, Error> { + let uri_str = format!("{}/analytics/rules", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -592,38 +481,20 @@ pub async fn retrieve_analytics_rules( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `Vec`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `Vec`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Upserts an analytics rule with the given name. -pub async fn upsert_analytics_rule( - configuration: &configuration::Configuration, - params: UpsertAnalyticsRuleParams, -) -> Result> { - let uri_str = format!( - "{}/analytics/rules/{ruleName}", - configuration.base_path, - ruleName = crate::apis::urlencode(params.rule_name) - ); +pub async fn upsert_analytics_rule(configuration: &configuration::Configuration, params: UpsertAnalyticsRuleParams) -> Result> { + + let uri_str = format!("{}/analytics/rules/{ruleName}", configuration.base_path, ruleName=crate::apis::urlencode(params.rule_name)); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -654,24 +525,13 @@ pub async fn upsert_analytics_rule( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::AnalyticsRule`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsRule`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsRule`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsRule`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } + diff --git a/typesense_codegen/src/apis/collections_api.rs b/typesense_codegen/src/apis/collections_api.rs index d2356ce..b3151e9 100644 --- a/typesense_codegen/src/apis/collections_api.rs +++ b/typesense_codegen/src/apis/collections_api.rs @@ -4,48 +4,49 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ -use super::{ContentType, Error, configuration}; -use crate::{apis::ResponseContent, models}; + use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`create_collection`] #[derive(Clone, Debug)] pub struct CreateCollectionParams { /// The collection object to be created - pub collection_schema: models::CollectionSchema, + pub collection_schema: models::CollectionSchema } /// struct for passing parameters to the method [`delete_alias`] #[derive(Clone, Debug)] pub struct DeleteAliasParams { /// The name of the alias to delete - pub alias_name: String, + pub alias_name: String } /// struct for passing parameters to the method [`delete_collection`] #[derive(Clone, Debug)] pub struct DeleteCollectionParams { /// The name of the collection to delete - pub collection_name: String, + pub collection_name: String } /// struct for passing parameters to the method [`get_alias`] #[derive(Clone, Debug)] pub struct GetAliasParams { /// The name of the alias to retrieve - pub alias_name: String, + pub alias_name: String } /// struct for passing parameters to the method [`get_collection`] #[derive(Clone, Debug)] pub struct GetCollectionParams { /// The name of the collection to retrieve - pub collection_name: String, + pub collection_name: String } /// struct for passing parameters to the method [`get_collections`] @@ -53,7 +54,7 @@ pub struct GetCollectionParams { pub struct GetCollectionsParams { pub exclude_fields: Option, pub limit: Option, - pub offset: Option, + pub offset: Option } /// struct for passing parameters to the method [`update_collection`] @@ -62,7 +63,7 @@ pub struct UpdateCollectionParams { /// The name of the collection to update pub collection_name: String, /// The document object with fields to be updated - pub collection_update_schema: models::CollectionUpdateSchema, + pub collection_update_schema: models::CollectionUpdateSchema } /// struct for passing parameters to the method [`upsert_alias`] @@ -71,9 +72,10 @@ pub struct UpsertAliasParams { /// The name of the alias to create/update pub alias_name: String, /// Collection alias to be created/updated - pub collection_alias_schema: Option, + pub collection_alias_schema: Option } + /// struct for typed errors of method [`create_collection`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -147,15 +149,12 @@ pub enum UpsertAliasError { UnknownValue(serde_json::Value), } + /// When a collection is created, we give it a name and describe the fields that will be indexed from the documents added to the collection. -pub async fn create_collection( - configuration: &configuration::Configuration, - params: CreateCollectionParams, -) -> Result> { +pub async fn create_collection(configuration: &configuration::Configuration, params: CreateCollectionParams) -> Result> { + let uri_str = format!("{}/collections", configuration.base_path); - let mut req_builder = configuration - .client - .request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -185,40 +184,20 @@ pub async fn create_collection( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::CollectionResponse`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionResponse`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionResponse`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } -pub async fn delete_alias( - configuration: &configuration::Configuration, - params: DeleteAliasParams, -) -> Result> { - let uri_str = format!( - "{}/aliases/{aliasName}", - configuration.base_path, - aliasName = crate::apis::urlencode(params.alias_name) - ); - let mut req_builder = configuration - .client - .request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_alias(configuration: &configuration::Configuration, params: DeleteAliasParams) -> Result> { + + let uri_str = format!("{}/aliases/{aliasName}", configuration.base_path, aliasName=crate::apis::urlencode(params.alias_name)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -247,41 +226,21 @@ pub async fn delete_alias( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::CollectionAlias`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAlias`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionAlias`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAlias`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Permanently drops a collection. This action cannot be undone. For large collections, this might have an impact on read latencies. -pub async fn delete_collection( - configuration: &configuration::Configuration, - params: DeleteCollectionParams, -) -> Result> { - let uri_str = format!( - "{}/collections/{collectionName}", - configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name) - ); - let mut req_builder = configuration - .client - .request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_collection(configuration: &configuration::Configuration, params: DeleteCollectionParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -310,38 +269,20 @@ pub async fn delete_collection( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::CollectionResponse`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionResponse`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionResponse`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Find out which collection an alias points to by fetching it -pub async fn get_alias( - configuration: &configuration::Configuration, - params: GetAliasParams, -) -> Result> { - let uri_str = format!( - "{}/aliases/{aliasName}", - configuration.base_path, - aliasName = crate::apis::urlencode(params.alias_name) - ); +pub async fn get_alias(configuration: &configuration::Configuration, params: GetAliasParams) -> Result> { + + let uri_str = format!("{}/aliases/{aliasName}", configuration.base_path, aliasName=crate::apis::urlencode(params.alias_name)); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -371,32 +312,19 @@ pub async fn get_alias( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::CollectionAlias`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAlias`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionAlias`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAlias`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// List all aliases and the corresponding collections that they map to. -pub async fn get_aliases( - configuration: &configuration::Configuration, -) -> Result> { +pub async fn get_aliases(configuration: &configuration::Configuration) -> Result> { + let uri_str = format!("{}/aliases", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -427,38 +355,20 @@ pub async fn get_aliases( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::CollectionAliasesResponse`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAliasesResponse`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionAliasesResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAliasesResponse`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Retrieve the details of a collection, given its name. -pub async fn get_collection( - configuration: &configuration::Configuration, - params: GetCollectionParams, -) -> Result> { - let uri_str = format!( - "{}/collections/{collectionName}", - configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name) - ); +pub async fn get_collection(configuration: &configuration::Configuration, params: GetCollectionParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -488,33 +398,19 @@ pub async fn get_collection( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::CollectionResponse`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionResponse`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionResponse`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Returns a summary of all your collections. The collections are returned sorted by creation date, with the most recent collections appearing first. -pub async fn get_collections( - configuration: &configuration::Configuration, - params: GetCollectionsParams, -) -> Result, Error> { +pub async fn get_collections(configuration: &configuration::Configuration, params: GetCollectionsParams) -> Result, Error> { + let uri_str = format!("{}/collections", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -554,41 +450,21 @@ pub async fn get_collections( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `Vec`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `Vec`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Update a collection's schema to modify the fields and their types. -pub async fn update_collection( - configuration: &configuration::Configuration, - params: UpdateCollectionParams, -) -> Result> { - let uri_str = format!( - "{}/collections/{collectionName}", - configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name) - ); - let mut req_builder = configuration - .client - .request(reqwest::Method::PATCH, &uri_str); +pub async fn update_collection(configuration: &configuration::Configuration, params: UpdateCollectionParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); + let mut req_builder = configuration.client.request(reqwest::Method::PATCH, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -618,38 +494,20 @@ pub async fn update_collection( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::CollectionUpdateSchema`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionUpdateSchema`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionUpdateSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionUpdateSchema`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Create or update a collection alias. An alias is a virtual collection name that points to a real collection. If you're familiar with symbolic links on Linux, it's very similar to that. Aliases are useful when you want to reindex your data in the background on a new collection and switch your application to it without any changes to your code. -pub async fn upsert_alias( - configuration: &configuration::Configuration, - params: UpsertAliasParams, -) -> Result> { - let uri_str = format!( - "{}/aliases/{aliasName}", - configuration.base_path, - aliasName = crate::apis::urlencode(params.alias_name) - ); +pub async fn upsert_alias(configuration: &configuration::Configuration, params: UpsertAliasParams) -> Result> { + + let uri_str = format!("{}/aliases/{aliasName}", configuration.base_path, aliasName=crate::apis::urlencode(params.alias_name)); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -680,24 +538,13 @@ pub async fn upsert_alias( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::CollectionAlias`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAlias`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionAlias`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAlias`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } + diff --git a/typesense_codegen/src/apis/conversations_api.rs b/typesense_codegen/src/apis/conversations_api.rs index 4596344..4e68ba7 100644 --- a/typesense_codegen/src/apis/conversations_api.rs +++ b/typesense_codegen/src/apis/conversations_api.rs @@ -4,33 +4,34 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ -use super::{ContentType, Error, configuration}; -use crate::{apis::ResponseContent, models}; + use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`create_conversation_model`] #[derive(Clone, Debug)] pub struct CreateConversationModelParams { - pub conversation_model_create_schema: models::ConversationModelCreateSchema, + pub conversation_model_create_schema: models::ConversationModelCreateSchema } /// struct for passing parameters to the method [`delete_conversation_model`] #[derive(Clone, Debug)] pub struct DeleteConversationModelParams { /// The id of the conversation model to delete - pub model_id: String, + pub model_id: String } /// struct for passing parameters to the method [`retrieve_conversation_model`] #[derive(Clone, Debug)] pub struct RetrieveConversationModelParams { /// The id of the conversation model to retrieve - pub model_id: String, + pub model_id: String } /// struct for passing parameters to the method [`update_conversation_model`] @@ -38,9 +39,10 @@ pub struct RetrieveConversationModelParams { pub struct UpdateConversationModelParams { /// The id of the conversation model to update pub model_id: String, - pub conversation_model_update_schema: models::ConversationModelUpdateSchema, + pub conversation_model_update_schema: models::ConversationModelUpdateSchema } + /// struct for typed errors of method [`create_conversation_model`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -77,15 +79,12 @@ pub enum UpdateConversationModelError { UnknownValue(serde_json::Value), } + /// Create a Conversation Model -pub async fn create_conversation_model( - configuration: &configuration::Configuration, - params: CreateConversationModelParams, -) -> Result> { +pub async fn create_conversation_model(configuration: &configuration::Configuration, params: CreateConversationModelParams) -> Result> { + let uri_str = format!("{}/conversations/models", configuration.base_path); - let mut req_builder = configuration - .client - .request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -115,41 +114,21 @@ pub async fn create_conversation_model( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Delete a conversation model -pub async fn delete_conversation_model( - configuration: &configuration::Configuration, - params: DeleteConversationModelParams, -) -> Result> { - let uri_str = format!( - "{}/conversations/models/{modelId}", - configuration.base_path, - modelId = crate::apis::urlencode(params.model_id) - ); - let mut req_builder = configuration - .client - .request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_conversation_model(configuration: &configuration::Configuration, params: DeleteConversationModelParams) -> Result> { + + let uri_str = format!("{}/conversations/models/{modelId}", configuration.base_path, modelId=crate::apis::urlencode(params.model_id)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -178,32 +157,19 @@ pub async fn delete_conversation_model( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Retrieve all conversation models -pub async fn retrieve_all_conversation_models( - configuration: &configuration::Configuration, -) -> Result, Error> { +pub async fn retrieve_all_conversation_models(configuration: &configuration::Configuration) -> Result, Error> { + let uri_str = format!("{}/conversations/models", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -234,39 +200,20 @@ pub async fn retrieve_all_conversation_models( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `Vec`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `Vec`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec`")))), } } else { let content = resp.text().await?; - let entity: Option = - serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Retrieve a conversation model -pub async fn retrieve_conversation_model( - configuration: &configuration::Configuration, - params: RetrieveConversationModelParams, -) -> Result> { - let uri_str = format!( - "{}/conversations/models/{modelId}", - configuration.base_path, - modelId = crate::apis::urlencode(params.model_id) - ); +pub async fn retrieve_conversation_model(configuration: &configuration::Configuration, params: RetrieveConversationModelParams) -> Result> { + + let uri_str = format!("{}/conversations/models/{modelId}", configuration.base_path, modelId=crate::apis::urlencode(params.model_id)); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -296,38 +243,20 @@ pub async fn retrieve_conversation_model( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Update a conversation model -pub async fn update_conversation_model( - configuration: &configuration::Configuration, - params: UpdateConversationModelParams, -) -> Result> { - let uri_str = format!( - "{}/conversations/models/{modelId}", - configuration.base_path, - modelId = crate::apis::urlencode(params.model_id) - ); +pub async fn update_conversation_model(configuration: &configuration::Configuration, params: UpdateConversationModelParams) -> Result> { + + let uri_str = format!("{}/conversations/models/{modelId}", configuration.base_path, modelId=crate::apis::urlencode(params.model_id)); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -358,24 +287,13 @@ pub async fn update_conversation_model( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } + diff --git a/typesense_codegen/src/apis/curation_api.rs b/typesense_codegen/src/apis/curation_api.rs index 42a9d2c..4600ec6 100644 --- a/typesense_codegen/src/apis/curation_api.rs +++ b/typesense_codegen/src/apis/curation_api.rs @@ -4,14 +4,15 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ -use super::{ContentType, Error, configuration}; -use crate::{apis::ResponseContent, models}; + use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`delete_search_override`] #[derive(Clone, Debug)] @@ -19,14 +20,14 @@ pub struct DeleteSearchOverrideParams { /// The name of the collection pub collection_name: String, /// The ID of the search override to delete - pub override_id: String, + pub override_id: String } /// struct for passing parameters to the method [`get_search_overrides`] #[derive(Clone, Debug)] pub struct GetSearchOverridesParams { /// The name of the collection - pub collection_name: String, + pub collection_name: String } /// struct for passing parameters to the method [`upsert_search_override`] @@ -37,9 +38,10 @@ pub struct UpsertSearchOverrideParams { /// The ID of the search override to create/update pub override_id: String, /// The search override object to be created/updated - pub search_override_schema: models::SearchOverrideSchema, + pub search_override_schema: models::SearchOverrideSchema } + /// struct for typed errors of method [`delete_search_override`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -63,19 +65,11 @@ pub enum UpsertSearchOverrideError { UnknownValue(serde_json::Value), } -pub async fn delete_search_override( - configuration: &configuration::Configuration, - params: DeleteSearchOverrideParams, -) -> Result> { - let uri_str = format!( - "{}/collections/{collectionName}/overrides/{overrideId}", - configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name), - overrideId = crate::apis::urlencode(params.override_id) - ); - let mut req_builder = configuration - .client - .request(reqwest::Method::DELETE, &uri_str); + +pub async fn delete_search_override(configuration: &configuration::Configuration, params: DeleteSearchOverrideParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), overrideId=crate::apis::urlencode(params.override_id)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -104,37 +98,19 @@ pub async fn delete_search_override( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } -pub async fn get_search_overrides( - configuration: &configuration::Configuration, - params: GetSearchOverridesParams, -) -> Result> { - let uri_str = format!( - "{}/collections/{collectionName}/overrides", - configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name) - ); +pub async fn get_search_overrides(configuration: &configuration::Configuration, params: GetSearchOverridesParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}/overrides", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -164,39 +140,20 @@ pub async fn get_search_overrides( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::SearchOverridesResponse`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverridesResponse`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverridesResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverridesResponse`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Create or update an override to promote certain documents over others. Using overrides, you can include or exclude specific documents for a given query. -pub async fn upsert_search_override( - configuration: &configuration::Configuration, - params: UpsertSearchOverrideParams, -) -> Result> { - let uri_str = format!( - "{}/collections/{collectionName}/overrides/{overrideId}", - configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name), - overrideId = crate::apis::urlencode(params.override_id) - ); +pub async fn upsert_search_override(configuration: &configuration::Configuration, params: UpsertSearchOverrideParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), overrideId=crate::apis::urlencode(params.override_id)); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -227,24 +184,13 @@ pub async fn upsert_search_override( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::SearchOverride`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverride`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } + diff --git a/typesense_codegen/src/apis/debug_api.rs b/typesense_codegen/src/apis/debug_api.rs index 86fc9ea..7fb161c 100644 --- a/typesense_codegen/src/apis/debug_api.rs +++ b/typesense_codegen/src/apis/debug_api.rs @@ -4,14 +4,16 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ -use super::{ContentType, Error, configuration}; -use crate::{apis::ResponseContent, models}; + use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + /// struct for typed errors of method [`debug`] #[derive(Debug, Clone, Serialize, Deserialize)] @@ -20,10 +22,10 @@ pub enum DebugError { UnknownValue(serde_json::Value), } + /// Print debugging information -pub async fn debug( - configuration: &configuration::Configuration, -) -> Result> { +pub async fn debug(configuration: &configuration::Configuration) -> Result> { + let uri_str = format!("{}/debug", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -54,24 +56,13 @@ pub async fn debug( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::Debug200Response`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::Debug200Response`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::Debug200Response`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::Debug200Response`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } + diff --git a/typesense_codegen/src/apis/documents_api.rs b/typesense_codegen/src/apis/documents_api.rs index 744a858..5693578 100644 --- a/typesense_codegen/src/apis/documents_api.rs +++ b/typesense_codegen/src/apis/documents_api.rs @@ -4,14 +4,15 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ -use super::{ContentType, Error, configuration}; -use crate::{apis::ResponseContent, models}; + use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`delete_document`] #[derive(Clone, Debug)] @@ -19,7 +20,7 @@ pub struct DeleteDocumentParams { /// The name of the collection to search for the document under pub collection_name: String, /// The Document ID - pub document_id: String, + pub document_id: String } /// struct for passing parameters to the method [`delete_documents`] @@ -30,7 +31,7 @@ pub struct DeleteDocumentsParams { pub filter_by: Option, pub batch_size: Option, pub ignore_not_found: Option, - pub truncate: Option, + pub truncate: Option } /// struct for passing parameters to the method [`delete_search_override`] @@ -39,7 +40,7 @@ pub struct DeleteSearchOverrideParams { /// The name of the collection pub collection_name: String, /// The ID of the search override to delete - pub override_id: String, + pub override_id: String } /// struct for passing parameters to the method [`export_documents`] @@ -49,7 +50,7 @@ pub struct ExportDocumentsParams { pub collection_name: String, pub filter_by: Option, pub include_fields: Option, - pub exclude_fields: Option, + pub exclude_fields: Option } /// struct for passing parameters to the method [`get_document`] @@ -58,7 +59,7 @@ pub struct GetDocumentParams { /// The name of the collection to search for the document under pub collection_name: String, /// The Document ID - pub document_id: String, + pub document_id: String } /// struct for passing parameters to the method [`get_search_override`] @@ -67,14 +68,14 @@ pub struct GetSearchOverrideParams { /// The name of the collection pub collection_name: String, /// The id of the search override - pub override_id: String, + pub override_id: String } /// struct for passing parameters to the method [`get_search_overrides`] #[derive(Clone, Debug)] pub struct GetSearchOverridesParams { /// The name of the collection - pub collection_name: String, + pub collection_name: String } /// struct for passing parameters to the method [`import_documents`] @@ -89,7 +90,7 @@ pub struct ImportDocumentsParams { pub remote_embedding_batch_size: Option, pub return_doc: Option, pub action: Option, - pub dirty_values: Option, + pub dirty_values: Option } /// struct for passing parameters to the method [`index_document`] @@ -102,7 +103,7 @@ pub struct IndexDocumentParams { /// Additional action to perform pub action: Option, /// Dealing with Dirty Data - pub dirty_values: Option, + pub dirty_values: Option } /// struct for passing parameters to the method [`multi_search`] @@ -172,7 +173,7 @@ pub struct MultiSearchParams { pub conversation: Option, pub conversation_model_id: Option, pub conversation_id: Option, - pub multi_search_searches_parameter: Option, + pub multi_search_searches_parameter: Option } /// struct for passing parameters to the method [`search_collection`] @@ -250,7 +251,7 @@ pub struct SearchCollectionParams { pub voice_query: Option, pub conversation: Option, pub conversation_model_id: Option, - pub conversation_id: Option, + pub conversation_id: Option } /// struct for passing parameters to the method [`update_document`] @@ -263,7 +264,7 @@ pub struct UpdateDocumentParams { /// The document object with fields to be updated pub body: serde_json::Value, /// Dealing with Dirty Data - pub dirty_values: Option, + pub dirty_values: Option } /// struct for passing parameters to the method [`update_documents`] @@ -273,7 +274,7 @@ pub struct UpdateDocumentsParams { pub collection_name: String, /// The document fields to be updated pub body: serde_json::Value, - pub filter_by: Option, + pub filter_by: Option } /// struct for passing parameters to the method [`upsert_search_override`] @@ -284,9 +285,10 @@ pub struct UpsertSearchOverrideParams { /// The ID of the search override to create/update pub override_id: String, /// The search override object to be created/updated - pub search_override_schema: models::SearchOverrideSchema, + pub search_override_schema: models::SearchOverrideSchema } + /// struct for typed errors of method [`delete_document`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -400,20 +402,12 @@ pub enum UpsertSearchOverrideError { UnknownValue(serde_json::Value), } + /// Delete an individual document from a collection by using its ID. -pub async fn delete_document( - configuration: &configuration::Configuration, - params: DeleteDocumentParams, -) -> Result> { - let uri_str = format!( - "{}/collections/{collectionName}/documents/{documentId}", - configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name), - documentId = crate::apis::urlencode(params.document_id) - ); - let mut req_builder = configuration - .client - .request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_document(configuration: &configuration::Configuration, params: DeleteDocumentParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}/documents/{documentId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), documentId=crate::apis::urlencode(params.document_id)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -442,41 +436,21 @@ pub async fn delete_document( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `serde_json::Value`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `serde_json::Value`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Delete a bunch of documents that match a specific filter condition. Use the `batch_size` parameter to control the number of documents that should deleted at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. -pub async fn delete_documents( - configuration: &configuration::Configuration, - params: DeleteDocumentsParams, -) -> Result> { - let uri_str = format!( - "{}/collections/{collectionName}/documents", - configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name) - ); - let mut req_builder = configuration - .client - .request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_documents(configuration: &configuration::Configuration, params: DeleteDocumentsParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}/documents", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); if let Some(ref param_value) = params.filter_by { req_builder = req_builder.query(&[("filter_by", ¶m_value.to_string())]); @@ -517,41 +491,20 @@ pub async fn delete_documents( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::DeleteDocuments200Response`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::DeleteDocuments200Response`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::DeleteDocuments200Response`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::DeleteDocuments200Response`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } -pub async fn delete_search_override( - configuration: &configuration::Configuration, - params: DeleteSearchOverrideParams, -) -> Result> { - let uri_str = format!( - "{}/collections/{collectionName}/overrides/{overrideId}", - configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name), - overrideId = crate::apis::urlencode(params.override_id) - ); - let mut req_builder = configuration - .client - .request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_search_override(configuration: &configuration::Configuration, params: DeleteSearchOverrideParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), overrideId=crate::apis::urlencode(params.override_id)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -580,38 +533,20 @@ pub async fn delete_search_override( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Export all documents in a collection in JSON lines format. -pub async fn export_documents( - configuration: &configuration::Configuration, - params: ExportDocumentsParams, -) -> Result> { - let uri_str = format!( - "{}/collections/{collectionName}/documents/export", - configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name) - ); +pub async fn export_documents(configuration: &configuration::Configuration, params: ExportDocumentsParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}/documents/export", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref param_value) = params.filter_by { @@ -650,34 +585,19 @@ pub async fn export_documents( let content = resp.text().await?; match content_type { ContentType::Json | ContentType::Text => return Ok(content), - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `String`" - )))); - } + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `String`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Fetch an individual document from a collection by using its ID. -pub async fn get_document( - configuration: &configuration::Configuration, - params: GetDocumentParams, -) -> Result> { - let uri_str = format!( - "{}/collections/{collectionName}/documents/{documentId}", - configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name), - documentId = crate::apis::urlencode(params.document_id) - ); +pub async fn get_document(configuration: &configuration::Configuration, params: GetDocumentParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}/documents/{documentId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), documentId=crate::apis::urlencode(params.document_id)); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -707,39 +627,20 @@ pub async fn get_document( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `serde_json::Value`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `serde_json::Value`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Retrieve the details of a search override, given its id. -pub async fn get_search_override( - configuration: &configuration::Configuration, - params: GetSearchOverrideParams, -) -> Result> { - let uri_str = format!( - "{}/collections/{collectionName}/overrides/{overrideId}", - configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name), - overrideId = crate::apis::urlencode(params.override_id) - ); +pub async fn get_search_override(configuration: &configuration::Configuration, params: GetSearchOverrideParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), overrideId=crate::apis::urlencode(params.override_id)); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -769,37 +670,19 @@ pub async fn get_search_override( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::SearchOverride`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverride`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } -pub async fn get_search_overrides( - configuration: &configuration::Configuration, - params: GetSearchOverridesParams, -) -> Result> { - let uri_str = format!( - "{}/collections/{collectionName}/overrides", - configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name) - ); +pub async fn get_search_overrides(configuration: &configuration::Configuration, params: GetSearchOverridesParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}/overrides", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -829,41 +712,21 @@ pub async fn get_search_overrides( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::SearchOverridesResponse`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverridesResponse`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverridesResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverridesResponse`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// The documents to be imported must be formatted in a newline delimited JSON structure. You can feed the output file from a Typesense export operation directly as import. -pub async fn import_documents( - configuration: &configuration::Configuration, - params: ImportDocumentsParams, -) -> Result> { - let uri_str = format!( - "{}/collections/{collectionName}/documents/import", - configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name) - ); - let mut req_builder = configuration - .client - .request(reqwest::Method::POST, &uri_str); +pub async fn import_documents(configuration: &configuration::Configuration, params: ImportDocumentsParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}/documents/import", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); if let Some(ref param_value) = params.batch_size { req_builder = req_builder.query(&[("batch_size", ¶m_value.to_string())]); @@ -872,8 +735,7 @@ pub async fn import_documents( req_builder = req_builder.query(&[("return_id", ¶m_value.to_string())]); } if let Some(ref param_value) = params.remote_embedding_batch_size { - req_builder = - req_builder.query(&[("remote_embedding_batch_size", ¶m_value.to_string())]); + req_builder = req_builder.query(&[("remote_embedding_batch_size", ¶m_value.to_string())]); } if let Some(ref param_value) = params.return_doc { req_builder = req_builder.query(&[("return_doc", ¶m_value.to_string())]); @@ -895,9 +757,7 @@ pub async fn import_documents( }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - req_builder = req_builder - .header(reqwest::header::CONTENT_TYPE, "text/plain") - .body(params.body); + req_builder = req_builder.header(reqwest::header::CONTENT_TYPE, "text/plain").body(params.body); let req = req_builder.build()?; let resp = configuration.client.execute(req).await?; @@ -914,36 +774,20 @@ pub async fn import_documents( let content = resp.text().await?; match content_type { ContentType::Json | ContentType::Text => return Ok(content), - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `String`" - )))); - } + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `String`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// A document to be indexed in a given collection must conform to the schema of the collection. -pub async fn index_document( - configuration: &configuration::Configuration, - params: IndexDocumentParams, -) -> Result> { - let uri_str = format!( - "{}/collections/{collectionName}/documents", - configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name) - ); - let mut req_builder = configuration - .client - .request(reqwest::Method::POST, &uri_str); +pub async fn index_document(configuration: &configuration::Configuration, params: IndexDocumentParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}/documents", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); if let Some(ref param_value) = params.action { req_builder = req_builder.query(&[("action", ¶m_value.to_string())]); @@ -979,37 +823,21 @@ pub async fn index_document( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `serde_json::Value`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `serde_json::Value`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// This is especially useful to avoid round-trip network latencies incurred otherwise if each of these requests are sent in separate HTTP requests. You can also use this feature to do a federated search across multiple collections in a single HTTP request. -pub async fn multi_search( - configuration: &configuration::Configuration, - params: MultiSearchParams, -) -> Result> { +pub async fn multi_search(configuration: &configuration::Configuration, params: MultiSearchParams) -> Result> { + let uri_str = format!("{}/multi_search", configuration.base_path); - let mut req_builder = configuration - .client - .request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); if let Some(ref param_value) = params.q { req_builder = req_builder.query(&[("q", ¶m_value.to_string())]); @@ -1084,8 +912,7 @@ pub async fn multi_search( req_builder = req_builder.query(&[("highlight_full_fields", ¶m_value.to_string())]); } if let Some(ref param_value) = params.highlight_affix_num_tokens { - req_builder = - req_builder.query(&[("highlight_affix_num_tokens", ¶m_value.to_string())]); + req_builder = req_builder.query(&[("highlight_affix_num_tokens", ¶m_value.to_string())]); } if let Some(ref param_value) = params.highlight_start_tag { req_builder = req_builder.query(&[("highlight_start_tag", ¶m_value.to_string())]); @@ -1106,10 +933,7 @@ pub async fn multi_search( req_builder = req_builder.query(&[("typo_tokens_threshold", ¶m_value.to_string())]); } if let Some(ref param_value) = params.enable_typos_for_alpha_numerical_tokens { - req_builder = req_builder.query(&[( - "enable_typos_for_alpha_numerical_tokens", - ¶m_value.to_string(), - )]); + req_builder = req_builder.query(&[("enable_typos_for_alpha_numerical_tokens", ¶m_value.to_string())]); } if let Some(ref param_value) = params.filter_curated_hits { req_builder = req_builder.query(&[("filter_curated_hits", ¶m_value.to_string())]); @@ -1154,14 +978,10 @@ pub async fn multi_search( req_builder = req_builder.query(&[("prioritize_token_position", ¶m_value.to_string())]); } if let Some(ref param_value) = params.prioritize_num_matching_fields { - req_builder = - req_builder.query(&[("prioritize_num_matching_fields", ¶m_value.to_string())]); + req_builder = req_builder.query(&[("prioritize_num_matching_fields", ¶m_value.to_string())]); } if let Some(ref param_value) = params.enable_typos_for_numerical_tokens { - req_builder = req_builder.query(&[( - "enable_typos_for_numerical_tokens", - ¶m_value.to_string(), - )]); + req_builder = req_builder.query(&[("enable_typos_for_numerical_tokens", ¶m_value.to_string())]); } if let Some(ref param_value) = params.exhaustive_search { req_builder = req_builder.query(&[("exhaustive_search", ¶m_value.to_string())]); @@ -1185,12 +1005,10 @@ pub async fn multi_search( req_builder = req_builder.query(&[("vector_query", ¶m_value.to_string())]); } if let Some(ref param_value) = params.remote_embedding_timeout_ms { - req_builder = - req_builder.query(&[("remote_embedding_timeout_ms", ¶m_value.to_string())]); + req_builder = req_builder.query(&[("remote_embedding_timeout_ms", ¶m_value.to_string())]); } if let Some(ref param_value) = params.remote_embedding_num_tries { - req_builder = - req_builder.query(&[("remote_embedding_num_tries", ¶m_value.to_string())]); + req_builder = req_builder.query(&[("remote_embedding_num_tries", ¶m_value.to_string())]); } if let Some(ref param_value) = params.facet_strategy { req_builder = req_builder.query(&[("facet_strategy", ¶m_value.to_string())]); @@ -1241,38 +1059,20 @@ pub async fn multi_search( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `serde_json::Value`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `serde_json::Value`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Search for documents in a collection that match the search criteria. -pub async fn search_collection serde::Deserialize<'de> + Serialize>( - configuration: &configuration::Configuration, - params: SearchCollectionParams, -) -> Result, Error> { - let uri_str = format!( - "{}/collections/{collectionName}/documents/search", - configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name) - ); +pub async fn search_collection serde::Deserialize<'de> + Serialize>(configuration: &configuration::Configuration, params: SearchCollectionParams) -> Result, Error> { + + let uri_str = format!("{}/collections/{collectionName}/documents/search", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref param_value) = params.q { @@ -1357,8 +1157,7 @@ pub async fn search_collection serde::Deserialize<'de> + Serialize>( req_builder = req_builder.query(&[("highlight_full_fields", ¶m_value.to_string())]); } if let Some(ref param_value) = params.highlight_affix_num_tokens { - req_builder = - req_builder.query(&[("highlight_affix_num_tokens", ¶m_value.to_string())]); + req_builder = req_builder.query(&[("highlight_affix_num_tokens", ¶m_value.to_string())]); } if let Some(ref param_value) = params.highlight_start_tag { req_builder = req_builder.query(&[("highlight_start_tag", ¶m_value.to_string())]); @@ -1388,10 +1187,7 @@ pub async fn search_collection serde::Deserialize<'de> + Serialize>( req_builder = req_builder.query(&[("typo_tokens_threshold", ¶m_value.to_string())]); } if let Some(ref param_value) = params.enable_typos_for_alpha_numerical_tokens { - req_builder = req_builder.query(&[( - "enable_typos_for_alpha_numerical_tokens", - ¶m_value.to_string(), - )]); + req_builder = req_builder.query(&[("enable_typos_for_alpha_numerical_tokens", ¶m_value.to_string())]); } if let Some(ref param_value) = params.filter_curated_hits { req_builder = req_builder.query(&[("filter_curated_hits", ¶m_value.to_string())]); @@ -1439,14 +1235,10 @@ pub async fn search_collection serde::Deserialize<'de> + Serialize>( req_builder = req_builder.query(&[("prioritize_token_position", ¶m_value.to_string())]); } if let Some(ref param_value) = params.prioritize_num_matching_fields { - req_builder = - req_builder.query(&[("prioritize_num_matching_fields", ¶m_value.to_string())]); + req_builder = req_builder.query(&[("prioritize_num_matching_fields", ¶m_value.to_string())]); } if let Some(ref param_value) = params.enable_typos_for_numerical_tokens { - req_builder = req_builder.query(&[( - "enable_typos_for_numerical_tokens", - ¶m_value.to_string(), - )]); + req_builder = req_builder.query(&[("enable_typos_for_numerical_tokens", ¶m_value.to_string())]); } if let Some(ref param_value) = params.exhaustive_search { req_builder = req_builder.query(&[("exhaustive_search", ¶m_value.to_string())]); @@ -1470,12 +1262,10 @@ pub async fn search_collection serde::Deserialize<'de> + Serialize>( req_builder = req_builder.query(&[("vector_query", ¶m_value.to_string())]); } if let Some(ref param_value) = params.remote_embedding_timeout_ms { - req_builder = - req_builder.query(&[("remote_embedding_timeout_ms", ¶m_value.to_string())]); + req_builder = req_builder.query(&[("remote_embedding_timeout_ms", ¶m_value.to_string())]); } if let Some(ref param_value) = params.remote_embedding_num_tries { - req_builder = - req_builder.query(&[("remote_embedding_num_tries", ¶m_value.to_string())]); + req_builder = req_builder.query(&[("remote_embedding_num_tries", ¶m_value.to_string())]); } if let Some(ref param_value) = params.facet_strategy { req_builder = req_builder.query(&[("facet_strategy", ¶m_value.to_string())]); @@ -1525,42 +1315,21 @@ pub async fn search_collection serde::Deserialize<'de> + Serialize>( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::SearchResult`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::SearchResult`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchResult`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchResult`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Update an individual document from a collection by using its ID. The update can be partial. -pub async fn update_document( - configuration: &configuration::Configuration, - params: UpdateDocumentParams, -) -> Result> { - let uri_str = format!( - "{}/collections/{collectionName}/documents/{documentId}", - configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name), - documentId = crate::apis::urlencode(params.document_id) - ); - let mut req_builder = configuration - .client - .request(reqwest::Method::PATCH, &uri_str); +pub async fn update_document(configuration: &configuration::Configuration, params: UpdateDocumentParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}/documents/{documentId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), documentId=crate::apis::urlencode(params.document_id)); + let mut req_builder = configuration.client.request(reqwest::Method::PATCH, &uri_str); if let Some(ref param_value) = params.dirty_values { req_builder = req_builder.query(&[("dirty_values", ¶m_value.to_string())]); @@ -1593,41 +1362,21 @@ pub async fn update_document( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `serde_json::Value`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `serde_json::Value`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// The filter_by query parameter is used to filter to specify a condition against which the documents are matched. The request body contains the fields that should be updated for any documents that match the filter condition. This endpoint is only available if the Typesense server is version `0.25.0.rc12` or later. -pub async fn update_documents( - configuration: &configuration::Configuration, - params: UpdateDocumentsParams, -) -> Result> { - let uri_str = format!( - "{}/collections/{collectionName}/documents", - configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name) - ); - let mut req_builder = configuration - .client - .request(reqwest::Method::PATCH, &uri_str); +pub async fn update_documents(configuration: &configuration::Configuration, params: UpdateDocumentsParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}/documents", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); + let mut req_builder = configuration.client.request(reqwest::Method::PATCH, &uri_str); if let Some(ref param_value) = params.filter_by { req_builder = req_builder.query(&[("filter_by", ¶m_value.to_string())]); @@ -1660,39 +1409,20 @@ pub async fn update_documents( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::UpdateDocuments200Response`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::UpdateDocuments200Response`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::UpdateDocuments200Response`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::UpdateDocuments200Response`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Create or update an override to promote certain documents over others. Using overrides, you can include or exclude specific documents for a given query. -pub async fn upsert_search_override( - configuration: &configuration::Configuration, - params: UpsertSearchOverrideParams, -) -> Result> { - let uri_str = format!( - "{}/collections/{collectionName}/overrides/{overrideId}", - configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name), - overrideId = crate::apis::urlencode(params.override_id) - ); +pub async fn upsert_search_override(configuration: &configuration::Configuration, params: UpsertSearchOverrideParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), overrideId=crate::apis::urlencode(params.override_id)); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -1723,24 +1453,13 @@ pub async fn upsert_search_override( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::SearchOverride`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverride`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } + diff --git a/typesense_codegen/src/apis/health_api.rs b/typesense_codegen/src/apis/health_api.rs index 1a61750..595b323 100644 --- a/typesense_codegen/src/apis/health_api.rs +++ b/typesense_codegen/src/apis/health_api.rs @@ -4,14 +4,16 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ -use super::{ContentType, Error, configuration}; -use crate::{apis::ResponseContent, models}; + use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + /// struct for typed errors of method [`health`] #[derive(Debug, Clone, Serialize, Deserialize)] @@ -20,10 +22,10 @@ pub enum HealthError { UnknownValue(serde_json::Value), } + /// Checks if Typesense server is ready to accept requests. -pub async fn health( - configuration: &configuration::Configuration, -) -> Result> { +pub async fn health(configuration: &configuration::Configuration) -> Result> { + let uri_str = format!("{}/health", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -54,24 +56,13 @@ pub async fn health( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::HealthStatus`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::HealthStatus`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::HealthStatus`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::HealthStatus`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } + diff --git a/typesense_codegen/src/apis/keys_api.rs b/typesense_codegen/src/apis/keys_api.rs index b419c52..be85909 100644 --- a/typesense_codegen/src/apis/keys_api.rs +++ b/typesense_codegen/src/apis/keys_api.rs @@ -4,36 +4,38 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ -use super::{ContentType, Error, configuration}; -use crate::{apis::ResponseContent, models}; + use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`create_key`] #[derive(Clone, Debug)] pub struct CreateKeyParams { /// The object that describes API key scope - pub api_key_schema: Option, + pub api_key_schema: Option } /// struct for passing parameters to the method [`delete_key`] #[derive(Clone, Debug)] pub struct DeleteKeyParams { /// The ID of the key to delete - pub key_id: i64, + pub key_id: i64 } /// struct for passing parameters to the method [`get_key`] #[derive(Clone, Debug)] pub struct GetKeyParams { /// The ID of the key to retrieve - pub key_id: i64, + pub key_id: i64 } + /// struct for typed errors of method [`create_key`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -67,15 +69,12 @@ pub enum GetKeysError { UnknownValue(serde_json::Value), } + /// Create an API Key with fine-grain access control. You can restrict access on both a per-collection and per-action level. The generated key is returned only during creation. You want to store this key carefully in a secure place. -pub async fn create_key( - configuration: &configuration::Configuration, - params: CreateKeyParams, -) -> Result> { +pub async fn create_key(configuration: &configuration::Configuration, params: CreateKeyParams) -> Result> { + let uri_str = format!("{}/keys", configuration.base_path); - let mut req_builder = configuration - .client - .request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -105,40 +104,20 @@ pub async fn create_key( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::ApiKey`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::ApiKey`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ApiKey`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ApiKey`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } -pub async fn delete_key( - configuration: &configuration::Configuration, - params: DeleteKeyParams, -) -> Result> { - let uri_str = format!( - "{}/keys/{keyId}", - configuration.base_path, - keyId = params.key_id - ); - let mut req_builder = configuration - .client - .request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_key(configuration: &configuration::Configuration, params: DeleteKeyParams) -> Result> { + + let uri_str = format!("{}/keys/{keyId}", configuration.base_path, keyId=params.key_id); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -167,38 +146,20 @@ pub async fn delete_key( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::ApiKeyDeleteResponse`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::ApiKeyDeleteResponse`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ApiKeyDeleteResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ApiKeyDeleteResponse`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Retrieve (metadata about) a key. Only the key prefix is returned when you retrieve a key. Due to security reasons, only the create endpoint returns the full API key. -pub async fn get_key( - configuration: &configuration::Configuration, - params: GetKeyParams, -) -> Result> { - let uri_str = format!( - "{}/keys/{keyId}", - configuration.base_path, - keyId = params.key_id - ); +pub async fn get_key(configuration: &configuration::Configuration, params: GetKeyParams) -> Result> { + + let uri_str = format!("{}/keys/{keyId}", configuration.base_path, keyId=params.key_id); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -228,31 +189,18 @@ pub async fn get_key( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::ApiKey`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::ApiKey`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ApiKey`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ApiKey`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } -pub async fn get_keys( - configuration: &configuration::Configuration, -) -> Result> { +pub async fn get_keys(configuration: &configuration::Configuration) -> Result> { + let uri_str = format!("{}/keys", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -283,24 +231,13 @@ pub async fn get_keys( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::ApiKeysResponse`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::ApiKeysResponse`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ApiKeysResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ApiKeysResponse`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } + diff --git a/typesense_codegen/src/apis/nl_search_models_api.rs b/typesense_codegen/src/apis/nl_search_models_api.rs index b30d551..e88bea3 100644 --- a/typesense_codegen/src/apis/nl_search_models_api.rs +++ b/typesense_codegen/src/apis/nl_search_models_api.rs @@ -4,34 +4,35 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ -use super::{ContentType, Error, configuration}; -use crate::{apis::ResponseContent, models}; + use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`create_nl_search_model`] #[derive(Clone, Debug)] pub struct CreateNlSearchModelParams { /// The NL search model to be created - pub nl_search_model_create_schema: models::NlSearchModelCreateSchema, + pub nl_search_model_create_schema: models::NlSearchModelCreateSchema } /// struct for passing parameters to the method [`delete_nl_search_model`] #[derive(Clone, Debug)] pub struct DeleteNlSearchModelParams { /// The ID of the NL search model to delete - pub model_id: String, + pub model_id: String } /// struct for passing parameters to the method [`retrieve_nl_search_model`] #[derive(Clone, Debug)] pub struct RetrieveNlSearchModelParams { /// The ID of the NL search model to retrieve - pub model_id: String, + pub model_id: String } /// struct for passing parameters to the method [`update_nl_search_model`] @@ -40,9 +41,10 @@ pub struct UpdateNlSearchModelParams { /// The ID of the NL search model to update pub model_id: String, /// The NL search model fields to update - pub body: models::NlSearchModelCreateSchema, + pub body: models::NlSearchModelCreateSchema } + /// struct for typed errors of method [`create_nl_search_model`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -83,15 +85,12 @@ pub enum UpdateNlSearchModelError { UnknownValue(serde_json::Value), } + /// Create a new NL search model. -pub async fn create_nl_search_model( - configuration: &configuration::Configuration, - params: CreateNlSearchModelParams, -) -> Result> { +pub async fn create_nl_search_model(configuration: &configuration::Configuration, params: CreateNlSearchModelParams) -> Result> { + let uri_str = format!("{}/nl_search_models", configuration.base_path); - let mut req_builder = configuration - .client - .request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -121,41 +120,21 @@ pub async fn create_nl_search_model( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::NlSearchModelSchema`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelSchema`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::NlSearchModelSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelSchema`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Delete a specific NL search model by its ID. -pub async fn delete_nl_search_model( - configuration: &configuration::Configuration, - params: DeleteNlSearchModelParams, -) -> Result> { - let uri_str = format!( - "{}/nl_search_models/{modelId}", - configuration.base_path, - modelId = crate::apis::urlencode(params.model_id) - ); - let mut req_builder = configuration - .client - .request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_nl_search_model(configuration: &configuration::Configuration, params: DeleteNlSearchModelParams) -> Result> { + + let uri_str = format!("{}/nl_search_models/{modelId}", configuration.base_path, modelId=crate::apis::urlencode(params.model_id)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -184,32 +163,19 @@ pub async fn delete_nl_search_model( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::NlSearchModelDeleteSchema`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelDeleteSchema`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::NlSearchModelDeleteSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelDeleteSchema`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Retrieve all NL search models. -pub async fn retrieve_all_nl_search_models( - configuration: &configuration::Configuration, -) -> Result, Error> { +pub async fn retrieve_all_nl_search_models(configuration: &configuration::Configuration) -> Result, Error> { + let uri_str = format!("{}/nl_search_models", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -240,38 +206,20 @@ pub async fn retrieve_all_nl_search_models( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `Vec`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `Vec`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Retrieve a specific NL search model by its ID. -pub async fn retrieve_nl_search_model( - configuration: &configuration::Configuration, - params: RetrieveNlSearchModelParams, -) -> Result> { - let uri_str = format!( - "{}/nl_search_models/{modelId}", - configuration.base_path, - modelId = crate::apis::urlencode(params.model_id) - ); +pub async fn retrieve_nl_search_model(configuration: &configuration::Configuration, params: RetrieveNlSearchModelParams) -> Result> { + + let uri_str = format!("{}/nl_search_models/{modelId}", configuration.base_path, modelId=crate::apis::urlencode(params.model_id)); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -301,38 +249,20 @@ pub async fn retrieve_nl_search_model( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::NlSearchModelSchema`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelSchema`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::NlSearchModelSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelSchema`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Update an existing NL search model. -pub async fn update_nl_search_model( - configuration: &configuration::Configuration, - params: UpdateNlSearchModelParams, -) -> Result> { - let uri_str = format!( - "{}/nl_search_models/{modelId}", - configuration.base_path, - modelId = crate::apis::urlencode(params.model_id) - ); +pub async fn update_nl_search_model(configuration: &configuration::Configuration, params: UpdateNlSearchModelParams) -> Result> { + + let uri_str = format!("{}/nl_search_models/{modelId}", configuration.base_path, modelId=crate::apis::urlencode(params.model_id)); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -363,24 +293,13 @@ pub async fn update_nl_search_model( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::NlSearchModelSchema`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelSchema`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::NlSearchModelSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelSchema`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } + diff --git a/typesense_codegen/src/apis/operations_api.rs b/typesense_codegen/src/apis/operations_api.rs index 971cddb..4f88281 100644 --- a/typesense_codegen/src/apis/operations_api.rs +++ b/typesense_codegen/src/apis/operations_api.rs @@ -4,28 +4,30 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ -use super::{ContentType, Error, configuration}; -use crate::{apis::ResponseContent, models}; + use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`take_snapshot`] #[derive(Clone, Debug)] pub struct TakeSnapshotParams { /// The directory on the server where the snapshot should be saved. - pub snapshot_path: String, + pub snapshot_path: String } /// struct for passing parameters to the method [`toggle_slow_request_log`] #[derive(Clone, Debug)] pub struct ToggleSlowRequestLogParams { - pub toggle_slow_request_log_request: Option, + pub toggle_slow_request_log_request: Option } + /// struct for typed errors of method [`clear_cache`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -82,14 +84,12 @@ pub enum VoteError { UnknownValue(serde_json::Value), } + /// Clear the cached responses of search requests that are sent with `use_cache` parameter in the LRU cache. -pub async fn clear_cache( - configuration: &configuration::Configuration, -) -> Result> { +pub async fn clear_cache(configuration: &configuration::Configuration) -> Result> { + let uri_str = format!("{}/operations/cache/clear", configuration.base_path); - let mut req_builder = configuration - .client - .request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -118,36 +118,21 @@ pub async fn clear_cache( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Typesense uses RocksDB to store your documents on the disk. If you do frequent writes or updates, you could benefit from running a compaction of the underlying RocksDB database. This could reduce the size of the database and decrease read latency. While the database will not block during this operation, we recommend running it during off-peak hours. -pub async fn compact_db( - configuration: &configuration::Configuration, -) -> Result> { +pub async fn compact_db(configuration: &configuration::Configuration) -> Result> { + let uri_str = format!("{}/operations/db/compact", configuration.base_path); - let mut req_builder = configuration - .client - .request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -176,32 +161,19 @@ pub async fn compact_db( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Returns the status of any ongoing schema change operations. If no schema changes are in progress, returns an empty response. -pub async fn get_schema_changes( - configuration: &configuration::Configuration, -) -> Result, Error> { +pub async fn get_schema_changes(configuration: &configuration::Configuration) -> Result, Error> { + let uri_str = format!("{}/operations/schema_changes", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -232,32 +204,19 @@ pub async fn get_schema_changes( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `Vec`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `Vec`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Retrieve the stats about API endpoints. -pub async fn retrieve_api_stats( - configuration: &configuration::Configuration, -) -> Result> { +pub async fn retrieve_api_stats(configuration: &configuration::Configuration) -> Result> { + let uri_str = format!("{}/stats.json", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -288,32 +247,19 @@ pub async fn retrieve_api_stats( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::ApiStatsResponse`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::ApiStatsResponse`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ApiStatsResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ApiStatsResponse`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Retrieve the metrics. -pub async fn retrieve_metrics( - configuration: &configuration::Configuration, -) -> Result> { +pub async fn retrieve_metrics(configuration: &configuration::Configuration) -> Result> { + let uri_str = format!("{}/metrics.json", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -344,37 +290,21 @@ pub async fn retrieve_metrics( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `serde_json::Value`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `serde_json::Value`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Creates a point-in-time snapshot of a Typesense node's state and data in the specified directory. You can then backup the snapshot directory that gets created and later restore it as a data directory, as needed. -pub async fn take_snapshot( - configuration: &configuration::Configuration, - params: TakeSnapshotParams, -) -> Result> { +pub async fn take_snapshot(configuration: &configuration::Configuration, params: TakeSnapshotParams) -> Result> { + let uri_str = format!("{}/operations/snapshot", configuration.base_path); - let mut req_builder = configuration - .client - .request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); req_builder = req_builder.query(&[("snapshot_path", ¶ms.snapshot_path.to_string())]); if let Some(ref user_agent) = configuration.user_agent { @@ -404,37 +334,21 @@ pub async fn take_snapshot( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Enable logging of requests that take over a defined threshold of time. Default is `-1` which disables slow request logging. Slow requests are logged to the primary log file, with the prefix SLOW REQUEST. -pub async fn toggle_slow_request_log( - configuration: &configuration::Configuration, - params: ToggleSlowRequestLogParams, -) -> Result> { +pub async fn toggle_slow_request_log(configuration: &configuration::Configuration, params: ToggleSlowRequestLogParams) -> Result> { + let uri_str = format!("{}/config", configuration.base_path); - let mut req_builder = configuration - .client - .request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -464,36 +378,21 @@ pub async fn toggle_slow_request_log( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Triggers a follower node to initiate the raft voting process, which triggers leader re-election. The follower node that you run this operation against will become the new leader, once this command succeeds. -pub async fn vote( - configuration: &configuration::Configuration, -) -> Result> { +pub async fn vote(configuration: &configuration::Configuration) -> Result> { + let uri_str = format!("{}/operations/vote", configuration.base_path); - let mut req_builder = configuration - .client - .request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -522,24 +421,13 @@ pub async fn vote( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } + diff --git a/typesense_codegen/src/apis/override_api.rs b/typesense_codegen/src/apis/override_api.rs index 07b8cb3..d05d16f 100644 --- a/typesense_codegen/src/apis/override_api.rs +++ b/typesense_codegen/src/apis/override_api.rs @@ -4,14 +4,15 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ -use super::{ContentType, Error, configuration}; -use crate::{apis::ResponseContent, models}; + use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`get_search_override`] #[derive(Clone, Debug)] @@ -19,9 +20,10 @@ pub struct GetSearchOverrideParams { /// The name of the collection pub collection_name: String, /// The id of the search override - pub override_id: String, + pub override_id: String } + /// struct for typed errors of method [`get_search_override`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -29,17 +31,11 @@ pub enum GetSearchOverrideError { UnknownValue(serde_json::Value), } + /// Retrieve the details of a search override, given its id. -pub async fn get_search_override( - configuration: &configuration::Configuration, - params: GetSearchOverrideParams, -) -> Result> { - let uri_str = format!( - "{}/collections/{collectionName}/overrides/{overrideId}", - configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name), - overrideId = crate::apis::urlencode(params.override_id) - ); +pub async fn get_search_override(configuration: &configuration::Configuration, params: GetSearchOverrideParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), overrideId=crate::apis::urlencode(params.override_id)); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -69,24 +65,13 @@ pub async fn get_search_override( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::SearchOverride`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverride`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } + diff --git a/typesense_codegen/src/apis/presets_api.rs b/typesense_codegen/src/apis/presets_api.rs index eaf1046..8f16f89 100644 --- a/typesense_codegen/src/apis/presets_api.rs +++ b/typesense_codegen/src/apis/presets_api.rs @@ -4,27 +4,28 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ -use super::{ContentType, Error, configuration}; -use crate::{apis::ResponseContent, models}; + use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`delete_preset`] #[derive(Clone, Debug)] pub struct DeletePresetParams { /// The ID of the preset to delete. - pub preset_id: String, + pub preset_id: String } /// struct for passing parameters to the method [`retrieve_preset`] #[derive(Clone, Debug)] pub struct RetrievePresetParams { /// The ID of the preset to retrieve. - pub preset_id: String, + pub preset_id: String } /// struct for passing parameters to the method [`upsert_preset`] @@ -33,9 +34,10 @@ pub struct UpsertPresetParams { /// The name of the preset set to upsert. pub preset_id: String, /// The stopwords set to upsert. - pub preset_upsert_schema: models::PresetUpsertSchema, + pub preset_upsert_schema: models::PresetUpsertSchema } + /// struct for typed errors of method [`delete_preset`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -67,19 +69,12 @@ pub enum UpsertPresetError { UnknownValue(serde_json::Value), } + /// Permanently deletes a preset, given it's name. -pub async fn delete_preset( - configuration: &configuration::Configuration, - params: DeletePresetParams, -) -> Result> { - let uri_str = format!( - "{}/presets/{presetId}", - configuration.base_path, - presetId = crate::apis::urlencode(params.preset_id) - ); - let mut req_builder = configuration - .client - .request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_preset(configuration: &configuration::Configuration, params: DeletePresetParams) -> Result> { + + let uri_str = format!("{}/presets/{presetId}", configuration.base_path, presetId=crate::apis::urlencode(params.preset_id)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -108,32 +103,19 @@ pub async fn delete_preset( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::PresetDeleteSchema`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::PresetDeleteSchema`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::PresetDeleteSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::PresetDeleteSchema`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Retrieve the details of all presets -pub async fn retrieve_all_presets( - configuration: &configuration::Configuration, -) -> Result> { +pub async fn retrieve_all_presets(configuration: &configuration::Configuration) -> Result> { + let uri_str = format!("{}/presets", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -164,38 +146,20 @@ pub async fn retrieve_all_presets( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::PresetsRetrieveSchema`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::PresetsRetrieveSchema`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::PresetsRetrieveSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::PresetsRetrieveSchema`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Retrieve the details of a preset, given it's name. -pub async fn retrieve_preset( - configuration: &configuration::Configuration, - params: RetrievePresetParams, -) -> Result> { - let uri_str = format!( - "{}/presets/{presetId}", - configuration.base_path, - presetId = crate::apis::urlencode(params.preset_id) - ); +pub async fn retrieve_preset(configuration: &configuration::Configuration, params: RetrievePresetParams) -> Result> { + + let uri_str = format!("{}/presets/{presetId}", configuration.base_path, presetId=crate::apis::urlencode(params.preset_id)); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -225,38 +189,20 @@ pub async fn retrieve_preset( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::PresetSchema`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::PresetSchema`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::PresetSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::PresetSchema`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Create or update an existing preset. -pub async fn upsert_preset( - configuration: &configuration::Configuration, - params: UpsertPresetParams, -) -> Result> { - let uri_str = format!( - "{}/presets/{presetId}", - configuration.base_path, - presetId = crate::apis::urlencode(params.preset_id) - ); +pub async fn upsert_preset(configuration: &configuration::Configuration, params: UpsertPresetParams) -> Result> { + + let uri_str = format!("{}/presets/{presetId}", configuration.base_path, presetId=crate::apis::urlencode(params.preset_id)); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -287,24 +233,13 @@ pub async fn upsert_preset( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::PresetSchema`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::PresetSchema`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::PresetSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::PresetSchema`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } + diff --git a/typesense_codegen/src/apis/stemming_api.rs b/typesense_codegen/src/apis/stemming_api.rs index b477615..3f2bebb 100644 --- a/typesense_codegen/src/apis/stemming_api.rs +++ b/typesense_codegen/src/apis/stemming_api.rs @@ -4,20 +4,21 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ -use super::{ContentType, Error, configuration}; -use crate::{apis::ResponseContent, models}; + use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`get_stemming_dictionary`] #[derive(Clone, Debug)] pub struct GetStemmingDictionaryParams { /// The ID of the dictionary to retrieve - pub dictionary_id: String, + pub dictionary_id: String } /// struct for passing parameters to the method [`import_stemming_dictionary`] @@ -26,9 +27,10 @@ pub struct ImportStemmingDictionaryParams { /// The ID to assign to the dictionary pub id: String, /// The JSONL file containing word mappings - pub body: String, + pub body: String } + /// struct for typed errors of method [`get_stemming_dictionary`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -52,16 +54,11 @@ pub enum ListStemmingDictionariesError { UnknownValue(serde_json::Value), } + /// Fetch details of a specific stemming dictionary. -pub async fn get_stemming_dictionary( - configuration: &configuration::Configuration, - params: GetStemmingDictionaryParams, -) -> Result> { - let uri_str = format!( - "{}/stemming/dictionaries/{dictionaryId}", - configuration.base_path, - dictionaryId = crate::apis::urlencode(params.dictionary_id) - ); +pub async fn get_stemming_dictionary(configuration: &configuration::Configuration, params: GetStemmingDictionaryParams) -> Result> { + + let uri_str = format!("{}/stemming/dictionaries/{dictionaryId}", configuration.base_path, dictionaryId=crate::apis::urlencode(params.dictionary_id)); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -91,37 +88,21 @@ pub async fn get_stemming_dictionary( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::StemmingDictionary`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::StemmingDictionary`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::StemmingDictionary`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::StemmingDictionary`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Upload a JSONL file containing word mappings to create or update a stemming dictionary. -pub async fn import_stemming_dictionary( - configuration: &configuration::Configuration, - params: ImportStemmingDictionaryParams, -) -> Result> { +pub async fn import_stemming_dictionary(configuration: &configuration::Configuration, params: ImportStemmingDictionaryParams) -> Result> { + let uri_str = format!("{}/stemming/dictionaries/import", configuration.base_path); - let mut req_builder = configuration - .client - .request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); req_builder = req_builder.query(&[("id", ¶ms.id.to_string())]); if let Some(ref user_agent) = configuration.user_agent { @@ -152,32 +133,19 @@ pub async fn import_stemming_dictionary( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `String`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `String`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `String`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `String`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Retrieve a list of all available stemming dictionaries. -pub async fn list_stemming_dictionaries( - configuration: &configuration::Configuration, -) -> Result> { +pub async fn list_stemming_dictionaries(configuration: &configuration::Configuration) -> Result> { + let uri_str = format!("{}/stemming/dictionaries", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -208,24 +176,13 @@ pub async fn list_stemming_dictionaries( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::ListStemmingDictionaries200Response`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::ListStemmingDictionaries200Response`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ListStemmingDictionaries200Response`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ListStemmingDictionaries200Response`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } + diff --git a/typesense_codegen/src/apis/stopwords_api.rs b/typesense_codegen/src/apis/stopwords_api.rs index c74b98d..9fd4519 100644 --- a/typesense_codegen/src/apis/stopwords_api.rs +++ b/typesense_codegen/src/apis/stopwords_api.rs @@ -4,27 +4,28 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ -use super::{ContentType, Error, configuration}; -use crate::{apis::ResponseContent, models}; + use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`delete_stopwords_set`] #[derive(Clone, Debug)] pub struct DeleteStopwordsSetParams { /// The ID of the stopwords set to delete. - pub set_id: String, + pub set_id: String } /// struct for passing parameters to the method [`retrieve_stopwords_set`] #[derive(Clone, Debug)] pub struct RetrieveStopwordsSetParams { /// The ID of the stopwords set to retrieve. - pub set_id: String, + pub set_id: String } /// struct for passing parameters to the method [`upsert_stopwords_set`] @@ -33,9 +34,10 @@ pub struct UpsertStopwordsSetParams { /// The ID of the stopwords set to upsert. pub set_id: String, /// The stopwords set to upsert. - pub stopwords_set_upsert_schema: models::StopwordsSetUpsertSchema, + pub stopwords_set_upsert_schema: models::StopwordsSetUpsertSchema } + /// struct for typed errors of method [`delete_stopwords_set`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -67,19 +69,12 @@ pub enum UpsertStopwordsSetError { UnknownValue(serde_json::Value), } + /// Permanently deletes a stopwords set, given it's name. -pub async fn delete_stopwords_set( - configuration: &configuration::Configuration, - params: DeleteStopwordsSetParams, -) -> Result> { - let uri_str = format!( - "{}/stopwords/{setId}", - configuration.base_path, - setId = crate::apis::urlencode(params.set_id) - ); - let mut req_builder = configuration - .client - .request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_stopwords_set(configuration: &configuration::Configuration, params: DeleteStopwordsSetParams) -> Result> { + + let uri_str = format!("{}/stopwords/{setId}", configuration.base_path, setId=crate::apis::urlencode(params.set_id)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -108,38 +103,20 @@ pub async fn delete_stopwords_set( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::DeleteStopwordsSet200Response`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::DeleteStopwordsSet200Response`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::DeleteStopwordsSet200Response`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::DeleteStopwordsSet200Response`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Retrieve the details of a stopwords set, given it's name. -pub async fn retrieve_stopwords_set( - configuration: &configuration::Configuration, - params: RetrieveStopwordsSetParams, -) -> Result> { - let uri_str = format!( - "{}/stopwords/{setId}", - configuration.base_path, - setId = crate::apis::urlencode(params.set_id) - ); +pub async fn retrieve_stopwords_set(configuration: &configuration::Configuration, params: RetrieveStopwordsSetParams) -> Result> { + + let uri_str = format!("{}/stopwords/{setId}", configuration.base_path, setId=crate::apis::urlencode(params.set_id)); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -169,32 +146,19 @@ pub async fn retrieve_stopwords_set( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::StopwordsSetRetrieveSchema`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::StopwordsSetRetrieveSchema`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::StopwordsSetRetrieveSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::StopwordsSetRetrieveSchema`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Retrieve the details of all stopwords sets -pub async fn retrieve_stopwords_sets( - configuration: &configuration::Configuration, -) -> Result> { +pub async fn retrieve_stopwords_sets(configuration: &configuration::Configuration) -> Result> { + let uri_str = format!("{}/stopwords", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -225,38 +189,20 @@ pub async fn retrieve_stopwords_sets( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::StopwordsSetsRetrieveAllSchema`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::StopwordsSetsRetrieveAllSchema`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::StopwordsSetsRetrieveAllSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::StopwordsSetsRetrieveAllSchema`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// When an analytics rule is created, we give it a name and describe the type, the source collections and the destination collection. -pub async fn upsert_stopwords_set( - configuration: &configuration::Configuration, - params: UpsertStopwordsSetParams, -) -> Result> { - let uri_str = format!( - "{}/stopwords/{setId}", - configuration.base_path, - setId = crate::apis::urlencode(params.set_id) - ); +pub async fn upsert_stopwords_set(configuration: &configuration::Configuration, params: UpsertStopwordsSetParams) -> Result> { + + let uri_str = format!("{}/stopwords/{setId}", configuration.base_path, setId=crate::apis::urlencode(params.set_id)); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -287,24 +233,13 @@ pub async fn upsert_stopwords_set( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::StopwordsSetSchema`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::StopwordsSetSchema`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::StopwordsSetSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::StopwordsSetSchema`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } + diff --git a/typesense_codegen/src/apis/synonyms_api.rs b/typesense_codegen/src/apis/synonyms_api.rs index 79ccdfc..65473af 100644 --- a/typesense_codegen/src/apis/synonyms_api.rs +++ b/typesense_codegen/src/apis/synonyms_api.rs @@ -4,27 +4,28 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ -use super::{ContentType, Error, configuration}; -use crate::{apis::ResponseContent, models}; + use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`delete_synonym_set`] #[derive(Clone, Debug)] pub struct DeleteSynonymSetParams { /// The name of the synonym set to delete - pub synonym_set_name: String, + pub synonym_set_name: String } /// struct for passing parameters to the method [`retrieve_synonym_set`] #[derive(Clone, Debug)] pub struct RetrieveSynonymSetParams { /// The name of the synonym set to retrieve - pub synonym_set_name: String, + pub synonym_set_name: String } /// struct for passing parameters to the method [`upsert_synonym_set`] @@ -33,9 +34,10 @@ pub struct UpsertSynonymSetParams { /// The name of the synonym set to create/update pub synonym_set_name: String, /// The synonym set to be created/updated - pub synonym_set_create_schema: models::SynonymSetCreateSchema, + pub synonym_set_create_schema: models::SynonymSetCreateSchema } + /// struct for typed errors of method [`delete_synonym_set`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -67,19 +69,12 @@ pub enum UpsertSynonymSetError { UnknownValue(serde_json::Value), } + /// Delete a specific synonym set by its name -pub async fn delete_synonym_set( - configuration: &configuration::Configuration, - params: DeleteSynonymSetParams, -) -> Result> { - let uri_str = format!( - "{}/synonym_sets/{synonymSetName}", - configuration.base_path, - synonymSetName = crate::apis::urlencode(params.synonym_set_name) - ); - let mut req_builder = configuration - .client - .request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_synonym_set(configuration: &configuration::Configuration, params: DeleteSynonymSetParams) -> Result> { + + let uri_str = format!("{}/synonym_sets/{synonymSetName}", configuration.base_path, synonymSetName=crate::apis::urlencode(params.synonym_set_name)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -108,38 +103,20 @@ pub async fn delete_synonym_set( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::SynonymSetDeleteSchema`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::SynonymSetDeleteSchema`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SynonymSetDeleteSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SynonymSetDeleteSchema`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Retrieve a specific synonym set by its name -pub async fn retrieve_synonym_set( - configuration: &configuration::Configuration, - params: RetrieveSynonymSetParams, -) -> Result> { - let uri_str = format!( - "{}/synonym_sets/{synonymSetName}", - configuration.base_path, - synonymSetName = crate::apis::urlencode(params.synonym_set_name) - ); +pub async fn retrieve_synonym_set(configuration: &configuration::Configuration, params: RetrieveSynonymSetParams) -> Result> { + + let uri_str = format!("{}/synonym_sets/{synonymSetName}", configuration.base_path, synonymSetName=crate::apis::urlencode(params.synonym_set_name)); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -169,32 +146,19 @@ pub async fn retrieve_synonym_set( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::SynonymSetCreateSchema`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::SynonymSetCreateSchema`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SynonymSetCreateSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SynonymSetCreateSchema`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Retrieve all synonym sets -pub async fn retrieve_synonym_sets( - configuration: &configuration::Configuration, -) -> Result, Error> { +pub async fn retrieve_synonym_sets(configuration: &configuration::Configuration) -> Result, Error> { + let uri_str = format!("{}/synonym_sets", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -225,38 +189,20 @@ pub async fn retrieve_synonym_sets( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `Vec`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `Vec`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Create or update a synonym set with the given name -pub async fn upsert_synonym_set( - configuration: &configuration::Configuration, - params: UpsertSynonymSetParams, -) -> Result> { - let uri_str = format!( - "{}/synonym_sets/{synonymSetName}", - configuration.base_path, - synonymSetName = crate::apis::urlencode(params.synonym_set_name) - ); +pub async fn upsert_synonym_set(configuration: &configuration::Configuration, params: UpsertSynonymSetParams) -> Result> { + + let uri_str = format!("{}/synonym_sets/{synonymSetName}", configuration.base_path, synonymSetName=crate::apis::urlencode(params.synonym_set_name)); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -287,24 +233,13 @@ pub async fn upsert_synonym_set( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => { - return Err(Error::from(serde_json::Error::custom( - "Received `text/plain` content type response that cannot be converted to `models::SynonymSetSchema`", - ))); - } - ContentType::Unsupported(unknown_type) => { - return Err(Error::from(serde_json::Error::custom(format!( - "Received `{unknown_type}` content type response that cannot be converted to `models::SynonymSetSchema`" - )))); - } + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SynonymSetSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SynonymSetSchema`")))), } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { - status, - content, - entity, - })) + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } + diff --git a/typesense_codegen/src/models/analytics_event.rs b/typesense_codegen/src/models/analytics_event.rs index 7ab05e0..4559896 100644 --- a/typesense_codegen/src/models/analytics_event.rs +++ b/typesense_codegen/src/models/analytics_event.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -24,11 +24,7 @@ pub struct AnalyticsEvent { } impl AnalyticsEvent { - pub fn new( - name: String, - event_type: String, - data: models::AnalyticsEventData, - ) -> AnalyticsEvent { + pub fn new(name: String, event_type: String, data: models::AnalyticsEventData) -> AnalyticsEvent{ AnalyticsEvent { name, event_type, @@ -36,3 +32,4 @@ impl AnalyticsEvent { } } } + diff --git a/typesense_codegen/src/models/analytics_event_create_response.rs b/typesense_codegen/src/models/analytics_event_create_response.rs index 2018290..c15ca25 100644 --- a/typesense_codegen/src/models/analytics_event_create_response.rs +++ b/typesense_codegen/src/models/analytics_event_create_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,7 +18,10 @@ pub struct AnalyticsEventCreateResponse { } impl AnalyticsEventCreateResponse { - pub fn new(ok: bool) -> AnalyticsEventCreateResponse { - AnalyticsEventCreateResponse { ok } + pub fn new(ok: bool) -> AnalyticsEventCreateResponse{ + AnalyticsEventCreateResponse { + ok, + } } } + diff --git a/typesense_codegen/src/models/analytics_event_data.rs b/typesense_codegen/src/models/analytics_event_data.rs index 7c28241..75b44f9 100644 --- a/typesense_codegen/src/models/analytics_event_data.rs +++ b/typesense_codegen/src/models/analytics_event_data.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -28,7 +28,7 @@ pub struct AnalyticsEventData { impl AnalyticsEventData { /// Event payload - pub fn new() -> AnalyticsEventData { + pub fn new() -> AnalyticsEventData{ AnalyticsEventData { user_id: None, doc_id: None, @@ -38,3 +38,4 @@ impl AnalyticsEventData { } } } + diff --git a/typesense_codegen/src/models/analytics_events_response.rs b/typesense_codegen/src/models/analytics_events_response.rs index a0de4e0..fafd98b 100644 --- a/typesense_codegen/src/models/analytics_events_response.rs +++ b/typesense_codegen/src/models/analytics_events_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,7 +18,10 @@ pub struct AnalyticsEventsResponse { } impl AnalyticsEventsResponse { - pub fn new(events: Vec) -> AnalyticsEventsResponse { - AnalyticsEventsResponse { events } + pub fn new(events: Vec) -> AnalyticsEventsResponse{ + AnalyticsEventsResponse { + events, + } } } + diff --git a/typesense_codegen/src/models/analytics_events_response_events_inner.rs b/typesense_codegen/src/models/analytics_events_response_events_inner.rs index 9744a20..93f9dfc 100644 --- a/typesense_codegen/src/models/analytics_events_response_events_inner.rs +++ b/typesense_codegen/src/models/analytics_events_response_events_inner.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -32,7 +32,7 @@ pub struct AnalyticsEventsResponseEventsInner { } impl AnalyticsEventsResponseEventsInner { - pub fn new() -> AnalyticsEventsResponseEventsInner { + pub fn new() -> AnalyticsEventsResponseEventsInner{ AnalyticsEventsResponseEventsInner { name: None, event_type: None, @@ -45,3 +45,4 @@ impl AnalyticsEventsResponseEventsInner { } } } + diff --git a/typesense_codegen/src/models/analytics_rule.rs b/typesense_codegen/src/models/analytics_rule.rs index 4c01197..cc15a1d 100644 --- a/typesense_codegen/src/models/analytics_rule.rs +++ b/typesense_codegen/src/models/analytics_rule.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -28,12 +28,7 @@ pub struct AnalyticsRule { } impl AnalyticsRule { - pub fn new( - name: String, - r#type: Type, - collection: String, - event_type: String, - ) -> AnalyticsRule { + pub fn new(name: String, r#type: Type, collection: String, event_type: String) -> AnalyticsRule{ AnalyticsRule { name, r#type, @@ -44,7 +39,7 @@ impl AnalyticsRule { } } } -/// +/// #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum Type { #[serde(rename = "popular_queries")] @@ -62,3 +57,4 @@ impl Default for Type { Self::PopularQueries } } + diff --git a/typesense_codegen/src/models/analytics_rule_create.rs b/typesense_codegen/src/models/analytics_rule_create.rs index b9f8993..9373230 100644 --- a/typesense_codegen/src/models/analytics_rule_create.rs +++ b/typesense_codegen/src/models/analytics_rule_create.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -28,12 +28,7 @@ pub struct AnalyticsRuleCreate { } impl AnalyticsRuleCreate { - pub fn new( - name: String, - r#type: Type, - collection: String, - event_type: String, - ) -> AnalyticsRuleCreate { + pub fn new(name: String, r#type: Type, collection: String, event_type: String) -> AnalyticsRuleCreate{ AnalyticsRuleCreate { name, r#type, @@ -44,7 +39,7 @@ impl AnalyticsRuleCreate { } } } -/// +/// #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum Type { #[serde(rename = "popular_queries")] @@ -62,3 +57,4 @@ impl Default for Type { Self::PopularQueries } } + diff --git a/typesense_codegen/src/models/analytics_rule_create_params.rs b/typesense_codegen/src/models/analytics_rule_create_params.rs index 6127dd3..de7cf5a 100644 --- a/typesense_codegen/src/models/analytics_rule_create_params.rs +++ b/typesense_codegen/src/models/analytics_rule_create_params.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -13,17 +13,11 @@ use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct AnalyticsRuleCreateParams { - #[serde( - rename = "destination_collection", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "destination_collection", skip_serializing_if = "Option::is_none")] pub destination_collection: Option, #[serde(rename = "limit", skip_serializing_if = "Option::is_none")] pub limit: Option, - #[serde( - rename = "capture_search_requests", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "capture_search_requests", skip_serializing_if = "Option::is_none")] pub capture_search_requests: Option, #[serde(rename = "meta_fields", skip_serializing_if = "Option::is_none")] pub meta_fields: Option>, @@ -36,7 +30,7 @@ pub struct AnalyticsRuleCreateParams { } impl AnalyticsRuleCreateParams { - pub fn new() -> AnalyticsRuleCreateParams { + pub fn new() -> AnalyticsRuleCreateParams{ AnalyticsRuleCreateParams { destination_collection: None, limit: None, @@ -48,3 +42,4 @@ impl AnalyticsRuleCreateParams { } } } + diff --git a/typesense_codegen/src/models/analytics_rule_update.rs b/typesense_codegen/src/models/analytics_rule_update.rs index 3a42cc4..66ad385 100644 --- a/typesense_codegen/src/models/analytics_rule_update.rs +++ b/typesense_codegen/src/models/analytics_rule_update.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -24,7 +24,7 @@ pub struct AnalyticsRuleUpdate { impl AnalyticsRuleUpdate { /// Fields allowed to update on an analytics rule - pub fn new() -> AnalyticsRuleUpdate { + pub fn new() -> AnalyticsRuleUpdate{ AnalyticsRuleUpdate { name: None, rule_tag: None, @@ -32,3 +32,4 @@ impl AnalyticsRuleUpdate { } } } + diff --git a/typesense_codegen/src/models/analytics_status.rs b/typesense_codegen/src/models/analytics_status.rs index ee3f151..9d1b6bf 100644 --- a/typesense_codegen/src/models/analytics_status.rs +++ b/typesense_codegen/src/models/analytics_status.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -13,24 +13,15 @@ use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct AnalyticsStatus { - #[serde( - rename = "popular_prefix_queries", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "popular_prefix_queries", skip_serializing_if = "Option::is_none")] pub popular_prefix_queries: Option, - #[serde( - rename = "nohits_prefix_queries", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "nohits_prefix_queries", skip_serializing_if = "Option::is_none")] pub nohits_prefix_queries: Option, #[serde(rename = "log_prefix_queries", skip_serializing_if = "Option::is_none")] pub log_prefix_queries: Option, #[serde(rename = "query_log_events", skip_serializing_if = "Option::is_none")] pub query_log_events: Option, - #[serde( - rename = "query_counter_events", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "query_counter_events", skip_serializing_if = "Option::is_none")] pub query_counter_events: Option, #[serde(rename = "doc_log_events", skip_serializing_if = "Option::is_none")] pub doc_log_events: Option, @@ -39,7 +30,7 @@ pub struct AnalyticsStatus { } impl AnalyticsStatus { - pub fn new() -> AnalyticsStatus { + pub fn new() -> AnalyticsStatus{ AnalyticsStatus { popular_prefix_queries: None, nohits_prefix_queries: None, @@ -51,3 +42,4 @@ impl AnalyticsStatus { } } } + diff --git a/typesense_codegen/src/models/api_key.rs b/typesense_codegen/src/models/api_key.rs index 511f8b9..f108ead 100644 --- a/typesense_codegen/src/models/api_key.rs +++ b/typesense_codegen/src/models/api_key.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -30,7 +30,7 @@ pub struct ApiKey { } impl ApiKey { - pub fn new(description: String, actions: Vec, collections: Vec) -> ApiKey { + pub fn new(description: String, actions: Vec, collections: Vec) -> ApiKey{ ApiKey { value: None, description, @@ -42,3 +42,4 @@ impl ApiKey { } } } + diff --git a/typesense_codegen/src/models/api_key_delete_response.rs b/typesense_codegen/src/models/api_key_delete_response.rs index b9b453e..c12440d 100644 --- a/typesense_codegen/src/models/api_key_delete_response.rs +++ b/typesense_codegen/src/models/api_key_delete_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,7 +19,10 @@ pub struct ApiKeyDeleteResponse { } impl ApiKeyDeleteResponse { - pub fn new(id: i64) -> ApiKeyDeleteResponse { - ApiKeyDeleteResponse { id } + pub fn new(id: i64) -> ApiKeyDeleteResponse{ + ApiKeyDeleteResponse { + id, + } } } + diff --git a/typesense_codegen/src/models/api_key_schema.rs b/typesense_codegen/src/models/api_key_schema.rs index 095e5ec..3e8c2ab 100644 --- a/typesense_codegen/src/models/api_key_schema.rs +++ b/typesense_codegen/src/models/api_key_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -26,11 +26,7 @@ pub struct ApiKeySchema { } impl ApiKeySchema { - pub fn new( - description: String, - actions: Vec, - collections: Vec, - ) -> ApiKeySchema { + pub fn new(description: String, actions: Vec, collections: Vec) -> ApiKeySchema{ ApiKeySchema { value: None, description, @@ -40,3 +36,4 @@ impl ApiKeySchema { } } } + diff --git a/typesense_codegen/src/models/api_keys_response.rs b/typesense_codegen/src/models/api_keys_response.rs index 784a6bf..ca7686c 100644 --- a/typesense_codegen/src/models/api_keys_response.rs +++ b/typesense_codegen/src/models/api_keys_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,7 +18,10 @@ pub struct ApiKeysResponse { } impl ApiKeysResponse { - pub fn new(keys: Vec) -> ApiKeysResponse { - ApiKeysResponse { keys } + pub fn new(keys: Vec) -> ApiKeysResponse{ + ApiKeysResponse { + keys, + } } } + diff --git a/typesense_codegen/src/models/api_response.rs b/typesense_codegen/src/models/api_response.rs index 0a27c4f..08c2c11 100644 --- a/typesense_codegen/src/models/api_response.rs +++ b/typesense_codegen/src/models/api_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,7 +18,10 @@ pub struct ApiResponse { } impl ApiResponse { - pub fn new(message: String) -> ApiResponse { - ApiResponse { message } + pub fn new(message: String) -> ApiResponse{ + ApiResponse { + message, + } } } + diff --git a/typesense_codegen/src/models/api_stats_response.rs b/typesense_codegen/src/models/api_stats_response.rs index c35c77a..d8d2933 100644 --- a/typesense_codegen/src/models/api_stats_response.rs +++ b/typesense_codegen/src/models/api_stats_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -15,58 +15,34 @@ use serde::{Deserialize, Serialize}; pub struct ApiStatsResponse { #[serde(rename = "delete_latency_ms", skip_serializing_if = "Option::is_none")] pub delete_latency_ms: Option, - #[serde( - rename = "delete_requests_per_second", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "delete_requests_per_second", skip_serializing_if = "Option::is_none")] pub delete_requests_per_second: Option, #[serde(rename = "import_latency_ms", skip_serializing_if = "Option::is_none")] pub import_latency_ms: Option, - #[serde( - rename = "import_requests_per_second", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "import_requests_per_second", skip_serializing_if = "Option::is_none")] pub import_requests_per_second: Option, #[serde(rename = "latency_ms", skip_serializing_if = "Option::is_none")] pub latency_ms: Option, - #[serde( - rename = "overloaded_requests_per_second", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "overloaded_requests_per_second", skip_serializing_if = "Option::is_none")] pub overloaded_requests_per_second: Option, - #[serde( - rename = "pending_write_batches", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "pending_write_batches", skip_serializing_if = "Option::is_none")] pub pending_write_batches: Option, - #[serde( - rename = "requests_per_second", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "requests_per_second", skip_serializing_if = "Option::is_none")] pub requests_per_second: Option, #[serde(rename = "search_latency_ms", skip_serializing_if = "Option::is_none")] pub search_latency_ms: Option, - #[serde( - rename = "search_requests_per_second", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "search_requests_per_second", skip_serializing_if = "Option::is_none")] pub search_requests_per_second: Option, - #[serde( - rename = "total_requests_per_second", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "total_requests_per_second", skip_serializing_if = "Option::is_none")] pub total_requests_per_second: Option, #[serde(rename = "write_latency_ms", skip_serializing_if = "Option::is_none")] pub write_latency_ms: Option, - #[serde( - rename = "write_requests_per_second", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "write_requests_per_second", skip_serializing_if = "Option::is_none")] pub write_requests_per_second: Option, } impl ApiStatsResponse { - pub fn new() -> ApiStatsResponse { + pub fn new() -> ApiStatsResponse{ ApiStatsResponse { delete_latency_ms: None, delete_requests_per_second: None, @@ -84,3 +60,4 @@ impl ApiStatsResponse { } } } + diff --git a/typesense_codegen/src/models/collection_alias.rs b/typesense_codegen/src/models/collection_alias.rs index b5a61fe..f94f6a2 100644 --- a/typesense_codegen/src/models/collection_alias.rs +++ b/typesense_codegen/src/models/collection_alias.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -22,10 +22,11 @@ pub struct CollectionAlias { } impl CollectionAlias { - pub fn new(name: String, collection_name: String) -> CollectionAlias { + pub fn new(name: String, collection_name: String) -> CollectionAlias{ CollectionAlias { name, collection_name, } } } + diff --git a/typesense_codegen/src/models/collection_alias_schema.rs b/typesense_codegen/src/models/collection_alias_schema.rs index b35d641..3a67ea0 100644 --- a/typesense_codegen/src/models/collection_alias_schema.rs +++ b/typesense_codegen/src/models/collection_alias_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,7 +19,10 @@ pub struct CollectionAliasSchema { } impl CollectionAliasSchema { - pub fn new(collection_name: String) -> CollectionAliasSchema { - CollectionAliasSchema { collection_name } + pub fn new(collection_name: String) -> CollectionAliasSchema{ + CollectionAliasSchema { + collection_name, + } } } + diff --git a/typesense_codegen/src/models/collection_aliases_response.rs b/typesense_codegen/src/models/collection_aliases_response.rs index 3cf2d25..0db53a1 100644 --- a/typesense_codegen/src/models/collection_aliases_response.rs +++ b/typesense_codegen/src/models/collection_aliases_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,7 +18,10 @@ pub struct CollectionAliasesResponse { } impl CollectionAliasesResponse { - pub fn new(aliases: Vec) -> CollectionAliasesResponse { - CollectionAliasesResponse { aliases } + pub fn new(aliases: Vec) -> CollectionAliasesResponse{ + CollectionAliasesResponse { + aliases, + } } } + diff --git a/typesense_codegen/src/models/collection_response.rs b/typesense_codegen/src/models/collection_response.rs index 1039909..d664428 100644 --- a/typesense_codegen/src/models/collection_response.rs +++ b/typesense_codegen/src/models/collection_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -20,29 +20,23 @@ pub struct CollectionResponse { #[serde(rename = "fields")] pub fields: Vec, /// The name of an int32 / float field that determines the order in which the search results are ranked when a sort_by clause is not provided during searching. This field must indicate some kind of popularity. - #[serde( - rename = "default_sorting_field", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "default_sorting_field", skip_serializing_if = "Option::is_none")] pub default_sorting_field: Option, - /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. + /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. #[serde(rename = "token_separators", skip_serializing_if = "Option::is_none")] pub token_separators: Option>, /// List of synonym set names to associate with this collection #[serde(rename = "synonym_sets", skip_serializing_if = "Option::is_none")] pub synonym_sets: Option>, /// Enables experimental support at a collection level for nested object or object array fields. This field is only available if the Typesense server is version `0.24.0.rcn34` or later. - #[serde( - rename = "enable_nested_fields", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "enable_nested_fields", skip_serializing_if = "Option::is_none")] pub enable_nested_fields: Option, - /// List of symbols or special characters to be indexed. + /// List of symbols or special characters to be indexed. #[serde(rename = "symbols_to_index", skip_serializing_if = "Option::is_none")] pub symbols_to_index: Option>, #[serde(rename = "voice_query_model", skip_serializing_if = "Option::is_none")] pub voice_query_model: Option>, - /// Optional details about the collection, e.g., when it was created, who created it etc. + /// Optional details about the collection, e.g., when it was created, who created it etc. #[serde(rename = "metadata", skip_serializing_if = "Option::is_none")] pub metadata: Option, /// Number of documents in the collection @@ -54,12 +48,7 @@ pub struct CollectionResponse { } impl CollectionResponse { - pub fn new( - name: String, - fields: Vec, - num_documents: i64, - created_at: i64, - ) -> CollectionResponse { + pub fn new(name: String, fields: Vec, num_documents: i64, created_at: i64) -> CollectionResponse{ CollectionResponse { name, fields, @@ -75,3 +64,4 @@ impl CollectionResponse { } } } + diff --git a/typesense_codegen/src/models/collection_schema.rs b/typesense_codegen/src/models/collection_schema.rs index b861bee..7e2c754 100644 --- a/typesense_codegen/src/models/collection_schema.rs +++ b/typesense_codegen/src/models/collection_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -22,35 +22,29 @@ pub struct CollectionSchema { #[serde(rename = "fields")] pub fields: Vec, /// The name of an int32 / float field that determines the order in which the search results are ranked when a sort_by clause is not provided during searching. This field must indicate some kind of popularity. - #[serde( - rename = "default_sorting_field", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "default_sorting_field", skip_serializing_if = "Option::is_none")] pub default_sorting_field: Option, - /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. + /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. #[serde(rename = "token_separators", skip_serializing_if = "Option::is_none")] pub token_separators: Option>, /// List of synonym set names to associate with this collection #[serde(rename = "synonym_sets", skip_serializing_if = "Option::is_none")] pub synonym_sets: Option>, /// Enables experimental support at a collection level for nested object or object array fields. This field is only available if the Typesense server is version `0.24.0.rcn34` or later. - #[serde( - rename = "enable_nested_fields", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "enable_nested_fields", skip_serializing_if = "Option::is_none")] pub enable_nested_fields: Option, - /// List of symbols or special characters to be indexed. + /// List of symbols or special characters to be indexed. #[serde(rename = "symbols_to_index", skip_serializing_if = "Option::is_none")] pub symbols_to_index: Option>, #[serde(rename = "voice_query_model", skip_serializing_if = "Option::is_none")] pub voice_query_model: Option>, - /// Optional details about the collection, e.g., when it was created, who created it etc. + /// Optional details about the collection, e.g., when it was created, who created it etc. #[serde(rename = "metadata", skip_serializing_if = "Option::is_none")] pub metadata: Option, } impl CollectionSchema { - pub fn new(name: String, fields: Vec) -> CollectionSchema { + pub fn new(name: String, fields: Vec) -> CollectionSchema{ CollectionSchema { name, fields, @@ -64,3 +58,4 @@ impl CollectionSchema { } } } + diff --git a/typesense_codegen/src/models/collection_update_schema.rs b/typesense_codegen/src/models/collection_update_schema.rs index 27a4d09..ca45a78 100644 --- a/typesense_codegen/src/models/collection_update_schema.rs +++ b/typesense_codegen/src/models/collection_update_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,13 +19,13 @@ pub struct CollectionUpdateSchema { /// List of synonym set names to associate with this collection #[serde(rename = "synonym_sets", skip_serializing_if = "Option::is_none")] pub synonym_sets: Option>, - /// Optional details about the collection, e.g., when it was created, who created it etc. + /// Optional details about the collection, e.g., when it was created, who created it etc. #[serde(rename = "metadata", skip_serializing_if = "Option::is_none")] pub metadata: Option, } impl CollectionUpdateSchema { - pub fn new(fields: Vec) -> CollectionUpdateSchema { + pub fn new(fields: Vec) -> CollectionUpdateSchema{ CollectionUpdateSchema { fields, synonym_sets: None, @@ -33,3 +33,4 @@ impl CollectionUpdateSchema { } } } + diff --git a/typesense_codegen/src/models/conversation_model_create_schema.rs b/typesense_codegen/src/models/conversation_model_create_schema.rs index fc587c3..3a2ed5b 100644 --- a/typesense_codegen/src/models/conversation_model_create_schema.rs +++ b/typesense_codegen/src/models/conversation_model_create_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -31,10 +31,10 @@ pub struct ConversationModelCreateSchema { /// The system prompt that contains special instructions to the LLM #[serde(rename = "system_prompt", skip_serializing_if = "Option::is_none")] pub system_prompt: Option, - /// Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) + /// Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) #[serde(rename = "ttl", skip_serializing_if = "Option::is_none")] pub ttl: Option, - /// The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. + /// The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. #[serde(rename = "max_bytes")] pub max_bytes: i32, /// URL of vLLM service @@ -43,11 +43,7 @@ pub struct ConversationModelCreateSchema { } impl ConversationModelCreateSchema { - pub fn new( - model_name: String, - history_collection: String, - max_bytes: i32, - ) -> ConversationModelCreateSchema { + pub fn new(model_name: String, history_collection: String, max_bytes: i32) -> ConversationModelCreateSchema{ ConversationModelCreateSchema { id: None, model_name, @@ -61,3 +57,4 @@ impl ConversationModelCreateSchema { } } } + diff --git a/typesense_codegen/src/models/conversation_model_schema.rs b/typesense_codegen/src/models/conversation_model_schema.rs index 1738f77..828988d 100644 --- a/typesense_codegen/src/models/conversation_model_schema.rs +++ b/typesense_codegen/src/models/conversation_model_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -31,10 +31,10 @@ pub struct ConversationModelSchema { /// The system prompt that contains special instructions to the LLM #[serde(rename = "system_prompt", skip_serializing_if = "Option::is_none")] pub system_prompt: Option, - /// Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) + /// Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) #[serde(rename = "ttl", skip_serializing_if = "Option::is_none")] pub ttl: Option, - /// The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. + /// The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. #[serde(rename = "max_bytes")] pub max_bytes: i32, /// URL of vLLM service @@ -43,12 +43,7 @@ pub struct ConversationModelSchema { } impl ConversationModelSchema { - pub fn new( - id: String, - model_name: String, - history_collection: String, - max_bytes: i32, - ) -> ConversationModelSchema { + pub fn new(id: String, model_name: String, history_collection: String, max_bytes: i32) -> ConversationModelSchema{ ConversationModelSchema { id, model_name, @@ -62,3 +57,4 @@ impl ConversationModelSchema { } } } + diff --git a/typesense_codegen/src/models/conversation_model_update_schema.rs b/typesense_codegen/src/models/conversation_model_update_schema.rs index 1335019..7ac5e40 100644 --- a/typesense_codegen/src/models/conversation_model_update_schema.rs +++ b/typesense_codegen/src/models/conversation_model_update_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -31,10 +31,10 @@ pub struct ConversationModelUpdateSchema { /// The system prompt that contains special instructions to the LLM #[serde(rename = "system_prompt", skip_serializing_if = "Option::is_none")] pub system_prompt: Option, - /// Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) + /// Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) #[serde(rename = "ttl", skip_serializing_if = "Option::is_none")] pub ttl: Option, - /// The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. + /// The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. #[serde(rename = "max_bytes", skip_serializing_if = "Option::is_none")] pub max_bytes: Option, /// URL of vLLM service @@ -43,7 +43,7 @@ pub struct ConversationModelUpdateSchema { } impl ConversationModelUpdateSchema { - pub fn new() -> ConversationModelUpdateSchema { + pub fn new() -> ConversationModelUpdateSchema{ ConversationModelUpdateSchema { id: None, model_name: None, @@ -57,3 +57,4 @@ impl ConversationModelUpdateSchema { } } } + diff --git a/typesense_codegen/src/models/create_analytics_rule_200_response.rs b/typesense_codegen/src/models/create_analytics_rule_200_response.rs index 80053ca..6d45dca 100644 --- a/typesense_codegen/src/models/create_analytics_rule_200_response.rs +++ b/typesense_codegen/src/models/create_analytics_rule_200_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -23,7 +23,7 @@ impl Default for CreateAnalyticsRule200Response { Self::AnalyticsRule(Default::default()) } } -/// +/// #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum Type { #[serde(rename = "popular_queries")] @@ -41,3 +41,4 @@ impl Default for Type { Self::PopularQueries } } + diff --git a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs index bb9f001..8e773e2 100644 --- a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs +++ b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -30,12 +30,7 @@ pub struct CreateAnalyticsRule200ResponseOneOfInner { } impl CreateAnalyticsRule200ResponseOneOfInner { - pub fn new( - name: String, - r#type: Type, - collection: String, - event_type: String, - ) -> CreateAnalyticsRule200ResponseOneOfInner { + pub fn new(name: String, r#type: Type, collection: String, event_type: String) -> CreateAnalyticsRule200ResponseOneOfInner{ CreateAnalyticsRule200ResponseOneOfInner { name, r#type, @@ -47,7 +42,7 @@ impl CreateAnalyticsRule200ResponseOneOfInner { } } } -/// +/// #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum Type { #[serde(rename = "popular_queries")] @@ -65,3 +60,4 @@ impl Default for Type { Self::PopularQueries } } + diff --git a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs index 08500ef..12f7422 100644 --- a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs +++ b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,7 +18,10 @@ pub struct CreateAnalyticsRule200ResponseOneOfInnerAnyOf { } impl CreateAnalyticsRule200ResponseOneOfInnerAnyOf { - pub fn new() -> CreateAnalyticsRule200ResponseOneOfInnerAnyOf { - CreateAnalyticsRule200ResponseOneOfInnerAnyOf { error: None } + pub fn new() -> CreateAnalyticsRule200ResponseOneOfInnerAnyOf{ + CreateAnalyticsRule200ResponseOneOfInnerAnyOf { + error: None, + } } } + diff --git a/typesense_codegen/src/models/create_analytics_rule_request.rs b/typesense_codegen/src/models/create_analytics_rule_request.rs index 262570e..597dec9 100644 --- a/typesense_codegen/src/models/create_analytics_rule_request.rs +++ b/typesense_codegen/src/models/create_analytics_rule_request.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -23,7 +23,7 @@ impl Default for CreateAnalyticsRuleRequest { Self::AnalyticsRuleCreate(Default::default()) } } -/// +/// #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum Type { #[serde(rename = "popular_queries")] @@ -41,3 +41,4 @@ impl Default for Type { Self::PopularQueries } } + diff --git a/typesense_codegen/src/models/debug_200_response.rs b/typesense_codegen/src/models/debug_200_response.rs index 946d84e..0c88dd7 100644 --- a/typesense_codegen/src/models/debug_200_response.rs +++ b/typesense_codegen/src/models/debug_200_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,7 +18,10 @@ pub struct Debug200Response { } impl Debug200Response { - pub fn new() -> Debug200Response { - Debug200Response { version: None } + pub fn new() -> Debug200Response{ + Debug200Response { + version: None, + } } } + diff --git a/typesense_codegen/src/models/delete_documents_200_response.rs b/typesense_codegen/src/models/delete_documents_200_response.rs index 169020c..5779adf 100644 --- a/typesense_codegen/src/models/delete_documents_200_response.rs +++ b/typesense_codegen/src/models/delete_documents_200_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,7 +18,10 @@ pub struct DeleteDocuments200Response { } impl DeleteDocuments200Response { - pub fn new(num_deleted: i32) -> DeleteDocuments200Response { - DeleteDocuments200Response { num_deleted } + pub fn new(num_deleted: i32) -> DeleteDocuments200Response{ + DeleteDocuments200Response { + num_deleted, + } } } + diff --git a/typesense_codegen/src/models/delete_documents_parameters.rs b/typesense_codegen/src/models/delete_documents_parameters.rs index 55e8241..903d717 100644 --- a/typesense_codegen/src/models/delete_documents_parameters.rs +++ b/typesense_codegen/src/models/delete_documents_parameters.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -26,7 +26,7 @@ pub struct DeleteDocumentsParameters { } impl DeleteDocumentsParameters { - pub fn new(filter_by: String) -> DeleteDocumentsParameters { + pub fn new(filter_by: String) -> DeleteDocumentsParameters{ DeleteDocumentsParameters { filter_by, batch_size: None, @@ -35,3 +35,4 @@ impl DeleteDocumentsParameters { } } } + diff --git a/typesense_codegen/src/models/delete_stopwords_set_200_response.rs b/typesense_codegen/src/models/delete_stopwords_set_200_response.rs index 03b93ef..87fa748 100644 --- a/typesense_codegen/src/models/delete_stopwords_set_200_response.rs +++ b/typesense_codegen/src/models/delete_stopwords_set_200_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,7 +18,10 @@ pub struct DeleteStopwordsSet200Response { } impl DeleteStopwordsSet200Response { - pub fn new(id: String) -> DeleteStopwordsSet200Response { - DeleteStopwordsSet200Response { id } + pub fn new(id: String) -> DeleteStopwordsSet200Response{ + DeleteStopwordsSet200Response { + id, + } } } + diff --git a/typesense_codegen/src/models/dirty_values.rs b/typesense_codegen/src/models/dirty_values.rs index 8caeab9..5c3a422 100644 --- a/typesense_codegen/src/models/dirty_values.rs +++ b/typesense_codegen/src/models/dirty_values.rs @@ -4,14 +4,14 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ use crate::models; use serde::{Deserialize, Serialize}; -/// +/// #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum DirtyValues { #[serde(rename = "coerce_or_reject")] @@ -22,6 +22,7 @@ pub enum DirtyValues { Drop, #[serde(rename = "reject")] Reject, + } impl std::fmt::Display for DirtyValues { @@ -40,3 +41,4 @@ impl Default for DirtyValues { Self::CoerceOrReject } } + diff --git a/typesense_codegen/src/models/drop_tokens_mode.rs b/typesense_codegen/src/models/drop_tokens_mode.rs index 5b8ba01..9769869 100644 --- a/typesense_codegen/src/models/drop_tokens_mode.rs +++ b/typesense_codegen/src/models/drop_tokens_mode.rs @@ -4,15 +4,15 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ use crate::models; use serde::{Deserialize, Serialize}; -/// DropTokensMode : Dictates the direction in which the words in the query must be dropped when the original words in the query do not appear in any document. Values: right_to_left (default), left_to_right, both_sides:3 A note on both_sides:3 - for queries up to 3 tokens (words) in length, this mode will drop tokens from both sides and exhaustively rank all matching results. If query length is greater than 3 words, Typesense will just fallback to default behavior of right_to_left -/// Dictates the direction in which the words in the query must be dropped when the original words in the query do not appear in any document. Values: right_to_left (default), left_to_right, both_sides:3 A note on both_sides:3 - for queries up to 3 tokens (words) in length, this mode will drop tokens from both sides and exhaustively rank all matching results. If query length is greater than 3 words, Typesense will just fallback to default behavior of right_to_left +/// DropTokensMode : Dictates the direction in which the words in the query must be dropped when the original words in the query do not appear in any document. Values: right_to_left (default), left_to_right, both_sides:3 A note on both_sides:3 - for queries up to 3 tokens (words) in length, this mode will drop tokens from both sides and exhaustively rank all matching results. If query length is greater than 3 words, Typesense will just fallback to default behavior of right_to_left +/// Dictates the direction in which the words in the query must be dropped when the original words in the query do not appear in any document. Values: right_to_left (default), left_to_right, both_sides:3 A note on both_sides:3 - for queries up to 3 tokens (words) in length, this mode will drop tokens from both sides and exhaustively rank all matching results. If query length is greater than 3 words, Typesense will just fallback to default behavior of right_to_left #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum DropTokensMode { #[serde(rename = "right_to_left")] @@ -21,6 +21,7 @@ pub enum DropTokensMode { LeftToRight, #[serde(rename = "both_sides:3")] BothSidesColon3, + } impl std::fmt::Display for DropTokensMode { @@ -38,3 +39,4 @@ impl Default for DropTokensMode { Self::RightToLeft } } + diff --git a/typesense_codegen/src/models/export_documents_parameters.rs b/typesense_codegen/src/models/export_documents_parameters.rs index 36984f8..b1defbb 100644 --- a/typesense_codegen/src/models/export_documents_parameters.rs +++ b/typesense_codegen/src/models/export_documents_parameters.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -25,7 +25,7 @@ pub struct ExportDocumentsParameters { } impl ExportDocumentsParameters { - pub fn new() -> ExportDocumentsParameters { + pub fn new() -> ExportDocumentsParameters{ ExportDocumentsParameters { filter_by: None, include_fields: None, @@ -33,3 +33,4 @@ impl ExportDocumentsParameters { } } } + diff --git a/typesense_codegen/src/models/facet_counts.rs b/typesense_codegen/src/models/facet_counts.rs index d9cbdf3..a56913a 100644 --- a/typesense_codegen/src/models/facet_counts.rs +++ b/typesense_codegen/src/models/facet_counts.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -22,7 +22,7 @@ pub struct FacetCounts { } impl FacetCounts { - pub fn new() -> FacetCounts { + pub fn new() -> FacetCounts{ FacetCounts { counts: None, field_name: None, @@ -30,3 +30,4 @@ impl FacetCounts { } } } + diff --git a/typesense_codegen/src/models/facet_counts_counts_inner.rs b/typesense_codegen/src/models/facet_counts_counts_inner.rs index bc6ede2..9b732a5 100644 --- a/typesense_codegen/src/models/facet_counts_counts_inner.rs +++ b/typesense_codegen/src/models/facet_counts_counts_inner.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -24,7 +24,7 @@ pub struct FacetCountsCountsInner { } impl FacetCountsCountsInner { - pub fn new() -> FacetCountsCountsInner { + pub fn new() -> FacetCountsCountsInner{ FacetCountsCountsInner { count: None, highlighted: None, @@ -33,3 +33,4 @@ impl FacetCountsCountsInner { } } } + diff --git a/typesense_codegen/src/models/facet_counts_stats.rs b/typesense_codegen/src/models/facet_counts_stats.rs index 7f0d9dd..24a8e63 100644 --- a/typesense_codegen/src/models/facet_counts_stats.rs +++ b/typesense_codegen/src/models/facet_counts_stats.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -26,7 +26,7 @@ pub struct FacetCountsStats { } impl FacetCountsStats { - pub fn new() -> FacetCountsStats { + pub fn new() -> FacetCountsStats{ FacetCountsStats { max: None, min: None, @@ -36,3 +36,4 @@ impl FacetCountsStats { } } } + diff --git a/typesense_codegen/src/models/field.rs b/typesense_codegen/src/models/field.rs index 39bacbb..b3fd4d7 100644 --- a/typesense_codegen/src/models/field.rs +++ b/typesense_codegen/src/models/field.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -31,32 +31,32 @@ pub struct Field { pub sort: Option, #[serde(rename = "infix", skip_serializing_if = "Option::is_none")] pub infix: Option, - /// Name of a field in another collection that should be linked to this collection so that it can be joined during query. + /// Name of a field in another collection that should be linked to this collection so that it can be joined during query. #[serde(rename = "reference", skip_serializing_if = "Option::is_none")] pub reference: Option, #[serde(rename = "num_dim", skip_serializing_if = "Option::is_none")] pub num_dim: Option, #[serde(rename = "drop", skip_serializing_if = "Option::is_none")] pub drop: Option, - /// When set to false, the field value will not be stored on disk. Default: true. + /// When set to false, the field value will not be stored on disk. Default: true. #[serde(rename = "store", skip_serializing_if = "Option::is_none")] pub store: Option, - /// The distance metric to be used for vector search. Default: `cosine`. You can also use `ip` for inner product. + /// The distance metric to be used for vector search. Default: `cosine`. You can also use `ip` for inner product. #[serde(rename = "vec_dist", skip_serializing_if = "Option::is_none")] pub vec_dist: Option, - /// Enables an index optimized for range filtering on numerical fields (e.g. rating:>3.5). Default: false. + /// Enables an index optimized for range filtering on numerical fields (e.g. rating:>3.5). Default: false. #[serde(rename = "range_index", skip_serializing_if = "Option::is_none")] pub range_index: Option, - /// Values are stemmed before indexing in-memory. Default: false. + /// Values are stemmed before indexing in-memory. Default: false. #[serde(rename = "stem", skip_serializing_if = "Option::is_none")] pub stem: Option, /// Name of the stemming dictionary to use for this field #[serde(rename = "stem_dictionary", skip_serializing_if = "Option::is_none")] pub stem_dictionary: Option, - /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. + /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. #[serde(rename = "token_separators", skip_serializing_if = "Option::is_none")] pub token_separators: Option>, - /// List of symbols or special characters to be indexed. + /// List of symbols or special characters to be indexed. #[serde(rename = "symbols_to_index", skip_serializing_if = "Option::is_none")] pub symbols_to_index: Option>, #[serde(rename = "embed", skip_serializing_if = "Option::is_none")] @@ -64,7 +64,7 @@ pub struct Field { } impl Field { - pub fn new(name: String, r#type: String) -> Field { + pub fn new(name: String, r#type: String) -> Field{ Field { name, r#type, @@ -88,3 +88,4 @@ impl Field { } } } + diff --git a/typesense_codegen/src/models/field_embed.rs b/typesense_codegen/src/models/field_embed.rs index 0e84fd9..2b9b203 100644 --- a/typesense_codegen/src/models/field_embed.rs +++ b/typesense_codegen/src/models/field_embed.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -20,10 +20,11 @@ pub struct FieldEmbed { } impl FieldEmbed { - pub fn new(from: Vec, model_config: models::FieldEmbedModelConfig) -> FieldEmbed { + pub fn new(from: Vec, model_config: models::FieldEmbedModelConfig) -> FieldEmbed{ FieldEmbed { from, model_config: Box::new(model_config), } } } + diff --git a/typesense_codegen/src/models/field_embed_model_config.rs b/typesense_codegen/src/models/field_embed_model_config.rs index ee40bea..407e32f 100644 --- a/typesense_codegen/src/models/field_embed_model_config.rs +++ b/typesense_codegen/src/models/field_embed_model_config.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -36,7 +36,7 @@ pub struct FieldEmbedModelConfig { } impl FieldEmbedModelConfig { - pub fn new(model_name: String) -> FieldEmbedModelConfig { + pub fn new(model_name: String) -> FieldEmbedModelConfig{ FieldEmbedModelConfig { model_name, api_key: None, @@ -51,3 +51,4 @@ impl FieldEmbedModelConfig { } } } + diff --git a/typesense_codegen/src/models/get_collections_parameters.rs b/typesense_codegen/src/models/get_collections_parameters.rs index 02497f6..01226a7 100644 --- a/typesense_codegen/src/models/get_collections_parameters.rs +++ b/typesense_codegen/src/models/get_collections_parameters.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -16,7 +16,7 @@ pub struct GetCollectionsParameters { /// Comma-separated list of fields from the collection to exclude from the response #[serde(rename = "exclude_fields", skip_serializing_if = "Option::is_none")] pub exclude_fields: Option, - /// Number of collections to fetch. Default: returns all collections. + /// Number of collections to fetch. Default: returns all collections. #[serde(rename = "limit", skip_serializing_if = "Option::is_none")] pub limit: Option, /// Identifies the starting point to return collections when paginating. @@ -25,7 +25,7 @@ pub struct GetCollectionsParameters { } impl GetCollectionsParameters { - pub fn new() -> GetCollectionsParameters { + pub fn new() -> GetCollectionsParameters{ GetCollectionsParameters { exclude_fields: None, limit: None, @@ -33,3 +33,4 @@ impl GetCollectionsParameters { } } } + diff --git a/typesense_codegen/src/models/health_status.rs b/typesense_codegen/src/models/health_status.rs index 66cdf6b..82a4489 100644 --- a/typesense_codegen/src/models/health_status.rs +++ b/typesense_codegen/src/models/health_status.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,7 +18,10 @@ pub struct HealthStatus { } impl HealthStatus { - pub fn new(ok: bool) -> HealthStatus { - HealthStatus { ok } + pub fn new(ok: bool) -> HealthStatus{ + HealthStatus { + ok, + } } } + diff --git a/typesense_codegen/src/models/import_documents_parameters.rs b/typesense_codegen/src/models/import_documents_parameters.rs index e17494a..0b7abab 100644 --- a/typesense_codegen/src/models/import_documents_parameters.rs +++ b/typesense_codegen/src/models/import_documents_parameters.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +18,7 @@ pub struct ImportDocumentsParameters { /// Returning the id of the imported documents. If you want the import response to return the ingested document's id in the response, you can use the return_id parameter. #[serde(rename = "return_id", skip_serializing_if = "Option::is_none")] pub return_id: Option, - #[serde( - rename = "remote_embedding_batch_size", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "remote_embedding_batch_size", skip_serializing_if = "Option::is_none")] pub remote_embedding_batch_size: Option, #[serde(rename = "return_doc", skip_serializing_if = "Option::is_none")] pub return_doc: Option, @@ -32,7 +29,7 @@ pub struct ImportDocumentsParameters { } impl ImportDocumentsParameters { - pub fn new() -> ImportDocumentsParameters { + pub fn new() -> ImportDocumentsParameters{ ImportDocumentsParameters { batch_size: None, return_id: None, @@ -43,3 +40,4 @@ impl ImportDocumentsParameters { } } } + diff --git a/typesense_codegen/src/models/index_action.rs b/typesense_codegen/src/models/index_action.rs index eb52174..7bce745 100644 --- a/typesense_codegen/src/models/index_action.rs +++ b/typesense_codegen/src/models/index_action.rs @@ -4,14 +4,14 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ use crate::models; use serde::{Deserialize, Serialize}; -/// +/// #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum IndexAction { #[serde(rename = "create")] @@ -22,6 +22,7 @@ pub enum IndexAction { Upsert, #[serde(rename = "emplace")] Emplace, + } impl std::fmt::Display for IndexAction { @@ -40,3 +41,4 @@ impl Default for IndexAction { Self::Create } } + diff --git a/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs b/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs index 9985e0d..75a8ddf 100644 --- a/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs +++ b/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,7 +18,10 @@ pub struct ListStemmingDictionaries200Response { } impl ListStemmingDictionaries200Response { - pub fn new() -> ListStemmingDictionaries200Response { - ListStemmingDictionaries200Response { dictionaries: None } + pub fn new() -> ListStemmingDictionaries200Response{ + ListStemmingDictionaries200Response { + dictionaries: None, + } } } + diff --git a/typesense_codegen/src/models/multi_search_collection_parameters.rs b/typesense_codegen/src/models/multi_search_collection_parameters.rs index 76f99e0..cc5a457 100644 --- a/typesense_codegen/src/models/multi_search_collection_parameters.rs +++ b/typesense_codegen/src/models/multi_search_collection_parameters.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -54,7 +54,7 @@ pub struct MultiSearchCollectionParameters { /// Facet values that are returned can now be filtered via this parameter. The matching facet text is also highlighted. For example, when faceting by `category`, you can set `facet_query=category:shoe` to return only facet values that contain the prefix \"shoe\". #[serde(rename = "facet_query", skip_serializing_if = "Option::is_none")] pub facet_query: Option, - /// The number of typographical errors (1 or 2) that would be tolerated. Default: 2 + /// The number of typographical errors (1 or 2) that would be tolerated. Default: 2 #[serde(rename = "num_typos", skip_serializing_if = "Option::is_none")] pub num_typos: Option, /// Results from this specific page number would be fetched. @@ -63,7 +63,7 @@ pub struct MultiSearchCollectionParameters { /// Number of results to fetch per page. Default: 10 #[serde(rename = "per_page", skip_serializing_if = "Option::is_none")] pub per_page: Option, - /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. + /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. #[serde(rename = "limit", skip_serializing_if = "Option::is_none")] pub limit: Option, /// Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. @@ -72,14 +72,11 @@ pub struct MultiSearchCollectionParameters { /// You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. #[serde(rename = "group_by", skip_serializing_if = "Option::is_none")] pub group_by: Option, - /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 + /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 #[serde(rename = "group_limit", skip_serializing_if = "Option::is_none")] pub group_limit: Option, - /// Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true - #[serde( - rename = "group_missing_values", - skip_serializing_if = "Option::is_none" - )] + /// Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true + #[serde(rename = "group_missing_values", skip_serializing_if = "Option::is_none")] pub group_missing_values: Option, /// List of fields from the document to include in the search result #[serde(rename = "include_fields", skip_serializing_if = "Option::is_none")] @@ -88,194 +85,140 @@ pub struct MultiSearchCollectionParameters { #[serde(rename = "exclude_fields", skip_serializing_if = "Option::is_none")] pub exclude_fields: Option, /// List of fields which should be highlighted fully without snippeting - #[serde( - rename = "highlight_full_fields", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "highlight_full_fields", skip_serializing_if = "Option::is_none")] pub highlight_full_fields: Option, - /// The number of tokens that should surround the highlighted text on each side. Default: 4 - #[serde( - rename = "highlight_affix_num_tokens", - skip_serializing_if = "Option::is_none" - )] + /// The number of tokens that should surround the highlighted text on each side. Default: 4 + #[serde(rename = "highlight_affix_num_tokens", skip_serializing_if = "Option::is_none")] pub highlight_affix_num_tokens: Option, - /// The start tag used for the highlighted snippets. Default: `` - #[serde( - rename = "highlight_start_tag", - skip_serializing_if = "Option::is_none" - )] + /// The start tag used for the highlighted snippets. Default: `` + #[serde(rename = "highlight_start_tag", skip_serializing_if = "Option::is_none")] pub highlight_start_tag: Option, - /// The end tag used for the highlighted snippets. Default: `` + /// The end tag used for the highlighted snippets. Default: `` #[serde(rename = "highlight_end_tag", skip_serializing_if = "Option::is_none")] pub highlight_end_tag: Option, - /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 + /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 #[serde(rename = "snippet_threshold", skip_serializing_if = "Option::is_none")] pub snippet_threshold: Option, - /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 - #[serde( - rename = "drop_tokens_threshold", - skip_serializing_if = "Option::is_none" - )] + /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 + #[serde(rename = "drop_tokens_threshold", skip_serializing_if = "Option::is_none")] pub drop_tokens_threshold: Option, #[serde(rename = "drop_tokens_mode", skip_serializing_if = "Option::is_none")] pub drop_tokens_mode: Option, - /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 - #[serde( - rename = "typo_tokens_threshold", - skip_serializing_if = "Option::is_none" - )] + /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 + #[serde(rename = "typo_tokens_threshold", skip_serializing_if = "Option::is_none")] pub typo_tokens_threshold: Option, - /// Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. - #[serde( - rename = "enable_typos_for_alpha_numerical_tokens", - skip_serializing_if = "Option::is_none" - )] + /// Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + #[serde(rename = "enable_typos_for_alpha_numerical_tokens", skip_serializing_if = "Option::is_none")] pub enable_typos_for_alpha_numerical_tokens: Option, - /// Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false - #[serde( - rename = "filter_curated_hits", - skip_serializing_if = "Option::is_none" - )] + /// Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + #[serde(rename = "filter_curated_hits", skip_serializing_if = "Option::is_none")] pub filter_curated_hits: Option, - /// If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + /// If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true #[serde(rename = "enable_synonyms", skip_serializing_if = "Option::is_none")] pub enable_synonyms: Option, - /// Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). + /// Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). #[serde(rename = "enable_analytics", skip_serializing_if = "Option::is_none")] pub enable_analytics: Option, - /// Allow synonym resolution on word prefixes in the query. Default: false + /// Allow synonym resolution on word prefixes in the query. Default: false #[serde(rename = "synonym_prefix", skip_serializing_if = "Option::is_none")] pub synonym_prefix: Option, - /// Allow synonym resolution on typo-corrected words in the query. Default: 0 + /// Allow synonym resolution on typo-corrected words in the query. Default: 0 #[serde(rename = "synonym_num_typos", skip_serializing_if = "Option::is_none")] pub synonym_num_typos: Option, - /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "pinned_hits", skip_serializing_if = "Option::is_none")] pub pinned_hits: Option, - /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "hidden_hits", skip_serializing_if = "Option::is_none")] pub hidden_hits: Option, /// Comma separated list of tags to trigger the curations rules that match the tags. #[serde(rename = "override_tags", skip_serializing_if = "Option::is_none")] pub override_tags: Option, - /// A list of custom fields that must be highlighted even if you don't query for them + /// A list of custom fields that must be highlighted even if you don't query for them #[serde(rename = "highlight_fields", skip_serializing_if = "Option::is_none")] pub highlight_fields: Option, - /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same - #[serde( - rename = "pre_segmented_query", - skip_serializing_if = "Option::is_none" - )] + /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same + #[serde(rename = "pre_segmented_query", skip_serializing_if = "Option::is_none")] pub pre_segmented_query: Option, - /// Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. + /// Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. #[serde(rename = "preset", skip_serializing_if = "Option::is_none")] pub preset: Option, - /// If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false + /// If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false #[serde(rename = "enable_overrides", skip_serializing_if = "Option::is_none")] pub enable_overrides: Option, - /// Set this parameter to true to ensure that an exact match is ranked above the others - #[serde( - rename = "prioritize_exact_match", - skip_serializing_if = "Option::is_none" - )] + /// Set this parameter to true to ensure that an exact match is ranked above the others + #[serde(rename = "prioritize_exact_match", skip_serializing_if = "Option::is_none")] pub prioritize_exact_match: Option, - /// Make Typesense prioritize documents where the query words appear earlier in the text. - #[serde( - rename = "prioritize_token_position", - skip_serializing_if = "Option::is_none" - )] + /// Make Typesense prioritize documents where the query words appear earlier in the text. + #[serde(rename = "prioritize_token_position", skip_serializing_if = "Option::is_none")] pub prioritize_token_position: Option, - /// Make Typesense prioritize documents where the query words appear in more number of fields. - #[serde( - rename = "prioritize_num_matching_fields", - skip_serializing_if = "Option::is_none" - )] + /// Make Typesense prioritize documents where the query words appear in more number of fields. + #[serde(rename = "prioritize_num_matching_fields", skip_serializing_if = "Option::is_none")] pub prioritize_num_matching_fields: Option, - /// Make Typesense disable typos for numerical tokens. - #[serde( - rename = "enable_typos_for_numerical_tokens", - skip_serializing_if = "Option::is_none" - )] + /// Make Typesense disable typos for numerical tokens. + #[serde(rename = "enable_typos_for_numerical_tokens", skip_serializing_if = "Option::is_none")] pub enable_typos_for_numerical_tokens: Option, - /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). + /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). #[serde(rename = "exhaustive_search", skip_serializing_if = "Option::is_none")] pub exhaustive_search: Option, - /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. + /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. #[serde(rename = "search_cutoff_ms", skip_serializing_if = "Option::is_none")] pub search_cutoff_ms: Option, - /// Enable server side caching of search query results. By default, caching is disabled. + /// Enable server side caching of search query results. By default, caching is disabled. #[serde(rename = "use_cache", skip_serializing_if = "Option::is_none")] pub use_cache: Option, - /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. + /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. #[serde(rename = "cache_ttl", skip_serializing_if = "Option::is_none")] pub cache_ttl: Option, - /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_1typo", skip_serializing_if = "Option::is_none")] pub min_len_1typo: Option, - /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_2typo", skip_serializing_if = "Option::is_none")] pub min_len_2typo: Option, - /// Vector query expression for fetching documents \"closest\" to a given query/document vector. + /// Vector query expression for fetching documents \"closest\" to a given query/document vector. #[serde(rename = "vector_query", skip_serializing_if = "Option::is_none")] pub vector_query: Option, - /// Timeout (in milliseconds) for fetching remote embeddings. - #[serde( - rename = "remote_embedding_timeout_ms", - skip_serializing_if = "Option::is_none" - )] + /// Timeout (in milliseconds) for fetching remote embeddings. + #[serde(rename = "remote_embedding_timeout_ms", skip_serializing_if = "Option::is_none")] pub remote_embedding_timeout_ms: Option, - /// Number of times to retry fetching remote embeddings. - #[serde( - rename = "remote_embedding_num_tries", - skip_serializing_if = "Option::is_none" - )] + /// Number of times to retry fetching remote embeddings. + #[serde(rename = "remote_embedding_num_tries", skip_serializing_if = "Option::is_none")] pub remote_embedding_num_tries: Option, - /// Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). + /// Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). #[serde(rename = "facet_strategy", skip_serializing_if = "Option::is_none")] pub facet_strategy: Option, - /// Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. + /// Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. #[serde(rename = "stopwords", skip_serializing_if = "Option::is_none")] pub stopwords: Option, - /// Comma separated string of nested facet fields whose parent object should be returned in facet response. - #[serde( - rename = "facet_return_parent", - skip_serializing_if = "Option::is_none" - )] + /// Comma separated string of nested facet fields whose parent object should be returned in facet response. + #[serde(rename = "facet_return_parent", skip_serializing_if = "Option::is_none")] pub facet_return_parent: Option, - /// The base64 encoded audio file in 16 khz 16-bit WAV format. + /// The base64 encoded audio file in 16 khz 16-bit WAV format. #[serde(rename = "voice_query", skip_serializing_if = "Option::is_none")] pub voice_query: Option, - /// Enable conversational search. + /// Enable conversational search. #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] pub conversation: Option, - /// The Id of Conversation Model to be used. - #[serde( - rename = "conversation_model_id", - skip_serializing_if = "Option::is_none" - )] + /// The Id of Conversation Model to be used. + #[serde(rename = "conversation_model_id", skip_serializing_if = "Option::is_none")] pub conversation_model_id: Option, - /// The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + /// The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. #[serde(rename = "conversation_id", skip_serializing_if = "Option::is_none")] pub conversation_id: Option, - /// The collection to search in. + /// The collection to search in. #[serde(rename = "collection", skip_serializing_if = "Option::is_none")] pub collection: Option, /// A separate search API key for each search within a multi_search request - #[serde( - rename = "x-typesense-api-key", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "x-typesense-api-key", skip_serializing_if = "Option::is_none")] pub x_typesense_api_key: Option, - /// When true, computes both text match and vector distance scores for all matches in hybrid search. Documents found only through keyword search will get a vector distance score, and documents found only through vector search will get a text match score. - #[serde( - rename = "rerank_hybrid_matches", - skip_serializing_if = "Option::is_none" - )] + /// When true, computes both text match and vector distance scores for all matches in hybrid search. Documents found only through keyword search will get a vector distance score, and documents found only through vector search will get a text match score. + #[serde(rename = "rerank_hybrid_matches", skip_serializing_if = "Option::is_none")] pub rerank_hybrid_matches: Option, } impl MultiSearchCollectionParameters { - pub fn new() -> MultiSearchCollectionParameters { + pub fn new() -> MultiSearchCollectionParameters{ MultiSearchCollectionParameters { q: None, query_by: None, @@ -347,3 +290,4 @@ impl MultiSearchCollectionParameters { } } } + diff --git a/typesense_codegen/src/models/multi_search_parameters.rs b/typesense_codegen/src/models/multi_search_parameters.rs index 21b2db0..7602ca5 100644 --- a/typesense_codegen/src/models/multi_search_parameters.rs +++ b/typesense_codegen/src/models/multi_search_parameters.rs @@ -4,14 +4,14 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ use crate::models; use serde::{Deserialize, Serialize}; -/// MultiSearchParameters : Parameters for the multi search API. +/// MultiSearchParameters : Parameters for the multi search API. #[derive(bon::Builder)] #[builder(on(String, into))] #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] @@ -55,7 +55,7 @@ pub struct MultiSearchParameters { /// Facet values that are returned can now be filtered via this parameter. The matching facet text is also highlighted. For example, when faceting by `category`, you can set `facet_query=category:shoe` to return only facet values that contain the prefix \"shoe\". #[serde(rename = "facet_query", skip_serializing_if = "Option::is_none")] pub facet_query: Option, - /// The number of typographical errors (1 or 2) that would be tolerated. Default: 2 + /// The number of typographical errors (1 or 2) that would be tolerated. Default: 2 #[serde(rename = "num_typos", skip_serializing_if = "Option::is_none")] pub num_typos: Option, /// Results from this specific page number would be fetched. @@ -64,7 +64,7 @@ pub struct MultiSearchParameters { /// Number of results to fetch per page. Default: 10 #[serde(rename = "per_page", skip_serializing_if = "Option::is_none")] pub per_page: Option, - /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. + /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. #[serde(rename = "limit", skip_serializing_if = "Option::is_none")] pub limit: Option, /// Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. @@ -73,14 +73,11 @@ pub struct MultiSearchParameters { /// You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. #[serde(rename = "group_by", skip_serializing_if = "Option::is_none")] pub group_by: Option, - /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 + /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 #[serde(rename = "group_limit", skip_serializing_if = "Option::is_none")] pub group_limit: Option, - /// Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true - #[serde( - rename = "group_missing_values", - skip_serializing_if = "Option::is_none" - )] + /// Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true + #[serde(rename = "group_missing_values", skip_serializing_if = "Option::is_none")] pub group_missing_values: Option, /// List of fields from the document to include in the search result #[serde(rename = "include_fields", skip_serializing_if = "Option::is_none")] @@ -89,180 +86,132 @@ pub struct MultiSearchParameters { #[serde(rename = "exclude_fields", skip_serializing_if = "Option::is_none")] pub exclude_fields: Option, /// List of fields which should be highlighted fully without snippeting - #[serde( - rename = "highlight_full_fields", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "highlight_full_fields", skip_serializing_if = "Option::is_none")] pub highlight_full_fields: Option, - /// The number of tokens that should surround the highlighted text on each side. Default: 4 - #[serde( - rename = "highlight_affix_num_tokens", - skip_serializing_if = "Option::is_none" - )] + /// The number of tokens that should surround the highlighted text on each side. Default: 4 + #[serde(rename = "highlight_affix_num_tokens", skip_serializing_if = "Option::is_none")] pub highlight_affix_num_tokens: Option, - /// The start tag used for the highlighted snippets. Default: `` - #[serde( - rename = "highlight_start_tag", - skip_serializing_if = "Option::is_none" - )] + /// The start tag used for the highlighted snippets. Default: `` + #[serde(rename = "highlight_start_tag", skip_serializing_if = "Option::is_none")] pub highlight_start_tag: Option, - /// The end tag used for the highlighted snippets. Default: `` + /// The end tag used for the highlighted snippets. Default: `` #[serde(rename = "highlight_end_tag", skip_serializing_if = "Option::is_none")] pub highlight_end_tag: Option, - /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 + /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 #[serde(rename = "snippet_threshold", skip_serializing_if = "Option::is_none")] pub snippet_threshold: Option, - /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 - #[serde( - rename = "drop_tokens_threshold", - skip_serializing_if = "Option::is_none" - )] + /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 + #[serde(rename = "drop_tokens_threshold", skip_serializing_if = "Option::is_none")] pub drop_tokens_threshold: Option, #[serde(rename = "drop_tokens_mode", skip_serializing_if = "Option::is_none")] pub drop_tokens_mode: Option, - /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 - #[serde( - rename = "typo_tokens_threshold", - skip_serializing_if = "Option::is_none" - )] + /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 + #[serde(rename = "typo_tokens_threshold", skip_serializing_if = "Option::is_none")] pub typo_tokens_threshold: Option, - /// Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. - #[serde( - rename = "enable_typos_for_alpha_numerical_tokens", - skip_serializing_if = "Option::is_none" - )] + /// Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + #[serde(rename = "enable_typos_for_alpha_numerical_tokens", skip_serializing_if = "Option::is_none")] pub enable_typos_for_alpha_numerical_tokens: Option, - /// Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false - #[serde( - rename = "filter_curated_hits", - skip_serializing_if = "Option::is_none" - )] + /// Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + #[serde(rename = "filter_curated_hits", skip_serializing_if = "Option::is_none")] pub filter_curated_hits: Option, - /// If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + /// If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true #[serde(rename = "enable_synonyms", skip_serializing_if = "Option::is_none")] pub enable_synonyms: Option, - /// Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). + /// Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). #[serde(rename = "enable_analytics", skip_serializing_if = "Option::is_none")] pub enable_analytics: Option, - /// Allow synonym resolution on word prefixes in the query. Default: false + /// Allow synonym resolution on word prefixes in the query. Default: false #[serde(rename = "synonym_prefix", skip_serializing_if = "Option::is_none")] pub synonym_prefix: Option, - /// Allow synonym resolution on typo-corrected words in the query. Default: 0 + /// Allow synonym resolution on typo-corrected words in the query. Default: 0 #[serde(rename = "synonym_num_typos", skip_serializing_if = "Option::is_none")] pub synonym_num_typos: Option, - /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "pinned_hits", skip_serializing_if = "Option::is_none")] pub pinned_hits: Option, - /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "hidden_hits", skip_serializing_if = "Option::is_none")] pub hidden_hits: Option, /// Comma separated list of tags to trigger the curations rules that match the tags. #[serde(rename = "override_tags", skip_serializing_if = "Option::is_none")] pub override_tags: Option, - /// A list of custom fields that must be highlighted even if you don't query for them + /// A list of custom fields that must be highlighted even if you don't query for them #[serde(rename = "highlight_fields", skip_serializing_if = "Option::is_none")] pub highlight_fields: Option, - /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same - #[serde( - rename = "pre_segmented_query", - skip_serializing_if = "Option::is_none" - )] + /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same + #[serde(rename = "pre_segmented_query", skip_serializing_if = "Option::is_none")] pub pre_segmented_query: Option, - /// Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. + /// Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. #[serde(rename = "preset", skip_serializing_if = "Option::is_none")] pub preset: Option, - /// If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false + /// If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false #[serde(rename = "enable_overrides", skip_serializing_if = "Option::is_none")] pub enable_overrides: Option, - /// Set this parameter to true to ensure that an exact match is ranked above the others - #[serde( - rename = "prioritize_exact_match", - skip_serializing_if = "Option::is_none" - )] + /// Set this parameter to true to ensure that an exact match is ranked above the others + #[serde(rename = "prioritize_exact_match", skip_serializing_if = "Option::is_none")] pub prioritize_exact_match: Option, - /// Make Typesense prioritize documents where the query words appear earlier in the text. - #[serde( - rename = "prioritize_token_position", - skip_serializing_if = "Option::is_none" - )] + /// Make Typesense prioritize documents where the query words appear earlier in the text. + #[serde(rename = "prioritize_token_position", skip_serializing_if = "Option::is_none")] pub prioritize_token_position: Option, - /// Make Typesense prioritize documents where the query words appear in more number of fields. - #[serde( - rename = "prioritize_num_matching_fields", - skip_serializing_if = "Option::is_none" - )] + /// Make Typesense prioritize documents where the query words appear in more number of fields. + #[serde(rename = "prioritize_num_matching_fields", skip_serializing_if = "Option::is_none")] pub prioritize_num_matching_fields: Option, - /// Make Typesense disable typos for numerical tokens. - #[serde( - rename = "enable_typos_for_numerical_tokens", - skip_serializing_if = "Option::is_none" - )] + /// Make Typesense disable typos for numerical tokens. + #[serde(rename = "enable_typos_for_numerical_tokens", skip_serializing_if = "Option::is_none")] pub enable_typos_for_numerical_tokens: Option, - /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). + /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). #[serde(rename = "exhaustive_search", skip_serializing_if = "Option::is_none")] pub exhaustive_search: Option, - /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. + /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. #[serde(rename = "search_cutoff_ms", skip_serializing_if = "Option::is_none")] pub search_cutoff_ms: Option, - /// Enable server side caching of search query results. By default, caching is disabled. + /// Enable server side caching of search query results. By default, caching is disabled. #[serde(rename = "use_cache", skip_serializing_if = "Option::is_none")] pub use_cache: Option, - /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. + /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. #[serde(rename = "cache_ttl", skip_serializing_if = "Option::is_none")] pub cache_ttl: Option, - /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_1typo", skip_serializing_if = "Option::is_none")] pub min_len_1typo: Option, - /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_2typo", skip_serializing_if = "Option::is_none")] pub min_len_2typo: Option, - /// Vector query expression for fetching documents \"closest\" to a given query/document vector. + /// Vector query expression for fetching documents \"closest\" to a given query/document vector. #[serde(rename = "vector_query", skip_serializing_if = "Option::is_none")] pub vector_query: Option, - /// Timeout (in milliseconds) for fetching remote embeddings. - #[serde( - rename = "remote_embedding_timeout_ms", - skip_serializing_if = "Option::is_none" - )] + /// Timeout (in milliseconds) for fetching remote embeddings. + #[serde(rename = "remote_embedding_timeout_ms", skip_serializing_if = "Option::is_none")] pub remote_embedding_timeout_ms: Option, - /// Number of times to retry fetching remote embeddings. - #[serde( - rename = "remote_embedding_num_tries", - skip_serializing_if = "Option::is_none" - )] + /// Number of times to retry fetching remote embeddings. + #[serde(rename = "remote_embedding_num_tries", skip_serializing_if = "Option::is_none")] pub remote_embedding_num_tries: Option, - /// Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). + /// Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). #[serde(rename = "facet_strategy", skip_serializing_if = "Option::is_none")] pub facet_strategy: Option, - /// Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. + /// Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. #[serde(rename = "stopwords", skip_serializing_if = "Option::is_none")] pub stopwords: Option, - /// Comma separated string of nested facet fields whose parent object should be returned in facet response. - #[serde( - rename = "facet_return_parent", - skip_serializing_if = "Option::is_none" - )] + /// Comma separated string of nested facet fields whose parent object should be returned in facet response. + #[serde(rename = "facet_return_parent", skip_serializing_if = "Option::is_none")] pub facet_return_parent: Option, - /// The base64 encoded audio file in 16 khz 16-bit WAV format. + /// The base64 encoded audio file in 16 khz 16-bit WAV format. #[serde(rename = "voice_query", skip_serializing_if = "Option::is_none")] pub voice_query: Option, - /// Enable conversational search. + /// Enable conversational search. #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] pub conversation: Option, - /// The Id of Conversation Model to be used. - #[serde( - rename = "conversation_model_id", - skip_serializing_if = "Option::is_none" - )] + /// The Id of Conversation Model to be used. + #[serde(rename = "conversation_model_id", skip_serializing_if = "Option::is_none")] pub conversation_model_id: Option, - /// The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + /// The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. #[serde(rename = "conversation_id", skip_serializing_if = "Option::is_none")] pub conversation_id: Option, } impl MultiSearchParameters { - /// Parameters for the multi search API. - pub fn new() -> MultiSearchParameters { + /// Parameters for the multi search API. + pub fn new() -> MultiSearchParameters{ MultiSearchParameters { q: None, query_by: None, @@ -331,3 +280,4 @@ impl MultiSearchParameters { } } } + diff --git a/typesense_codegen/src/models/multi_search_result.rs b/typesense_codegen/src/models/multi_search_result.rs index bef6780..d3ffd67 100644 --- a/typesense_codegen/src/models/multi_search_result.rs +++ b/typesense_codegen/src/models/multi_search_result.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -20,10 +20,11 @@ pub struct MultiSearchResult { } impl MultiSearchResult { - pub fn new(results: Vec>) -> MultiSearchResult { + pub fn new(results: Vec>) -> MultiSearchResult{ MultiSearchResult { results, conversation: None, } } } + diff --git a/typesense_codegen/src/models/multi_search_result_item.rs b/typesense_codegen/src/models/multi_search_result_item.rs index 64794c8..6f4c8bc 100644 --- a/typesense_codegen/src/models/multi_search_result_item.rs +++ b/typesense_codegen/src/models/multi_search_result_item.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -42,10 +42,7 @@ pub struct MultiSearchResultItem { #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] pub conversation: Option>, /// Returned only for union query response. - #[serde( - rename = "union_request_params", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "union_request_params", skip_serializing_if = "Option::is_none")] pub union_request_params: Option>, /// HTTP error code #[serde(rename = "code", skip_serializing_if = "Option::is_none")] @@ -56,7 +53,7 @@ pub struct MultiSearchResultItem { } impl MultiSearchResultItem { - pub fn new() -> MultiSearchResultItem { + pub fn new() -> MultiSearchResultItem{ MultiSearchResultItem { facet_counts: None, found: None, @@ -75,3 +72,4 @@ impl MultiSearchResultItem { } } } + diff --git a/typesense_codegen/src/models/multi_search_searches_parameter.rs b/typesense_codegen/src/models/multi_search_searches_parameter.rs index 36cd062..f8e69d3 100644 --- a/typesense_codegen/src/models/multi_search_searches_parameter.rs +++ b/typesense_codegen/src/models/multi_search_searches_parameter.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -21,12 +21,11 @@ pub struct MultiSearchSearchesParameter { } impl MultiSearchSearchesParameter { - pub fn new( - searches: Vec, - ) -> MultiSearchSearchesParameter { + pub fn new(searches: Vec) -> MultiSearchSearchesParameter{ MultiSearchSearchesParameter { union: None, searches, } } } + diff --git a/typesense_codegen/src/models/nl_search_model_base.rs b/typesense_codegen/src/models/nl_search_model_base.rs index 5bb066f..4e08735 100644 --- a/typesense_codegen/src/models/nl_search_model_base.rs +++ b/typesense_codegen/src/models/nl_search_model_base.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -70,7 +70,7 @@ pub struct NlSearchModelBase { } impl NlSearchModelBase { - pub fn new() -> NlSearchModelBase { + pub fn new() -> NlSearchModelBase{ NlSearchModelBase { model_name: None, api_key: None, @@ -93,3 +93,4 @@ impl NlSearchModelBase { } } } + diff --git a/typesense_codegen/src/models/nl_search_model_create_schema.rs b/typesense_codegen/src/models/nl_search_model_create_schema.rs index 34cb2d4..4259d0a 100644 --- a/typesense_codegen/src/models/nl_search_model_create_schema.rs +++ b/typesense_codegen/src/models/nl_search_model_create_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -73,7 +73,7 @@ pub struct NlSearchModelCreateSchema { } impl NlSearchModelCreateSchema { - pub fn new() -> NlSearchModelCreateSchema { + pub fn new() -> NlSearchModelCreateSchema{ NlSearchModelCreateSchema { model_name: None, api_key: None, @@ -97,3 +97,4 @@ impl NlSearchModelCreateSchema { } } } + diff --git a/typesense_codegen/src/models/nl_search_model_delete_schema.rs b/typesense_codegen/src/models/nl_search_model_delete_schema.rs index f31df7d..20dbf83 100644 --- a/typesense_codegen/src/models/nl_search_model_delete_schema.rs +++ b/typesense_codegen/src/models/nl_search_model_delete_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,7 +19,10 @@ pub struct NlSearchModelDeleteSchema { } impl NlSearchModelDeleteSchema { - pub fn new(id: String) -> NlSearchModelDeleteSchema { - NlSearchModelDeleteSchema { id } + pub fn new(id: String) -> NlSearchModelDeleteSchema{ + NlSearchModelDeleteSchema { + id, + } } } + diff --git a/typesense_codegen/src/models/nl_search_model_schema.rs b/typesense_codegen/src/models/nl_search_model_schema.rs index b2066e0..9a24637 100644 --- a/typesense_codegen/src/models/nl_search_model_schema.rs +++ b/typesense_codegen/src/models/nl_search_model_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -73,7 +73,7 @@ pub struct NlSearchModelSchema { } impl NlSearchModelSchema { - pub fn new(id: String) -> NlSearchModelSchema { + pub fn new(id: String) -> NlSearchModelSchema{ NlSearchModelSchema { model_name: None, api_key: None, @@ -97,3 +97,4 @@ impl NlSearchModelSchema { } } } + diff --git a/typesense_codegen/src/models/preset_delete_schema.rs b/typesense_codegen/src/models/preset_delete_schema.rs index 5203796..77294d0 100644 --- a/typesense_codegen/src/models/preset_delete_schema.rs +++ b/typesense_codegen/src/models/preset_delete_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,7 +18,10 @@ pub struct PresetDeleteSchema { } impl PresetDeleteSchema { - pub fn new(name: String) -> PresetDeleteSchema { - PresetDeleteSchema { name } + pub fn new(name: String) -> PresetDeleteSchema{ + PresetDeleteSchema { + name, + } } } + diff --git a/typesense_codegen/src/models/preset_schema.rs b/typesense_codegen/src/models/preset_schema.rs index c12caca..8c9352c 100644 --- a/typesense_codegen/src/models/preset_schema.rs +++ b/typesense_codegen/src/models/preset_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -20,10 +20,11 @@ pub struct PresetSchema { } impl PresetSchema { - pub fn new(value: models::PresetUpsertSchemaValue, name: String) -> PresetSchema { + pub fn new(value: models::PresetUpsertSchemaValue, name: String) -> PresetSchema{ PresetSchema { value: Box::new(value), name, } } } + diff --git a/typesense_codegen/src/models/preset_upsert_schema.rs b/typesense_codegen/src/models/preset_upsert_schema.rs index 92eff0d..92203f8 100644 --- a/typesense_codegen/src/models/preset_upsert_schema.rs +++ b/typesense_codegen/src/models/preset_upsert_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,9 +18,10 @@ pub struct PresetUpsertSchema { } impl PresetUpsertSchema { - pub fn new(value: models::PresetUpsertSchemaValue) -> PresetUpsertSchema { + pub fn new(value: models::PresetUpsertSchemaValue) -> PresetUpsertSchema{ PresetUpsertSchema { value: Box::new(value), } } } + diff --git a/typesense_codegen/src/models/preset_upsert_schema_value.rs b/typesense_codegen/src/models/preset_upsert_schema_value.rs index 43335aa..f6a502f 100644 --- a/typesense_codegen/src/models/preset_upsert_schema_value.rs +++ b/typesense_codegen/src/models/preset_upsert_schema_value.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -23,3 +23,4 @@ impl Default for PresetUpsertSchemaValue { Self::SearchParameters(Default::default()) } } + diff --git a/typesense_codegen/src/models/presets_retrieve_schema.rs b/typesense_codegen/src/models/presets_retrieve_schema.rs index e64ecf1..e13bc93 100644 --- a/typesense_codegen/src/models/presets_retrieve_schema.rs +++ b/typesense_codegen/src/models/presets_retrieve_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,7 +18,10 @@ pub struct PresetsRetrieveSchema { } impl PresetsRetrieveSchema { - pub fn new(presets: Vec) -> PresetsRetrieveSchema { - PresetsRetrieveSchema { presets } + pub fn new(presets: Vec) -> PresetsRetrieveSchema{ + PresetsRetrieveSchema { + presets, + } } } + diff --git a/typesense_codegen/src/models/schema_change_status.rs b/typesense_codegen/src/models/schema_change_status.rs index 22bb410..f051a9b 100644 --- a/typesense_codegen/src/models/schema_change_status.rs +++ b/typesense_codegen/src/models/schema_change_status.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -25,7 +25,7 @@ pub struct SchemaChangeStatus { } impl SchemaChangeStatus { - pub fn new() -> SchemaChangeStatus { + pub fn new() -> SchemaChangeStatus{ SchemaChangeStatus { collection: None, validated_docs: None, @@ -33,3 +33,4 @@ impl SchemaChangeStatus { } } } + diff --git a/typesense_codegen/src/models/search_grouped_hit.rs b/typesense_codegen/src/models/search_grouped_hit.rs index 434b8fc..73d9292 100644 --- a/typesense_codegen/src/models/search_grouped_hit.rs +++ b/typesense_codegen/src/models/search_grouped_hit.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -23,10 +23,7 @@ pub struct SearchGroupedHit { } impl SearchGroupedHit { - pub fn new( - group_key: Vec, - hits: Vec>, - ) -> SearchGroupedHit { + pub fn new(group_key: Vec, hits: Vec>) -> SearchGroupedHit{ SearchGroupedHit { found: None, group_key, @@ -34,3 +31,4 @@ impl SearchGroupedHit { } } } + diff --git a/typesense_codegen/src/models/search_highlight.rs b/typesense_codegen/src/models/search_highlight.rs index c45afcc..0b5101d 100644 --- a/typesense_codegen/src/models/search_highlight.rs +++ b/typesense_codegen/src/models/search_highlight.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -35,7 +35,7 @@ pub struct SearchHighlight { } impl SearchHighlight { - pub fn new() -> SearchHighlight { + pub fn new() -> SearchHighlight{ SearchHighlight { field: None, snippet: None, @@ -47,3 +47,4 @@ impl SearchHighlight { } } } + diff --git a/typesense_codegen/src/models/search_override.rs b/typesense_codegen/src/models/search_override.rs index b1f8353..0740e2d 100644 --- a/typesense_codegen/src/models/search_override.rs +++ b/typesense_codegen/src/models/search_override.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -21,37 +21,31 @@ pub struct SearchOverride { /// List of document `id`s that should be excluded from the search results. #[serde(rename = "excludes", skip_serializing_if = "Option::is_none")] pub excludes: Option>, - /// A filter by clause that is applied to any search query that matches the override rule. + /// A filter by clause that is applied to any search query that matches the override rule. #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] pub filter_by: Option, - /// Indicates whether search query tokens that exist in the override's rule should be removed from the search query. - #[serde( - rename = "remove_matched_tokens", - skip_serializing_if = "Option::is_none" - )] + /// Indicates whether search query tokens that exist in the override's rule should be removed from the search query. + #[serde(rename = "remove_matched_tokens", skip_serializing_if = "Option::is_none")] pub remove_matched_tokens: Option, - /// Return a custom JSON object in the Search API response, when this rule is triggered. This can can be used to display a pre-defined message (eg: a promotion banner) on the front-end when a particular rule is triggered. + /// Return a custom JSON object in the Search API response, when this rule is triggered. This can can be used to display a pre-defined message (eg: a promotion banner) on the front-end when a particular rule is triggered. #[serde(rename = "metadata", skip_serializing_if = "Option::is_none")] pub metadata: Option, - /// A sort by clause that is applied to any search query that matches the override rule. + /// A sort by clause that is applied to any search query that matches the override rule. #[serde(rename = "sort_by", skip_serializing_if = "Option::is_none")] pub sort_by: Option, - /// Replaces the current search query with this value, when the search query matches the override rule. + /// Replaces the current search query with this value, when the search query matches the override rule. #[serde(rename = "replace_query", skip_serializing_if = "Option::is_none")] pub replace_query: Option, - /// When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. - #[serde( - rename = "filter_curated_hits", - skip_serializing_if = "Option::is_none" - )] + /// When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. + #[serde(rename = "filter_curated_hits", skip_serializing_if = "Option::is_none")] pub filter_curated_hits: Option, - /// A Unix timestamp that indicates the date/time from which the override will be active. You can use this to create override rules that start applying from a future point in time. + /// A Unix timestamp that indicates the date/time from which the override will be active. You can use this to create override rules that start applying from a future point in time. #[serde(rename = "effective_from_ts", skip_serializing_if = "Option::is_none")] pub effective_from_ts: Option, - /// A Unix timestamp that indicates the date/time until which the override will be active. You can use this to create override rules that stop applying after a period of time. + /// A Unix timestamp that indicates the date/time until which the override will be active. You can use this to create override rules that stop applying after a period of time. #[serde(rename = "effective_to_ts", skip_serializing_if = "Option::is_none")] pub effective_to_ts: Option, - /// When set to true, override processing will stop at the first matching rule. When set to false override processing will continue and multiple override actions will be triggered in sequence. Overrides are processed in the lexical sort order of their id field. Default: true. + /// When set to true, override processing will stop at the first matching rule. When set to false override processing will continue and multiple override actions will be triggered in sequence. Overrides are processed in the lexical sort order of their id field. Default: true. #[serde(rename = "stop_processing", skip_serializing_if = "Option::is_none")] pub stop_processing: Option, #[serde(rename = "id")] @@ -59,7 +53,7 @@ pub struct SearchOverride { } impl SearchOverride { - pub fn new(rule: models::SearchOverrideRule, id: String) -> SearchOverride { + pub fn new(rule: models::SearchOverrideRule, id: String) -> SearchOverride{ SearchOverride { rule: Box::new(rule), includes: None, @@ -77,3 +71,4 @@ impl SearchOverride { } } } + diff --git a/typesense_codegen/src/models/search_override_delete_response.rs b/typesense_codegen/src/models/search_override_delete_response.rs index 3949320..23bc8f4 100644 --- a/typesense_codegen/src/models/search_override_delete_response.rs +++ b/typesense_codegen/src/models/search_override_delete_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,7 +19,10 @@ pub struct SearchOverrideDeleteResponse { } impl SearchOverrideDeleteResponse { - pub fn new(id: String) -> SearchOverrideDeleteResponse { - SearchOverrideDeleteResponse { id } + pub fn new(id: String) -> SearchOverrideDeleteResponse{ + SearchOverrideDeleteResponse { + id, + } } } + diff --git a/typesense_codegen/src/models/search_override_exclude.rs b/typesense_codegen/src/models/search_override_exclude.rs index 58b01b9..e6c0dee 100644 --- a/typesense_codegen/src/models/search_override_exclude.rs +++ b/typesense_codegen/src/models/search_override_exclude.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,7 +19,10 @@ pub struct SearchOverrideExclude { } impl SearchOverrideExclude { - pub fn new(id: String) -> SearchOverrideExclude { - SearchOverrideExclude { id } + pub fn new(id: String) -> SearchOverrideExclude{ + SearchOverrideExclude { + id, + } } } + diff --git a/typesense_codegen/src/models/search_override_include.rs b/typesense_codegen/src/models/search_override_include.rs index 7756358..5344b55 100644 --- a/typesense_codegen/src/models/search_override_include.rs +++ b/typesense_codegen/src/models/search_override_include.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -22,7 +22,11 @@ pub struct SearchOverrideInclude { } impl SearchOverrideInclude { - pub fn new(id: String, position: i32) -> SearchOverrideInclude { - SearchOverrideInclude { id, position } + pub fn new(id: String, position: i32) -> SearchOverrideInclude{ + SearchOverrideInclude { + id, + position, + } } } + diff --git a/typesense_codegen/src/models/search_override_rule.rs b/typesense_codegen/src/models/search_override_rule.rs index de9ebf5..3ce37a4 100644 --- a/typesense_codegen/src/models/search_override_rule.rs +++ b/typesense_codegen/src/models/search_override_rule.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,16 +19,16 @@ pub struct SearchOverrideRule { /// Indicates what search queries should be overridden #[serde(rename = "query", skip_serializing_if = "Option::is_none")] pub query: Option, - /// Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. + /// Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. #[serde(rename = "match", skip_serializing_if = "Option::is_none")] pub r#match: Option, - /// Indicates that the override should apply when the filter_by parameter in a search query exactly matches the string specified here (including backticks, spaces, brackets, etc). + /// Indicates that the override should apply when the filter_by parameter in a search query exactly matches the string specified here (including backticks, spaces, brackets, etc). #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] pub filter_by: Option, } impl SearchOverrideRule { - pub fn new() -> SearchOverrideRule { + pub fn new() -> SearchOverrideRule{ SearchOverrideRule { tags: None, query: None, @@ -37,7 +37,7 @@ impl SearchOverrideRule { } } } -/// Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. +/// Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum Match { #[serde(rename = "exact")] @@ -51,3 +51,4 @@ impl Default for Match { Self::Exact } } + diff --git a/typesense_codegen/src/models/search_override_schema.rs b/typesense_codegen/src/models/search_override_schema.rs index 1b0eede..8dfdd8c 100644 --- a/typesense_codegen/src/models/search_override_schema.rs +++ b/typesense_codegen/src/models/search_override_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -21,43 +21,37 @@ pub struct SearchOverrideSchema { /// List of document `id`s that should be excluded from the search results. #[serde(rename = "excludes", skip_serializing_if = "Option::is_none")] pub excludes: Option>, - /// A filter by clause that is applied to any search query that matches the override rule. + /// A filter by clause that is applied to any search query that matches the override rule. #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] pub filter_by: Option, - /// Indicates whether search query tokens that exist in the override's rule should be removed from the search query. - #[serde( - rename = "remove_matched_tokens", - skip_serializing_if = "Option::is_none" - )] + /// Indicates whether search query tokens that exist in the override's rule should be removed from the search query. + #[serde(rename = "remove_matched_tokens", skip_serializing_if = "Option::is_none")] pub remove_matched_tokens: Option, - /// Return a custom JSON object in the Search API response, when this rule is triggered. This can can be used to display a pre-defined message (eg: a promotion banner) on the front-end when a particular rule is triggered. + /// Return a custom JSON object in the Search API response, when this rule is triggered. This can can be used to display a pre-defined message (eg: a promotion banner) on the front-end when a particular rule is triggered. #[serde(rename = "metadata", skip_serializing_if = "Option::is_none")] pub metadata: Option, - /// A sort by clause that is applied to any search query that matches the override rule. + /// A sort by clause that is applied to any search query that matches the override rule. #[serde(rename = "sort_by", skip_serializing_if = "Option::is_none")] pub sort_by: Option, - /// Replaces the current search query with this value, when the search query matches the override rule. + /// Replaces the current search query with this value, when the search query matches the override rule. #[serde(rename = "replace_query", skip_serializing_if = "Option::is_none")] pub replace_query: Option, - /// When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. - #[serde( - rename = "filter_curated_hits", - skip_serializing_if = "Option::is_none" - )] + /// When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. + #[serde(rename = "filter_curated_hits", skip_serializing_if = "Option::is_none")] pub filter_curated_hits: Option, - /// A Unix timestamp that indicates the date/time from which the override will be active. You can use this to create override rules that start applying from a future point in time. + /// A Unix timestamp that indicates the date/time from which the override will be active. You can use this to create override rules that start applying from a future point in time. #[serde(rename = "effective_from_ts", skip_serializing_if = "Option::is_none")] pub effective_from_ts: Option, - /// A Unix timestamp that indicates the date/time until which the override will be active. You can use this to create override rules that stop applying after a period of time. + /// A Unix timestamp that indicates the date/time until which the override will be active. You can use this to create override rules that stop applying after a period of time. #[serde(rename = "effective_to_ts", skip_serializing_if = "Option::is_none")] pub effective_to_ts: Option, - /// When set to true, override processing will stop at the first matching rule. When set to false override processing will continue and multiple override actions will be triggered in sequence. Overrides are processed in the lexical sort order of their id field. Default: true. + /// When set to true, override processing will stop at the first matching rule. When set to false override processing will continue and multiple override actions will be triggered in sequence. Overrides are processed in the lexical sort order of their id field. Default: true. #[serde(rename = "stop_processing", skip_serializing_if = "Option::is_none")] pub stop_processing: Option, } impl SearchOverrideSchema { - pub fn new(rule: models::SearchOverrideRule) -> SearchOverrideSchema { + pub fn new(rule: models::SearchOverrideRule) -> SearchOverrideSchema{ SearchOverrideSchema { rule: Box::new(rule), includes: None, @@ -74,3 +68,4 @@ impl SearchOverrideSchema { } } } + diff --git a/typesense_codegen/src/models/search_overrides_response.rs b/typesense_codegen/src/models/search_overrides_response.rs index fd8aba3..eaef52b 100644 --- a/typesense_codegen/src/models/search_overrides_response.rs +++ b/typesense_codegen/src/models/search_overrides_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,7 +18,10 @@ pub struct SearchOverridesResponse { } impl SearchOverridesResponse { - pub fn new(overrides: Vec) -> SearchOverridesResponse { - SearchOverridesResponse { overrides } + pub fn new(overrides: Vec) -> SearchOverridesResponse{ + SearchOverridesResponse { + overrides, + } } } + diff --git a/typesense_codegen/src/models/search_parameters.rs b/typesense_codegen/src/models/search_parameters.rs index 860beff..d1f8f89 100644 --- a/typesense_codegen/src/models/search_parameters.rs +++ b/typesense_codegen/src/models/search_parameters.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -49,10 +49,7 @@ pub struct SearchParameters { #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] pub filter_by: Option, /// Controls the number of similar words that Typesense considers during fuzzy search on filter_by values. Useful for controlling prefix matches like company_name:Acm*. - #[serde( - rename = "max_filter_by_candidates", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "max_filter_by_candidates", skip_serializing_if = "Option::is_none")] pub max_filter_by_candidates: Option, /// A list of numerical fields and their corresponding sort orders that will be used for ordering your results. Up to 3 sort fields can be specified. The text similarity score is exposed as a special `_text_match` field that you can use in the list of sorting fields. If no `sort_by` parameter is specified, results are sorted by `_text_match:desc,default_sorting_field:desc` #[serde(rename = "sort_by", skip_serializing_if = "Option::is_none")] @@ -66,7 +63,7 @@ pub struct SearchParameters { /// Facet values that are returned can now be filtered via this parameter. The matching facet text is also highlighted. For example, when faceting by `category`, you can set `facet_query=category:shoe` to return only facet values that contain the prefix \"shoe\". #[serde(rename = "facet_query", skip_serializing_if = "Option::is_none")] pub facet_query: Option, - /// The number of typographical errors (1 or 2) that would be tolerated. Default: 2 + /// The number of typographical errors (1 or 2) that would be tolerated. Default: 2 #[serde(rename = "num_typos", skip_serializing_if = "Option::is_none")] pub num_typos: Option, /// Results from this specific page number would be fetched. @@ -75,7 +72,7 @@ pub struct SearchParameters { /// Number of results to fetch per page. Default: 10 #[serde(rename = "per_page", skip_serializing_if = "Option::is_none")] pub per_page: Option, - /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. + /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. #[serde(rename = "limit", skip_serializing_if = "Option::is_none")] pub limit: Option, /// Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. @@ -84,14 +81,11 @@ pub struct SearchParameters { /// You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. #[serde(rename = "group_by", skip_serializing_if = "Option::is_none")] pub group_by: Option, - /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 + /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 #[serde(rename = "group_limit", skip_serializing_if = "Option::is_none")] pub group_limit: Option, - /// Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true - #[serde( - rename = "group_missing_values", - skip_serializing_if = "Option::is_none" - )] + /// Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true + #[serde(rename = "group_missing_values", skip_serializing_if = "Option::is_none")] pub group_missing_values: Option, /// List of fields from the document to include in the search result #[serde(rename = "include_fields", skip_serializing_if = "Option::is_none")] @@ -100,194 +94,143 @@ pub struct SearchParameters { #[serde(rename = "exclude_fields", skip_serializing_if = "Option::is_none")] pub exclude_fields: Option, /// List of fields which should be highlighted fully without snippeting - #[serde( - rename = "highlight_full_fields", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "highlight_full_fields", skip_serializing_if = "Option::is_none")] pub highlight_full_fields: Option, - /// The number of tokens that should surround the highlighted text on each side. Default: 4 - #[serde( - rename = "highlight_affix_num_tokens", - skip_serializing_if = "Option::is_none" - )] + /// The number of tokens that should surround the highlighted text on each side. Default: 4 + #[serde(rename = "highlight_affix_num_tokens", skip_serializing_if = "Option::is_none")] pub highlight_affix_num_tokens: Option, - /// The start tag used for the highlighted snippets. Default: `` - #[serde( - rename = "highlight_start_tag", - skip_serializing_if = "Option::is_none" - )] + /// The start tag used for the highlighted snippets. Default: `` + #[serde(rename = "highlight_start_tag", skip_serializing_if = "Option::is_none")] pub highlight_start_tag: Option, - /// The end tag used for the highlighted snippets. Default: `` + /// The end tag used for the highlighted snippets. Default: `` #[serde(rename = "highlight_end_tag", skip_serializing_if = "Option::is_none")] pub highlight_end_tag: Option, - /// Flag for enabling/disabling the deprecated, old highlight structure in the response. Default: true - #[serde( - rename = "enable_highlight_v1", - skip_serializing_if = "Option::is_none" - )] + /// Flag for enabling/disabling the deprecated, old highlight structure in the response. Default: true + #[serde(rename = "enable_highlight_v1", skip_serializing_if = "Option::is_none")] pub enable_highlight_v1: Option, - /// Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). + /// Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). #[serde(rename = "enable_analytics", skip_serializing_if = "Option::is_none")] pub enable_analytics: Option, - /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 + /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 #[serde(rename = "snippet_threshold", skip_serializing_if = "Option::is_none")] pub snippet_threshold: Option, /// List of synonym set names to associate with this search query #[serde(rename = "synonym_sets", skip_serializing_if = "Option::is_none")] pub synonym_sets: Option, - /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 - #[serde( - rename = "drop_tokens_threshold", - skip_serializing_if = "Option::is_none" - )] + /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 + #[serde(rename = "drop_tokens_threshold", skip_serializing_if = "Option::is_none")] pub drop_tokens_threshold: Option, #[serde(rename = "drop_tokens_mode", skip_serializing_if = "Option::is_none")] pub drop_tokens_mode: Option, - /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 - #[serde( - rename = "typo_tokens_threshold", - skip_serializing_if = "Option::is_none" - )] + /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 + #[serde(rename = "typo_tokens_threshold", skip_serializing_if = "Option::is_none")] pub typo_tokens_threshold: Option, - /// Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. - #[serde( - rename = "enable_typos_for_alpha_numerical_tokens", - skip_serializing_if = "Option::is_none" - )] + /// Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + #[serde(rename = "enable_typos_for_alpha_numerical_tokens", skip_serializing_if = "Option::is_none")] pub enable_typos_for_alpha_numerical_tokens: Option, - /// Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false - #[serde( - rename = "filter_curated_hits", - skip_serializing_if = "Option::is_none" - )] + /// Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + #[serde(rename = "filter_curated_hits", skip_serializing_if = "Option::is_none")] pub filter_curated_hits: Option, - /// If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + /// If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true #[serde(rename = "enable_synonyms", skip_serializing_if = "Option::is_none")] pub enable_synonyms: Option, - /// Allow synonym resolution on word prefixes in the query. Default: false + /// Allow synonym resolution on word prefixes in the query. Default: false #[serde(rename = "synonym_prefix", skip_serializing_if = "Option::is_none")] pub synonym_prefix: Option, - /// Allow synonym resolution on typo-corrected words in the query. Default: 0 + /// Allow synonym resolution on typo-corrected words in the query. Default: 0 #[serde(rename = "synonym_num_typos", skip_serializing_if = "Option::is_none")] pub synonym_num_typos: Option, - /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "pinned_hits", skip_serializing_if = "Option::is_none")] pub pinned_hits: Option, - /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "hidden_hits", skip_serializing_if = "Option::is_none")] pub hidden_hits: Option, /// Comma separated list of tags to trigger the curations rules that match the tags. #[serde(rename = "override_tags", skip_serializing_if = "Option::is_none")] pub override_tags: Option, - /// A list of custom fields that must be highlighted even if you don't query for them + /// A list of custom fields that must be highlighted even if you don't query for them #[serde(rename = "highlight_fields", skip_serializing_if = "Option::is_none")] pub highlight_fields: Option, - /// Treat space as typo: search for q=basket ball if q=basketball is not found or vice-versa. Splitting/joining of tokens will only be attempted if the original query produces no results. To always trigger this behavior, set value to `always``. To disable, set value to `off`. Default is `fallback`. + /// Treat space as typo: search for q=basket ball if q=basketball is not found or vice-versa. Splitting/joining of tokens will only be attempted if the original query produces no results. To always trigger this behavior, set value to `always``. To disable, set value to `off`. Default is `fallback`. #[serde(rename = "split_join_tokens", skip_serializing_if = "Option::is_none")] pub split_join_tokens: Option, - /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same - #[serde( - rename = "pre_segmented_query", - skip_serializing_if = "Option::is_none" - )] + /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same + #[serde(rename = "pre_segmented_query", skip_serializing_if = "Option::is_none")] pub pre_segmented_query: Option, - /// Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. + /// Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. #[serde(rename = "preset", skip_serializing_if = "Option::is_none")] pub preset: Option, - /// If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false + /// If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false #[serde(rename = "enable_overrides", skip_serializing_if = "Option::is_none")] pub enable_overrides: Option, - /// Set this parameter to true to ensure that an exact match is ranked above the others - #[serde( - rename = "prioritize_exact_match", - skip_serializing_if = "Option::is_none" - )] + /// Set this parameter to true to ensure that an exact match is ranked above the others + #[serde(rename = "prioritize_exact_match", skip_serializing_if = "Option::is_none")] pub prioritize_exact_match: Option, - /// Control the number of words that Typesense considers for typo and prefix searching. + /// Control the number of words that Typesense considers for typo and prefix searching. #[serde(rename = "max_candidates", skip_serializing_if = "Option::is_none")] pub max_candidates: Option, - /// Make Typesense prioritize documents where the query words appear earlier in the text. - #[serde( - rename = "prioritize_token_position", - skip_serializing_if = "Option::is_none" - )] + /// Make Typesense prioritize documents where the query words appear earlier in the text. + #[serde(rename = "prioritize_token_position", skip_serializing_if = "Option::is_none")] pub prioritize_token_position: Option, - /// Make Typesense prioritize documents where the query words appear in more number of fields. - #[serde( - rename = "prioritize_num_matching_fields", - skip_serializing_if = "Option::is_none" - )] + /// Make Typesense prioritize documents where the query words appear in more number of fields. + #[serde(rename = "prioritize_num_matching_fields", skip_serializing_if = "Option::is_none")] pub prioritize_num_matching_fields: Option, - /// Make Typesense disable typos for numerical tokens. - #[serde( - rename = "enable_typos_for_numerical_tokens", - skip_serializing_if = "Option::is_none" - )] + /// Make Typesense disable typos for numerical tokens. + #[serde(rename = "enable_typos_for_numerical_tokens", skip_serializing_if = "Option::is_none")] pub enable_typos_for_numerical_tokens: Option, - /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). + /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). #[serde(rename = "exhaustive_search", skip_serializing_if = "Option::is_none")] pub exhaustive_search: Option, - /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. + /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. #[serde(rename = "search_cutoff_ms", skip_serializing_if = "Option::is_none")] pub search_cutoff_ms: Option, - /// Enable server side caching of search query results. By default, caching is disabled. + /// Enable server side caching of search query results. By default, caching is disabled. #[serde(rename = "use_cache", skip_serializing_if = "Option::is_none")] pub use_cache: Option, - /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. + /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. #[serde(rename = "cache_ttl", skip_serializing_if = "Option::is_none")] pub cache_ttl: Option, - /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_1typo", skip_serializing_if = "Option::is_none")] pub min_len_1typo: Option, - /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_2typo", skip_serializing_if = "Option::is_none")] pub min_len_2typo: Option, - /// Vector query expression for fetching documents \"closest\" to a given query/document vector. + /// Vector query expression for fetching documents \"closest\" to a given query/document vector. #[serde(rename = "vector_query", skip_serializing_if = "Option::is_none")] pub vector_query: Option, - /// Timeout (in milliseconds) for fetching remote embeddings. - #[serde( - rename = "remote_embedding_timeout_ms", - skip_serializing_if = "Option::is_none" - )] + /// Timeout (in milliseconds) for fetching remote embeddings. + #[serde(rename = "remote_embedding_timeout_ms", skip_serializing_if = "Option::is_none")] pub remote_embedding_timeout_ms: Option, - /// Number of times to retry fetching remote embeddings. - #[serde( - rename = "remote_embedding_num_tries", - skip_serializing_if = "Option::is_none" - )] + /// Number of times to retry fetching remote embeddings. + #[serde(rename = "remote_embedding_num_tries", skip_serializing_if = "Option::is_none")] pub remote_embedding_num_tries: Option, - /// Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). + /// Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). #[serde(rename = "facet_strategy", skip_serializing_if = "Option::is_none")] pub facet_strategy: Option, - /// Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. + /// Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. #[serde(rename = "stopwords", skip_serializing_if = "Option::is_none")] pub stopwords: Option, - /// Comma separated string of nested facet fields whose parent object should be returned in facet response. - #[serde( - rename = "facet_return_parent", - skip_serializing_if = "Option::is_none" - )] + /// Comma separated string of nested facet fields whose parent object should be returned in facet response. + #[serde(rename = "facet_return_parent", skip_serializing_if = "Option::is_none")] pub facet_return_parent: Option, - /// The base64 encoded audio file in 16 khz 16-bit WAV format. + /// The base64 encoded audio file in 16 khz 16-bit WAV format. #[serde(rename = "voice_query", skip_serializing_if = "Option::is_none")] pub voice_query: Option, - /// Enable conversational search. + /// Enable conversational search. #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] pub conversation: Option, - /// The Id of Conversation Model to be used. - #[serde( - rename = "conversation_model_id", - skip_serializing_if = "Option::is_none" - )] + /// The Id of Conversation Model to be used. + #[serde(rename = "conversation_model_id", skip_serializing_if = "Option::is_none")] pub conversation_model_id: Option, - /// The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + /// The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. #[serde(rename = "conversation_id", skip_serializing_if = "Option::is_none")] pub conversation_id: Option, } impl SearchParameters { - pub fn new() -> SearchParameters { + pub fn new() -> SearchParameters{ SearchParameters { q: None, query_by: None, @@ -363,3 +306,4 @@ impl SearchParameters { } } } + diff --git a/typesense_codegen/src/models/search_request_params.rs b/typesense_codegen/src/models/search_request_params.rs index 7e67048..727ebb7 100644 --- a/typesense_codegen/src/models/search_request_params.rs +++ b/typesense_codegen/src/models/search_request_params.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -24,7 +24,7 @@ pub struct SearchRequestParams { } impl SearchRequestParams { - pub fn new(collection_name: String, q: String, per_page: i32) -> SearchRequestParams { + pub fn new(collection_name: String, q: String, per_page: i32) -> SearchRequestParams{ SearchRequestParams { collection_name, q, @@ -33,3 +33,4 @@ impl SearchRequestParams { } } } + diff --git a/typesense_codegen/src/models/search_request_params_voice_query.rs b/typesense_codegen/src/models/search_request_params_voice_query.rs index 97e78ef..b5fd5a3 100644 --- a/typesense_codegen/src/models/search_request_params_voice_query.rs +++ b/typesense_codegen/src/models/search_request_params_voice_query.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,9 +18,10 @@ pub struct SearchRequestParamsVoiceQuery { } impl SearchRequestParamsVoiceQuery { - pub fn new() -> SearchRequestParamsVoiceQuery { + pub fn new() -> SearchRequestParamsVoiceQuery{ SearchRequestParamsVoiceQuery { transcribed_query: None, } } } + diff --git a/typesense_codegen/src/models/search_result.rs b/typesense_codegen/src/models/search_result.rs index f5ea5b5..b1630c9 100644 --- a/typesense_codegen/src/models/search_result.rs +++ b/typesense_codegen/src/models/search_result.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -42,15 +42,12 @@ pub struct SearchResult { #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] pub conversation: Option>, /// Returned only for union query response. - #[serde( - rename = "union_request_params", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "union_request_params", skip_serializing_if = "Option::is_none")] pub union_request_params: Option>, } impl SearchResult { - pub fn new() -> SearchResult { + pub fn new() -> SearchResult{ SearchResult { facet_counts: None, found: None, @@ -67,3 +64,4 @@ impl SearchResult { } } } + diff --git a/typesense_codegen/src/models/search_result_conversation.rs b/typesense_codegen/src/models/search_result_conversation.rs index 380be44..c47f800 100644 --- a/typesense_codegen/src/models/search_result_conversation.rs +++ b/typesense_codegen/src/models/search_result_conversation.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -24,12 +24,7 @@ pub struct SearchResultConversation { } impl SearchResultConversation { - pub fn new( - answer: String, - conversation_history: Vec, - conversation_id: String, - query: String, - ) -> SearchResultConversation { + pub fn new(answer: String, conversation_history: Vec, conversation_id: String, query: String) -> SearchResultConversation{ SearchResultConversation { answer, conversation_history, @@ -38,3 +33,4 @@ impl SearchResultConversation { } } } + diff --git a/typesense_codegen/src/models/search_result_hit.rs b/typesense_codegen/src/models/search_result_hit.rs index abe92e4..8ffb5e4 100644 --- a/typesense_codegen/src/models/search_result_hit.rs +++ b/typesense_codegen/src/models/search_result_hit.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -27,10 +27,7 @@ pub struct SearchResultHit { #[serde(rename = "text_match_info", skip_serializing_if = "Option::is_none")] pub text_match_info: Option>, /// Can be any key-value pair - #[serde( - rename = "geo_distance_meters", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "geo_distance_meters", skip_serializing_if = "Option::is_none")] pub geo_distance_meters: Option>, /// Distance between the query vector and matching document's vector value #[serde(rename = "vector_distance", skip_serializing_if = "Option::is_none")] @@ -43,7 +40,7 @@ pub struct SearchResultHit { } impl SearchResultHit { - pub fn new() -> SearchResultHit { + pub fn new() -> SearchResultHit{ SearchResultHit { highlights: None, highlight: None, @@ -57,3 +54,4 @@ impl SearchResultHit { } } } + diff --git a/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs b/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs index ed0bea0..def14c5 100644 --- a/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs +++ b/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -21,9 +21,10 @@ pub struct SearchResultHitHybridSearchInfo { impl SearchResultHitHybridSearchInfo { /// Information about hybrid search scoring - pub fn new() -> SearchResultHitHybridSearchInfo { + pub fn new() -> SearchResultHitHybridSearchInfo{ SearchResultHitHybridSearchInfo { rank_fusion_score: None, } } } + diff --git a/typesense_codegen/src/models/search_result_hit_text_match_info.rs b/typesense_codegen/src/models/search_result_hit_text_match_info.rs index e77c40f..6ad7736 100644 --- a/typesense_codegen/src/models/search_result_hit_text_match_info.rs +++ b/typesense_codegen/src/models/search_result_hit_text_match_info.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -30,7 +30,7 @@ pub struct SearchResultHitTextMatchInfo { } impl SearchResultHitTextMatchInfo { - pub fn new() -> SearchResultHitTextMatchInfo { + pub fn new() -> SearchResultHitTextMatchInfo{ SearchResultHitTextMatchInfo { best_field_score: None, best_field_weight: None, @@ -42,3 +42,4 @@ impl SearchResultHitTextMatchInfo { } } } + diff --git a/typesense_codegen/src/models/search_synonym.rs b/typesense_codegen/src/models/search_synonym.rs index 3d81eb7..4310dab 100644 --- a/typesense_codegen/src/models/search_synonym.rs +++ b/typesense_codegen/src/models/search_synonym.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -30,7 +30,7 @@ pub struct SearchSynonym { } impl SearchSynonym { - pub fn new(synonyms: Vec, id: String) -> SearchSynonym { + pub fn new(synonyms: Vec, id: String) -> SearchSynonym{ SearchSynonym { root: None, synonyms, @@ -40,3 +40,4 @@ impl SearchSynonym { } } } + diff --git a/typesense_codegen/src/models/search_synonym_delete_response.rs b/typesense_codegen/src/models/search_synonym_delete_response.rs index c69e47b..d138eab 100644 --- a/typesense_codegen/src/models/search_synonym_delete_response.rs +++ b/typesense_codegen/src/models/search_synonym_delete_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,7 +19,10 @@ pub struct SearchSynonymDeleteResponse { } impl SearchSynonymDeleteResponse { - pub fn new(id: String) -> SearchSynonymDeleteResponse { - SearchSynonymDeleteResponse { id } + pub fn new(id: String) -> SearchSynonymDeleteResponse{ + SearchSynonymDeleteResponse { + id, + } } } + diff --git a/typesense_codegen/src/models/search_synonym_schema.rs b/typesense_codegen/src/models/search_synonym_schema.rs index 192829f..99a96a9 100644 --- a/typesense_codegen/src/models/search_synonym_schema.rs +++ b/typesense_codegen/src/models/search_synonym_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -28,7 +28,7 @@ pub struct SearchSynonymSchema { } impl SearchSynonymSchema { - pub fn new(synonyms: Vec) -> SearchSynonymSchema { + pub fn new(synonyms: Vec) -> SearchSynonymSchema{ SearchSynonymSchema { root: None, synonyms, @@ -37,3 +37,4 @@ impl SearchSynonymSchema { } } } + diff --git a/typesense_codegen/src/models/search_synonyms_response.rs b/typesense_codegen/src/models/search_synonyms_response.rs index 40434ca..eab2311 100644 --- a/typesense_codegen/src/models/search_synonyms_response.rs +++ b/typesense_codegen/src/models/search_synonyms_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,7 +18,10 @@ pub struct SearchSynonymsResponse { } impl SearchSynonymsResponse { - pub fn new(synonyms: Vec) -> SearchSynonymsResponse { - SearchSynonymsResponse { synonyms } + pub fn new(synonyms: Vec) -> SearchSynonymsResponse{ + SearchSynonymsResponse { + synonyms, + } } } + diff --git a/typesense_codegen/src/models/stemming_dictionary.rs b/typesense_codegen/src/models/stemming_dictionary.rs index e90942c..3976e9c 100644 --- a/typesense_codegen/src/models/stemming_dictionary.rs +++ b/typesense_codegen/src/models/stemming_dictionary.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -22,7 +22,11 @@ pub struct StemmingDictionary { } impl StemmingDictionary { - pub fn new(id: String, words: Vec) -> StemmingDictionary { - StemmingDictionary { id, words } + pub fn new(id: String, words: Vec) -> StemmingDictionary{ + StemmingDictionary { + id, + words, + } } } + diff --git a/typesense_codegen/src/models/stemming_dictionary_words_inner.rs b/typesense_codegen/src/models/stemming_dictionary_words_inner.rs index 30cbd40..c712b4b 100644 --- a/typesense_codegen/src/models/stemming_dictionary_words_inner.rs +++ b/typesense_codegen/src/models/stemming_dictionary_words_inner.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -22,7 +22,11 @@ pub struct StemmingDictionaryWordsInner { } impl StemmingDictionaryWordsInner { - pub fn new(word: String, root: String) -> StemmingDictionaryWordsInner { - StemmingDictionaryWordsInner { word, root } + pub fn new(word: String, root: String) -> StemmingDictionaryWordsInner{ + StemmingDictionaryWordsInner { + word, + root, + } } } + diff --git a/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs b/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs index b1b6913..c3b7b9c 100644 --- a/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs +++ b/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,9 +18,10 @@ pub struct StopwordsSetRetrieveSchema { } impl StopwordsSetRetrieveSchema { - pub fn new(stopwords: models::StopwordsSetSchema) -> StopwordsSetRetrieveSchema { + pub fn new(stopwords: models::StopwordsSetSchema) -> StopwordsSetRetrieveSchema{ StopwordsSetRetrieveSchema { stopwords: Box::new(stopwords), } } } + diff --git a/typesense_codegen/src/models/stopwords_set_schema.rs b/typesense_codegen/src/models/stopwords_set_schema.rs index 8f13dee..bf1dace 100644 --- a/typesense_codegen/src/models/stopwords_set_schema.rs +++ b/typesense_codegen/src/models/stopwords_set_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -22,7 +22,7 @@ pub struct StopwordsSetSchema { } impl StopwordsSetSchema { - pub fn new(id: String, stopwords: Vec) -> StopwordsSetSchema { + pub fn new(id: String, stopwords: Vec) -> StopwordsSetSchema{ StopwordsSetSchema { id, stopwords, @@ -30,3 +30,4 @@ impl StopwordsSetSchema { } } } + diff --git a/typesense_codegen/src/models/stopwords_set_upsert_schema.rs b/typesense_codegen/src/models/stopwords_set_upsert_schema.rs index 1facab5..2feb7f1 100644 --- a/typesense_codegen/src/models/stopwords_set_upsert_schema.rs +++ b/typesense_codegen/src/models/stopwords_set_upsert_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -20,10 +20,11 @@ pub struct StopwordsSetUpsertSchema { } impl StopwordsSetUpsertSchema { - pub fn new(stopwords: Vec) -> StopwordsSetUpsertSchema { + pub fn new(stopwords: Vec) -> StopwordsSetUpsertSchema{ StopwordsSetUpsertSchema { stopwords, locale: None, } } } + diff --git a/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs b/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs index 84703ac..8e26e17 100644 --- a/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs +++ b/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,7 +18,10 @@ pub struct StopwordsSetsRetrieveAllSchema { } impl StopwordsSetsRetrieveAllSchema { - pub fn new(stopwords: Vec) -> StopwordsSetsRetrieveAllSchema { - StopwordsSetsRetrieveAllSchema { stopwords } + pub fn new(stopwords: Vec) -> StopwordsSetsRetrieveAllSchema{ + StopwordsSetsRetrieveAllSchema { + stopwords, + } } } + diff --git a/typesense_codegen/src/models/success_status.rs b/typesense_codegen/src/models/success_status.rs index c88ecb9..9b1f636 100644 --- a/typesense_codegen/src/models/success_status.rs +++ b/typesense_codegen/src/models/success_status.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,7 +18,10 @@ pub struct SuccessStatus { } impl SuccessStatus { - pub fn new(success: bool) -> SuccessStatus { - SuccessStatus { success } + pub fn new(success: bool) -> SuccessStatus{ + SuccessStatus { + success, + } } } + diff --git a/typesense_codegen/src/models/synonym_item_schema.rs b/typesense_codegen/src/models/synonym_item_schema.rs index bb03da3..8b1d84b 100644 --- a/typesense_codegen/src/models/synonym_item_schema.rs +++ b/typesense_codegen/src/models/synonym_item_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -31,7 +31,7 @@ pub struct SynonymItemSchema { } impl SynonymItemSchema { - pub fn new(id: String, synonyms: Vec) -> SynonymItemSchema { + pub fn new(id: String, synonyms: Vec) -> SynonymItemSchema{ SynonymItemSchema { id, synonyms, @@ -41,3 +41,4 @@ impl SynonymItemSchema { } } } + diff --git a/typesense_codegen/src/models/synonym_set_create_schema.rs b/typesense_codegen/src/models/synonym_set_create_schema.rs index 818ae98..c52dac9 100644 --- a/typesense_codegen/src/models/synonym_set_create_schema.rs +++ b/typesense_codegen/src/models/synonym_set_create_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,7 +19,10 @@ pub struct SynonymSetCreateSchema { } impl SynonymSetCreateSchema { - pub fn new(items: Vec) -> SynonymSetCreateSchema { - SynonymSetCreateSchema { items } + pub fn new(items: Vec) -> SynonymSetCreateSchema{ + SynonymSetCreateSchema { + items, + } } } + diff --git a/typesense_codegen/src/models/synonym_set_delete_schema.rs b/typesense_codegen/src/models/synonym_set_delete_schema.rs index e127040..e345e32 100644 --- a/typesense_codegen/src/models/synonym_set_delete_schema.rs +++ b/typesense_codegen/src/models/synonym_set_delete_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,7 +19,10 @@ pub struct SynonymSetDeleteSchema { } impl SynonymSetDeleteSchema { - pub fn new(name: String) -> SynonymSetDeleteSchema { - SynonymSetDeleteSchema { name } + pub fn new(name: String) -> SynonymSetDeleteSchema{ + SynonymSetDeleteSchema { + name, + } } } + diff --git a/typesense_codegen/src/models/synonym_set_schema.rs b/typesense_codegen/src/models/synonym_set_schema.rs index f9e171c..b500baf 100644 --- a/typesense_codegen/src/models/synonym_set_schema.rs +++ b/typesense_codegen/src/models/synonym_set_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -22,7 +22,11 @@ pub struct SynonymSetSchema { } impl SynonymSetSchema { - pub fn new(items: Vec, name: String) -> SynonymSetSchema { - SynonymSetSchema { items, name } + pub fn new(items: Vec, name: String) -> SynonymSetSchema{ + SynonymSetSchema { + items, + name, + } } } + diff --git a/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs b/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs index 612c1a5..ac28af6 100644 --- a/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs +++ b/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,7 +19,10 @@ pub struct SynonymSetsRetrieveSchema { } impl SynonymSetsRetrieveSchema { - pub fn new(synonym_sets: Vec) -> SynonymSetsRetrieveSchema { - SynonymSetsRetrieveSchema { synonym_sets } + pub fn new(synonym_sets: Vec) -> SynonymSetsRetrieveSchema{ + SynonymSetsRetrieveSchema { + synonym_sets, + } } } + diff --git a/typesense_codegen/src/models/toggle_slow_request_log_request.rs b/typesense_codegen/src/models/toggle_slow_request_log_request.rs index 2957298..fdce446 100644 --- a/typesense_codegen/src/models/toggle_slow_request_log_request.rs +++ b/typesense_codegen/src/models/toggle_slow_request_log_request.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,9 +18,10 @@ pub struct ToggleSlowRequestLogRequest { } impl ToggleSlowRequestLogRequest { - pub fn new(log_slow_requests_time_ms: i32) -> ToggleSlowRequestLogRequest { + pub fn new(log_slow_requests_time_ms: i32) -> ToggleSlowRequestLogRequest{ ToggleSlowRequestLogRequest { log_slow_requests_time_ms, } } } + diff --git a/typesense_codegen/src/models/update_documents_200_response.rs b/typesense_codegen/src/models/update_documents_200_response.rs index 88cc7b4..48d8905 100644 --- a/typesense_codegen/src/models/update_documents_200_response.rs +++ b/typesense_codegen/src/models/update_documents_200_response.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,7 +19,10 @@ pub struct UpdateDocuments200Response { } impl UpdateDocuments200Response { - pub fn new(num_updated: i32) -> UpdateDocuments200Response { - UpdateDocuments200Response { num_updated } + pub fn new(num_updated: i32) -> UpdateDocuments200Response{ + UpdateDocuments200Response { + num_updated, + } } } + diff --git a/typesense_codegen/src/models/update_documents_parameters.rs b/typesense_codegen/src/models/update_documents_parameters.rs index cf49cbb..36ce061 100644 --- a/typesense_codegen/src/models/update_documents_parameters.rs +++ b/typesense_codegen/src/models/update_documents_parameters.rs @@ -4,7 +4,7 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,7 +18,10 @@ pub struct UpdateDocumentsParameters { } impl UpdateDocumentsParameters { - pub fn new() -> UpdateDocumentsParameters { - UpdateDocumentsParameters { filter_by: None } + pub fn new() -> UpdateDocumentsParameters{ + UpdateDocumentsParameters { + filter_by: None, + } } } + diff --git a/typesense_codegen/src/models/voice_query_model_collection_config.rs b/typesense_codegen/src/models/voice_query_model_collection_config.rs index 38044c9..99cb770 100644 --- a/typesense_codegen/src/models/voice_query_model_collection_config.rs +++ b/typesense_codegen/src/models/voice_query_model_collection_config.rs @@ -4,14 +4,14 @@ * An open source search engine for building delightful search experiences. * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ use crate::models; use serde::{Deserialize, Serialize}; -/// VoiceQueryModelCollectionConfig : Configuration for the voice query model +/// VoiceQueryModelCollectionConfig : Configuration for the voice query model #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct VoiceQueryModelCollectionConfig { #[serde(rename = "model_name", skip_serializing_if = "Option::is_none")] @@ -19,8 +19,11 @@ pub struct VoiceQueryModelCollectionConfig { } impl VoiceQueryModelCollectionConfig { - /// Configuration for the voice query model - pub fn new() -> VoiceQueryModelCollectionConfig { - VoiceQueryModelCollectionConfig { model_name: None } + /// Configuration for the voice query model + pub fn new() -> VoiceQueryModelCollectionConfig{ + VoiceQueryModelCollectionConfig { + model_name: None, + } } } + diff --git a/xtask/src/add_vendor_attributes.rs b/xtask/src/add_vendor_attributes.rs new file mode 100644 index 0000000..b6fa561 --- /dev/null +++ b/xtask/src/add_vendor_attributes.rs @@ -0,0 +1,66 @@ +use crate::vendor_attributes::VendorAttributes; +use serde_yaml::Mapping; + +pub fn add_vendor_attributes(doc_root: &mut Mapping) -> Result<(), String> { + println!("Adding custom x-* vendor attributes..."); + let mut attrs = VendorAttributes::new(doc_root); + + // Schemas + attrs.schema_builder([ + "CollectionSchema", + "Field", + "SearchParameters", + "MultiSearchParameters", + "MultiSearchCollectionParameters", + ])?; + + attrs.schema_generic_parameter([ + ("SearchResult", ""), + ("SearchGroupedHit", ""), + ("SearchResultHit", ""), + ("MultiSearchResult", ""), + ("MultiSearchResultItem", ""), + ])?; + + attrs.schema_field_type_overrides( + "SearchResult", + [ + ("hits", "Option>>"), + ("grouped_hits", "Option>>"), + ], + )?; + attrs.schema_field_type_overrides( + "SearchGroupedHit", + [("hits", "Vec>")], + )?; + attrs.schema_field_type_overrides("SearchResultHit", [("document", "Option")])?; + attrs.schema_field_type_overrides( + "MultiSearchResult", + [("results", "Vec>")], + )?; + + // Operations + attrs + .operation("/collections/{collectionName}/documents/search", "get") + .generic_parameter(" serde::Deserialize<'de> + Serialize>") + .return_type("models::SearchResult") + .done()?; + + attrs + .operation("/multi_search", "post") + .return_type("serde_json::Value") + .done()?; + + attrs + .operation("/collections/{collectionName}/documents/import", "post") + .body_is_raw_text() + .supports_plain_text() + .done()?; + + attrs + .operation("/collections/{collectionName}/documents/export", "get") + .supports_plain_text() + .done()?; + + Ok(()) +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs index dfb3d1f..3687251 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -1,7 +1,9 @@ use anyhow::{Context, Result}; use clap::{Parser, ValueEnum}; use std::{env, fs, process::Command}; +mod add_vendor_attributes; mod preprocess_openapi; +mod vendor_attributes; use preprocess_openapi::preprocess_openapi_file; const SPEC_URL: &str = diff --git a/xtask/src/preprocess_openapi.rs b/xtask/src/preprocess_openapi.rs index c0e9e81..1e49ad5 100644 --- a/xtask/src/preprocess_openapi.rs +++ b/xtask/src/preprocess_openapi.rs @@ -1,6 +1,8 @@ use serde_yaml::{Mapping, Value}; use std::fs; +use crate::add_vendor_attributes::add_vendor_attributes; + // --- Main function to orchestrate the file reading, processing, and writing --- pub fn preprocess_openapi_file( input_path: &str, @@ -19,6 +21,10 @@ pub fn preprocess_openapi_file( // --- Step 2: Apply all the required transformations --- println!("Preprocessing the spec..."); + + add_vendor_attributes(doc_root)?; + + println!("Unwrapping parameters..."); unwrap_search_parameters(doc_root)?; unwrap_multi_search_parameters(doc_root)?; unwrap_parameters_by_path( diff --git a/xtask/src/vendor_attributes.rs b/xtask/src/vendor_attributes.rs new file mode 100644 index 0000000..17d411e --- /dev/null +++ b/xtask/src/vendor_attributes.rs @@ -0,0 +1,196 @@ +use serde_yaml::{Mapping, Value}; + +/// Where to apply a vendor (x-*) attribute. +pub enum VendorLocation<'a> { + Schema(&'a str), + SchemaField { schema: &'a str, field: &'a str }, + Operation { path: &'a str, method: &'a str }, +} + +/// Main helper struct that holds a mutable borrow of the OpenAPI root mapping. +pub struct VendorAttributes<'a> { + doc: &'a mut Mapping, +} + +impl<'a> VendorAttributes<'a> { + pub fn new(doc: &'a mut Mapping) -> Self { + Self { doc } + } + + // internal helpers + + fn traverse_value_mut(&mut self, keys: &[&str]) -> Option<&mut Value> { + if keys.is_empty() { + return None; + } + let mut cur: Option<&mut Value> = self.doc.get_mut(keys[0]); + for k in &keys[1..] { + cur = cur.and_then(|v| v.get_mut(k)); + } + cur + } + + fn get_map_mut(&mut self, keys: &[&str]) -> Result<&mut Mapping, String> { + self.traverse_value_mut(keys) + .and_then(|v| v.as_mapping_mut()) + .ok_or_else(|| format!("expected mapping at path: {}", keys.join("."))) + } + + #[inline] + fn insert_into_map(map: &mut Mapping, attr: &str, val: Value) { + map.insert(Value::String(attr.to_string()), val); + } + + fn set_attr( + &mut self, + location: VendorLocation<'_>, + attr: &str, + val: Value, + ) -> Result<&mut Self, String> { + match location { + VendorLocation::Schema(schema_name) => { + let map = self.get_map_mut(&["components", "schemas", schema_name])?; + Self::insert_into_map(map, attr, val); + Ok(self) + } + VendorLocation::SchemaField { schema, field } => { + let props_map = self + .get_map_mut(&["components", "schemas", schema, "properties"]) + .map_err(|_| format!("schema '{}' has no properties mapping", schema))?; + + let prop_key = Value::String(field.to_string()); + match props_map.get_mut(&prop_key) { + Some(existing_val) => { + if let Some(field_map) = existing_val.as_mapping_mut() { + Self::insert_into_map(field_map, attr, val); + Ok(self) + } else { + Err(format!( + "property '{}' in schema '{}' exists but is not a mapping; cannot set '{}'", + field, schema, attr + )) + } + } + None => { + let mut new_field_map = Mapping::new(); + new_field_map.insert(Value::String(attr.to_string()), val); + props_map.insert(prop_key, Value::Mapping(new_field_map)); + Ok(self) + } + } + } + VendorLocation::Operation { path, method } => { + let op_map = self + .get_map_mut(&["paths", path, method]) + .map_err(|_| format!("operation not found: {} {}", method, path))?; + Self::insert_into_map(op_map, attr, val); + Ok(self) + } + } + } + + pub fn schema_generic_parameter( + &mut self, + items: [(&str, &str); N], + ) -> Result<&mut Self, String> { + for (schema, generic) in items { + self.set_attr( + VendorLocation::Schema(schema), + "x-rust-generic-parameter", + Value::String(generic.into()), + )?; + } + Ok(self) + } + + pub fn schema_builder( + &mut self, + schemas: [&str; N], + ) -> Result<&mut Self, String> { + for schema in schemas { + self.set_attr( + VendorLocation::Schema(schema), + "x-rust-builder", + Value::Bool(true), + )?; + } + Ok(self) + } + + pub fn schema_field_type_overrides( + &mut self, + schema: &str, + overrides: [(&str, &str); N], + ) -> Result<&mut Self, String> { + for (field, rust_type) in overrides { + self.set_attr( + VendorLocation::SchemaField { schema, field }, + "x-rust-type", + Value::String(rust_type.into()), + )?; + } + Ok(self) + } + + pub fn operation<'b>(&'b mut self, path: &'b str, method: &'b str) -> OperationContext<'a, 'b> { + OperationContext { + vendor: self, + path, + method, + error: None, + } + } +} + +pub struct OperationContext<'a, 'b> { + vendor: &'b mut VendorAttributes<'a>, + path: &'b str, + method: &'b str, + error: Option, +} + +impl<'a, 'b> OperationContext<'a, 'b> { + fn try_set(&mut self, attr: &str, val: Value) { + if self.error.is_some() { + return; + } + if let Err(e) = self.vendor.set_attr( + VendorLocation::Operation { + path: self.path, + method: self.method, + }, + attr, + val, + ) { + self.error = Some(e); + } + } + + pub fn generic_parameter(mut self, generic: &str) -> Self { + self.try_set("x-rust-generic-parameter", Value::String(generic.into())); + self + } + + pub fn return_type(mut self, rust_type: &str) -> Self { + self.try_set("x-rust-return-type", Value::String(rust_type.into())); + self + } + + pub fn body_is_raw_text(mut self) -> Self { + self.try_set("x-rust-body-is-raw-text", Value::Bool(true)); + self + } + + pub fn supports_plain_text(mut self) -> Self { + self.try_set("x-supports-plain-text", Value::Bool(true)); + self + } + + /// Return to VendorAttributes if no errors, or propagate the first error + pub fn done(self) -> Result<&'b mut VendorAttributes<'a>, String> { + match self.error { + Some(err) => Err(err), + None => Ok(self.vendor), + } + } +} From 924e772b86583e289433819b5f97856530750cf9 Mon Sep 17 00:00:00 2001 From: RoDmitry Date: Fri, 12 Sep 2025 09:26:59 +0000 Subject: [PATCH 24/41] Workspace dependencies --- Cargo.toml | 20 +++++++++++++++++--- typesense/Cargo.toml | 28 ++++++++++++++-------------- typesense/src/client/mod.rs | 5 ++--- typesense_codegen/Cargo.toml | 11 ++++++----- xtask/Cargo.toml | 10 +++++----- 5 files changed, 44 insertions(+), 30 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 23adab9..36c1189 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,6 +16,20 @@ repository = "https://github.com/typesense/typesense-rust" authors = ["Typesense "] [workspace.dependencies] - -typesense_derive = { path = "./typesense_derive", version = "0.3.0" } -typesense_codegen = { path = "./typesense_codegen", version = "0.25.0" } \ No newline at end of file +typesense_codegen = { path = "./typesense_codegen", version = "0.25" } +typesense_derive = { path = "./typesense_derive", version = "0.3" } +anyhow = "1" +base64 = "0.22" +bon = "3" +clap = { version = "4", features = ["derive"] } +debug_unsafe = "0.1" +hmac = "0.12" +reqwest-retry = "0.7" +serde = { version = "1", features = ["derive"] } +serde_json = "1.0" +serde_repr = "0.1" +serde_yaml = "0.9" +sha2 = "0.10" +thiserror = "2" +url = "2" +web-time = "=1.1.0" diff --git a/typesense/Cargo.toml b/typesense/Cargo.toml index a408579..b25914f 100644 --- a/typesense/Cargo.toml +++ b/typesense/Cargo.toml @@ -19,17 +19,17 @@ crate-type = ["cdylib", "rlib"] [dependencies] typesense_codegen = { workspace = true } typesense_derive = { workspace = true, optional = true } -anyhow = "1.0" -base64 = "0.22" -bon = "3.7.0" -debug_unsafe = "0.1" -hmac = "0.12" -reqwest-retry = "0.7.0" -serde = { version = "1", features = ["derive"] } -serde_json = "1.0" -sha2 = "0.10" -thiserror = "1.0" -web-time = "=1.1.0" # required for wasm32 target +anyhow = { workspace = true } +base64 = { workspace = true } +bon = { workspace = true } +debug_unsafe = { workspace = true } +hmac = { workspace = true } +reqwest-retry = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +sha2 = { workspace = true } +thiserror = { workspace = true } +web-time = { workspace = true } # required for wasm32 target # native-only dependencies [target.'cfg(not(target_arch = "wasm32"))'.dependencies] @@ -43,20 +43,20 @@ reqwest = { version = "0.12", default-features = false, features = ["json"] } [dev-dependencies] dotenvy = "0.15" -trybuild = "1.0.42" nanoid = "0.4" +trybuild = "1.0.42" # native-only dev deps [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] tokio = { version = "1.5", features = ["macros", "rt", "rt-multi-thread"] } -wiremock = "0.5" +wiremock = "0.6" # wasm test deps [target.'cfg(target_arch = "wasm32")'.dev-dependencies] console_error_panic_hook = "0.1.6" wasm-bindgen = "0.2" -wasm-bindgen-test = "0.3.23" wasm-bindgen-futures = "0.4.50" +wasm-bindgen-test = "0.3.23" [[test]] name = "derive_tests" diff --git a/typesense/src/client/mod.rs b/typesense/src/client/mod.rs index 9fb6df0..38804b4 100644 --- a/typesense/src/client/mod.rs +++ b/typesense/src/client/mod.rs @@ -118,15 +118,14 @@ use collections::Collections; use key::Key; use keys::Keys; -use debug_unsafe::{option::OptionUnwrapper, slice::SliceGetter}; -use serde::{Serialize, de::DeserializeOwned}; - #[cfg(not(target_arch = "wasm32"))] use reqwest_middleware::ClientBuilder as ReqwestMiddlewareClientBuilder; #[cfg(not(target_arch = "wasm32"))] use reqwest_retry::RetryTransientMiddleware; pub use reqwest_retry::policies::ExponentialBackoff; +use debug_unsafe::{option::OptionUnwrapper, slice::SliceGetter}; +use serde::{Serialize, de::DeserializeOwned}; use std::{ future::Future, sync::{ diff --git a/typesense_codegen/Cargo.toml b/typesense_codegen/Cargo.toml index 51d07b6..ff2a22d 100644 --- a/typesense_codegen/Cargo.toml +++ b/typesense_codegen/Cargo.toml @@ -8,12 +8,13 @@ edition.workspace = true license.workspace = true [dependencies] -serde = { version = "^1.0", features = ["derive"] } -serde_json = "^1.0" -serde_repr = "^0.1" -url = "^2.5" -bon = "3.7.0" +bon = { workspace = true } reqwest = { version = "0.12", default-features = false, features = ["json"] } +serde = { workspace = true } +serde_json = { workspace = true } +serde_repr = { workspace = true } +url = { workspace = true } + [target.'cfg(not(target_arch = "wasm32"))'.dependencies] reqwest-middleware = { version = "0.4", features = ["json"] } diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index 994b250..f13f365 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -5,8 +5,8 @@ version = "0.0.0" edition.workspace = true [dependencies] -reqwest = { version = "0.11", features = ["blocking"] } # "blocking" is simpler for scripts -anyhow = "1.0" -clap = { version = "4.0", features = ["derive"] } -serde = { version = "1.0", features = ["derive"] } -serde_yaml = "0.9" +anyhow = { workspace = true } +clap = { workspace = true } +reqwest = { version = "0.12", features = ["blocking"] } # "blocking" is simpler for scripts +serde = { workspace = true } +serde_yaml = { workspace = true } From ef8dfc98ea427121d0466a21e7f11f0e6ad7e45a Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Fri, 12 Sep 2025 16:31:59 +0700 Subject: [PATCH 25/41] run cargo fmt after code-gen task --- typesense_codegen/src/apis/analytics_api.rs | 273 ++++++--- typesense_codegen/src/apis/collections_api.rs | 294 +++++++--- .../src/apis/conversations_api.rs | 167 ++++-- typesense_codegen/src/apis/curation_api.rs | 113 +++- typesense_codegen/src/apis/debug_api.rs | 34 +- typesense_codegen/src/apis/documents_api.rs | 530 +++++++++++++----- typesense_codegen/src/apis/health_api.rs | 34 +- typesense_codegen/src/apis/keys_api.rs | 132 +++-- .../src/apis/nl_search_models_api.rs | 164 ++++-- typesense_codegen/src/apis/operations_api.rs | 221 ++++++-- typesense_codegen/src/apis/override_api.rs | 44 +- typesense_codegen/src/apis/presets_api.rs | 134 +++-- typesense_codegen/src/apis/stemming_api.rs | 96 +++- typesense_codegen/src/apis/stopwords_api.rs | 134 +++-- typesense_codegen/src/apis/synonyms_api.rs | 134 +++-- .../src/models/analytics_event.rs | 10 +- .../models/analytics_event_create_response.rs | 10 +- .../src/models/analytics_event_data.rs | 6 +- .../src/models/analytics_events_response.rs | 10 +- .../analytics_events_response_events_inner.rs | 6 +- .../src/models/analytics_rule.rs | 13 +- .../src/models/analytics_rule_create.rs | 13 +- .../models/analytics_rule_create_params.rs | 16 +- .../src/models/analytics_rule_update.rs | 6 +- .../src/models/analytics_status.rs | 21 +- typesense_codegen/src/models/api_key.rs | 6 +- .../src/models/api_key_delete_response.rs | 10 +- .../src/models/api_key_schema.rs | 10 +- .../src/models/api_keys_response.rs | 10 +- typesense_codegen/src/models/api_response.rs | 10 +- .../src/models/api_stats_response.rs | 46 +- .../src/models/collection_alias.rs | 6 +- .../src/models/collection_alias_schema.rs | 10 +- .../src/models/collection_aliases_response.rs | 10 +- .../src/models/collection_response.rs | 27 +- .../src/models/collection_schema.rs | 22 +- .../src/models/collection_update_schema.rs | 8 +- .../conversation_model_create_schema.rs | 14 +- .../src/models/conversation_model_schema.rs | 15 +- .../conversation_model_update_schema.rs | 10 +- .../create_analytics_rule_200_response.rs | 6 +- ...nalytics_rule_200_response_one_of_inner.rs | 13 +- ...s_rule_200_response_one_of_inner_any_of.rs | 10 +- .../models/create_analytics_rule_request.rs | 6 +- .../src/models/debug_200_response.rs | 10 +- .../models/delete_documents_200_response.rs | 10 +- .../src/models/delete_documents_parameters.rs | 6 +- .../delete_stopwords_set_200_response.rs | 10 +- typesense_codegen/src/models/dirty_values.rs | 7 +- .../src/models/drop_tokens_mode.rs | 9 +- .../src/models/export_documents_parameters.rs | 6 +- typesense_codegen/src/models/facet_counts.rs | 6 +- .../src/models/facet_counts_counts_inner.rs | 6 +- .../src/models/facet_counts_stats.rs | 6 +- typesense_codegen/src/models/field.rs | 20 +- typesense_codegen/src/models/field_embed.rs | 6 +- .../src/models/field_embed_model_config.rs | 6 +- .../src/models/get_collections_parameters.rs | 8 +- typesense_codegen/src/models/health_status.rs | 10 +- .../src/models/import_documents_parameters.rs | 11 +- typesense_codegen/src/models/index_action.rs | 7 +- ...list_stemming_dictionaries_200_response.rs | 10 +- .../multi_search_collection_parameters.rs | 189 ++++--- .../src/models/multi_search_parameters.rs | 179 +++--- .../src/models/multi_search_result.rs | 6 +- .../src/models/multi_search_result_item.rs | 11 +- .../models/multi_search_searches_parameter.rs | 8 +- .../src/models/nl_search_model_base.rs | 6 +- .../models/nl_search_model_create_schema.rs | 6 +- .../models/nl_search_model_delete_schema.rs | 10 +- .../src/models/nl_search_model_schema.rs | 6 +- .../src/models/preset_delete_schema.rs | 10 +- typesense_codegen/src/models/preset_schema.rs | 6 +- .../src/models/preset_upsert_schema.rs | 6 +- .../src/models/preset_upsert_schema_value.rs | 4 +- .../src/models/presets_retrieve_schema.rs | 10 +- .../src/models/schema_change_status.rs | 6 +- .../src/models/search_grouped_hit.rs | 9 +- .../src/models/search_highlight.rs | 6 +- .../src/models/search_override.rs | 34 +- .../models/search_override_delete_response.rs | 10 +- .../src/models/search_override_exclude.rs | 10 +- .../src/models/search_override_include.rs | 11 +- .../src/models/search_override_rule.rs | 12 +- .../src/models/search_override_schema.rs | 34 +- .../src/models/search_overrides_response.rs | 10 +- .../src/models/search_parameters.rs | 191 ++++--- .../src/models/search_request_params.rs | 6 +- .../search_request_params_voice_query.rs | 6 +- typesense_codegen/src/models/search_result.rs | 11 +- .../src/models/search_result_conversation.rs | 11 +- .../src/models/search_result_hit.rs | 11 +- .../search_result_hit_hybrid_search_info.rs | 6 +- .../search_result_hit_text_match_info.rs | 6 +- .../src/models/search_synonym.rs | 6 +- .../models/search_synonym_delete_response.rs | 10 +- .../src/models/search_synonym_schema.rs | 6 +- .../src/models/search_synonyms_response.rs | 10 +- .../src/models/stemming_dictionary.rs | 11 +- .../models/stemming_dictionary_words_inner.rs | 11 +- .../models/stopwords_set_retrieve_schema.rs | 6 +- .../src/models/stopwords_set_schema.rs | 6 +- .../src/models/stopwords_set_upsert_schema.rs | 6 +- .../stopwords_sets_retrieve_all_schema.rs | 10 +- .../src/models/success_status.rs | 10 +- .../src/models/synonym_item_schema.rs | 6 +- .../src/models/synonym_set_create_schema.rs | 10 +- .../src/models/synonym_set_delete_schema.rs | 10 +- .../src/models/synonym_set_schema.rs | 11 +- .../models/synonym_sets_retrieve_schema.rs | 10 +- .../models/toggle_slow_request_log_request.rs | 6 +- .../models/update_documents_200_response.rs | 10 +- .../src/models/update_documents_parameters.rs | 10 +- .../voice_query_model_collection_config.rs | 14 +- xtask/src/main.rs | 15 + 115 files changed, 2656 insertions(+), 1403 deletions(-) diff --git a/typesense_codegen/src/apis/analytics_api.rs b/typesense_codegen/src/apis/analytics_api.rs index 5dd7ee3..611ea8a 100644 --- a/typesense_codegen/src/apis/analytics_api.rs +++ b/typesense_codegen/src/apis/analytics_api.rs @@ -2,37 +2,35 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ - +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`create_analytics_event`] #[derive(Clone, Debug)] pub struct CreateAnalyticsEventParams { /// The analytics event to be created - pub analytics_event: models::AnalyticsEvent + pub analytics_event: models::AnalyticsEvent, } /// struct for passing parameters to the method [`create_analytics_rule`] #[derive(Clone, Debug)] pub struct CreateAnalyticsRuleParams { /// The analytics rule(s) to be created - pub create_analytics_rule_request: models::CreateAnalyticsRuleRequest + pub create_analytics_rule_request: models::CreateAnalyticsRuleRequest, } /// struct for passing parameters to the method [`delete_analytics_rule`] #[derive(Clone, Debug)] pub struct DeleteAnalyticsRuleParams { /// The name of the analytics rule to delete - pub rule_name: String + pub rule_name: String, } /// struct for passing parameters to the method [`get_analytics_events`] @@ -42,21 +40,21 @@ pub struct GetAnalyticsEventsParams { /// Analytics rule name pub name: String, /// Number of events to return (max 1000) - pub n: i32 + pub n: i32, } /// struct for passing parameters to the method [`retrieve_analytics_rule`] #[derive(Clone, Debug)] pub struct RetrieveAnalyticsRuleParams { /// The name of the analytics rule to retrieve - pub rule_name: String + pub rule_name: String, } /// struct for passing parameters to the method [`retrieve_analytics_rules`] #[derive(Clone, Debug)] pub struct RetrieveAnalyticsRulesParams { /// Filter rules by rule_tag - pub rule_tag: Option + pub rule_tag: Option, } /// struct for passing parameters to the method [`upsert_analytics_rule`] @@ -65,10 +63,9 @@ pub struct UpsertAnalyticsRuleParams { /// The name of the analytics rule to upsert pub rule_name: String, /// The Analytics rule to be upserted - pub analytics_rule_update: models::AnalyticsRuleUpdate + pub analytics_rule_update: models::AnalyticsRuleUpdate, } - /// struct for typed errors of method [`create_analytics_event`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -138,12 +135,15 @@ pub enum UpsertAnalyticsRuleError { UnknownValue(serde_json::Value), } - /// Submit a single analytics event. The event must correspond to an existing analytics rule by name. -pub async fn create_analytics_event(configuration: &configuration::Configuration, params: CreateAnalyticsEventParams) -> Result> { - +pub async fn create_analytics_event( + configuration: &configuration::Configuration, + params: CreateAnalyticsEventParams, +) -> Result> { let uri_str = format!("{}/analytics/events", configuration.base_path); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -173,21 +173,37 @@ pub async fn create_analytics_event(configuration: &configuration::Configuration let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Create one or more analytics rules. You can send a single rule object or an array of rule objects. -pub async fn create_analytics_rule(configuration: &configuration::Configuration, params: CreateAnalyticsRuleParams) -> Result> { - +pub async fn create_analytics_rule( + configuration: &configuration::Configuration, + params: CreateAnalyticsRuleParams, +) -> Result> { let uri_str = format!("{}/analytics/rules", configuration.base_path); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -217,21 +233,41 @@ pub async fn create_analytics_rule(configuration: &configuration::Configuration, let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CreateAnalyticsRule200Response`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CreateAnalyticsRule200Response`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::CreateAnalyticsRule200Response`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::CreateAnalyticsRule200Response`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Permanently deletes an analytics rule, given it's name -pub async fn delete_analytics_rule(configuration: &configuration::Configuration, params: DeleteAnalyticsRuleParams) -> Result> { - - let uri_str = format!("{}/analytics/rules/{ruleName}", configuration.base_path, ruleName=crate::apis::urlencode(params.rule_name)); - let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_analytics_rule( + configuration: &configuration::Configuration, + params: DeleteAnalyticsRuleParams, +) -> Result> { + let uri_str = format!( + "{}/analytics/rules/{ruleName}", + configuration.base_path, + ruleName = crate::apis::urlencode(params.rule_name) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -260,21 +296,36 @@ pub async fn delete_analytics_rule(configuration: &configuration::Configuration, let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsRule`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsRule`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::AnalyticsRule`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsRule`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Triggers a flush of analytics data to persistent storage. -pub async fn flush_analytics(configuration: &configuration::Configuration) -> Result> { - +pub async fn flush_analytics( + configuration: &configuration::Configuration, +) -> Result> { let uri_str = format!("{}/analytics/flush", configuration.base_path); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -303,19 +354,33 @@ pub async fn flush_analytics(configuration: &configuration::Configuration) -> Re let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve the most recent events for a user and rule. -pub async fn get_analytics_events(configuration: &configuration::Configuration, params: GetAnalyticsEventsParams) -> Result> { - +pub async fn get_analytics_events( + configuration: &configuration::Configuration, + params: GetAnalyticsEventsParams, +) -> Result> { let uri_str = format!("{}/analytics/events", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -349,19 +414,32 @@ pub async fn get_analytics_events(configuration: &configuration::Configuration, let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsEventsResponse`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsEventsResponse`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::AnalyticsEventsResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsEventsResponse`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Returns sizes of internal analytics buffers and queues. -pub async fn get_analytics_status(configuration: &configuration::Configuration) -> Result> { - +pub async fn get_analytics_status( + configuration: &configuration::Configuration, +) -> Result> { let uri_str = format!("{}/analytics/status", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -392,20 +470,38 @@ pub async fn get_analytics_status(configuration: &configuration::Configuration) let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsStatus`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsStatus`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::AnalyticsStatus`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsStatus`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve the details of an analytics rule, given it's name -pub async fn retrieve_analytics_rule(configuration: &configuration::Configuration, params: RetrieveAnalyticsRuleParams) -> Result> { - - let uri_str = format!("{}/analytics/rules/{ruleName}", configuration.base_path, ruleName=crate::apis::urlencode(params.rule_name)); +pub async fn retrieve_analytics_rule( + configuration: &configuration::Configuration, + params: RetrieveAnalyticsRuleParams, +) -> Result> { + let uri_str = format!( + "{}/analytics/rules/{ruleName}", + configuration.base_path, + ruleName = crate::apis::urlencode(params.rule_name) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -435,19 +531,33 @@ pub async fn retrieve_analytics_rule(configuration: &configuration::Configuratio let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsRule`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsRule`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::AnalyticsRule`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsRule`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve all analytics rules. Use the optional rule_tag filter to narrow down results. -pub async fn retrieve_analytics_rules(configuration: &configuration::Configuration, params: RetrieveAnalyticsRulesParams) -> Result, Error> { - +pub async fn retrieve_analytics_rules( + configuration: &configuration::Configuration, + params: RetrieveAnalyticsRulesParams, +) -> Result, Error> { let uri_str = format!("{}/analytics/rules", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -481,20 +591,38 @@ pub async fn retrieve_analytics_rules(configuration: &configuration::Configurati let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `Vec`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `Vec`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Upserts an analytics rule with the given name. -pub async fn upsert_analytics_rule(configuration: &configuration::Configuration, params: UpsertAnalyticsRuleParams) -> Result> { - - let uri_str = format!("{}/analytics/rules/{ruleName}", configuration.base_path, ruleName=crate::apis::urlencode(params.rule_name)); +pub async fn upsert_analytics_rule( + configuration: &configuration::Configuration, + params: UpsertAnalyticsRuleParams, +) -> Result> { + let uri_str = format!( + "{}/analytics/rules/{ruleName}", + configuration.base_path, + ruleName = crate::apis::urlencode(params.rule_name) + ); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -525,13 +653,24 @@ pub async fn upsert_analytics_rule(configuration: &configuration::Configuration, let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsRule`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsRule`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::AnalyticsRule`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsRule`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } - diff --git a/typesense_codegen/src/apis/collections_api.rs b/typesense_codegen/src/apis/collections_api.rs index b3151e9..03cb661 100644 --- a/typesense_codegen/src/apis/collections_api.rs +++ b/typesense_codegen/src/apis/collections_api.rs @@ -2,51 +2,49 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ - +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`create_collection`] #[derive(Clone, Debug)] pub struct CreateCollectionParams { /// The collection object to be created - pub collection_schema: models::CollectionSchema + pub collection_schema: models::CollectionSchema, } /// struct for passing parameters to the method [`delete_alias`] #[derive(Clone, Debug)] pub struct DeleteAliasParams { /// The name of the alias to delete - pub alias_name: String + pub alias_name: String, } /// struct for passing parameters to the method [`delete_collection`] #[derive(Clone, Debug)] pub struct DeleteCollectionParams { /// The name of the collection to delete - pub collection_name: String + pub collection_name: String, } /// struct for passing parameters to the method [`get_alias`] #[derive(Clone, Debug)] pub struct GetAliasParams { /// The name of the alias to retrieve - pub alias_name: String + pub alias_name: String, } /// struct for passing parameters to the method [`get_collection`] #[derive(Clone, Debug)] pub struct GetCollectionParams { /// The name of the collection to retrieve - pub collection_name: String + pub collection_name: String, } /// struct for passing parameters to the method [`get_collections`] @@ -54,7 +52,7 @@ pub struct GetCollectionParams { pub struct GetCollectionsParams { pub exclude_fields: Option, pub limit: Option, - pub offset: Option + pub offset: Option, } /// struct for passing parameters to the method [`update_collection`] @@ -63,7 +61,7 @@ pub struct UpdateCollectionParams { /// The name of the collection to update pub collection_name: String, /// The document object with fields to be updated - pub collection_update_schema: models::CollectionUpdateSchema + pub collection_update_schema: models::CollectionUpdateSchema, } /// struct for passing parameters to the method [`upsert_alias`] @@ -72,10 +70,9 @@ pub struct UpsertAliasParams { /// The name of the alias to create/update pub alias_name: String, /// Collection alias to be created/updated - pub collection_alias_schema: Option + pub collection_alias_schema: Option, } - /// struct for typed errors of method [`create_collection`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -149,12 +146,15 @@ pub enum UpsertAliasError { UnknownValue(serde_json::Value), } - /// When a collection is created, we give it a name and describe the fields that will be indexed from the documents added to the collection. -pub async fn create_collection(configuration: &configuration::Configuration, params: CreateCollectionParams) -> Result> { - +pub async fn create_collection( + configuration: &configuration::Configuration, + params: CreateCollectionParams, +) -> Result> { let uri_str = format!("{}/collections", configuration.base_path); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -184,20 +184,40 @@ pub async fn create_collection(configuration: &configuration::Configuration, par let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionResponse`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionResponse`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::CollectionResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionResponse`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } -pub async fn delete_alias(configuration: &configuration::Configuration, params: DeleteAliasParams) -> Result> { - - let uri_str = format!("{}/aliases/{aliasName}", configuration.base_path, aliasName=crate::apis::urlencode(params.alias_name)); - let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_alias( + configuration: &configuration::Configuration, + params: DeleteAliasParams, +) -> Result> { + let uri_str = format!( + "{}/aliases/{aliasName}", + configuration.base_path, + aliasName = crate::apis::urlencode(params.alias_name) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -226,21 +246,41 @@ pub async fn delete_alias(configuration: &configuration::Configuration, params: let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionAlias`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAlias`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::CollectionAlias`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAlias`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Permanently drops a collection. This action cannot be undone. For large collections, this might have an impact on read latencies. -pub async fn delete_collection(configuration: &configuration::Configuration, params: DeleteCollectionParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); - let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_collection( + configuration: &configuration::Configuration, + params: DeleteCollectionParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -269,20 +309,38 @@ pub async fn delete_collection(configuration: &configuration::Configuration, par let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionResponse`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionResponse`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::CollectionResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionResponse`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Find out which collection an alias points to by fetching it -pub async fn get_alias(configuration: &configuration::Configuration, params: GetAliasParams) -> Result> { - - let uri_str = format!("{}/aliases/{aliasName}", configuration.base_path, aliasName=crate::apis::urlencode(params.alias_name)); +pub async fn get_alias( + configuration: &configuration::Configuration, + params: GetAliasParams, +) -> Result> { + let uri_str = format!( + "{}/aliases/{aliasName}", + configuration.base_path, + aliasName = crate::apis::urlencode(params.alias_name) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -312,19 +370,32 @@ pub async fn get_alias(configuration: &configuration::Configuration, params: Get let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionAlias`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAlias`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::CollectionAlias`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAlias`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// List all aliases and the corresponding collections that they map to. -pub async fn get_aliases(configuration: &configuration::Configuration) -> Result> { - +pub async fn get_aliases( + configuration: &configuration::Configuration, +) -> Result> { let uri_str = format!("{}/aliases", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -355,20 +426,38 @@ pub async fn get_aliases(configuration: &configuration::Configuration) -> Result let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionAliasesResponse`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAliasesResponse`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::CollectionAliasesResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAliasesResponse`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve the details of a collection, given its name. -pub async fn get_collection(configuration: &configuration::Configuration, params: GetCollectionParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); +pub async fn get_collection( + configuration: &configuration::Configuration, + params: GetCollectionParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -398,19 +487,33 @@ pub async fn get_collection(configuration: &configuration::Configuration, params let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionResponse`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionResponse`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::CollectionResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionResponse`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Returns a summary of all your collections. The collections are returned sorted by creation date, with the most recent collections appearing first. -pub async fn get_collections(configuration: &configuration::Configuration, params: GetCollectionsParams) -> Result, Error> { - +pub async fn get_collections( + configuration: &configuration::Configuration, + params: GetCollectionsParams, +) -> Result, Error> { let uri_str = format!("{}/collections", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -450,21 +553,41 @@ pub async fn get_collections(configuration: &configuration::Configuration, param let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `Vec`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `Vec`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Update a collection's schema to modify the fields and their types. -pub async fn update_collection(configuration: &configuration::Configuration, params: UpdateCollectionParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); - let mut req_builder = configuration.client.request(reqwest::Method::PATCH, &uri_str); +pub async fn update_collection( + configuration: &configuration::Configuration, + params: UpdateCollectionParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::PATCH, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -494,20 +617,38 @@ pub async fn update_collection(configuration: &configuration::Configuration, par let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionUpdateSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionUpdateSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::CollectionUpdateSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionUpdateSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Create or update a collection alias. An alias is a virtual collection name that points to a real collection. If you're familiar with symbolic links on Linux, it's very similar to that. Aliases are useful when you want to reindex your data in the background on a new collection and switch your application to it without any changes to your code. -pub async fn upsert_alias(configuration: &configuration::Configuration, params: UpsertAliasParams) -> Result> { - - let uri_str = format!("{}/aliases/{aliasName}", configuration.base_path, aliasName=crate::apis::urlencode(params.alias_name)); +pub async fn upsert_alias( + configuration: &configuration::Configuration, + params: UpsertAliasParams, +) -> Result> { + let uri_str = format!( + "{}/aliases/{aliasName}", + configuration.base_path, + aliasName = crate::apis::urlencode(params.alias_name) + ); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -538,13 +679,24 @@ pub async fn upsert_alias(configuration: &configuration::Configuration, params: let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionAlias`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAlias`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::CollectionAlias`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAlias`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } - diff --git a/typesense_codegen/src/apis/conversations_api.rs b/typesense_codegen/src/apis/conversations_api.rs index 4e68ba7..8f6b5e3 100644 --- a/typesense_codegen/src/apis/conversations_api.rs +++ b/typesense_codegen/src/apis/conversations_api.rs @@ -2,36 +2,34 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ - +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`create_conversation_model`] #[derive(Clone, Debug)] pub struct CreateConversationModelParams { - pub conversation_model_create_schema: models::ConversationModelCreateSchema + pub conversation_model_create_schema: models::ConversationModelCreateSchema, } /// struct for passing parameters to the method [`delete_conversation_model`] #[derive(Clone, Debug)] pub struct DeleteConversationModelParams { /// The id of the conversation model to delete - pub model_id: String + pub model_id: String, } /// struct for passing parameters to the method [`retrieve_conversation_model`] #[derive(Clone, Debug)] pub struct RetrieveConversationModelParams { /// The id of the conversation model to retrieve - pub model_id: String + pub model_id: String, } /// struct for passing parameters to the method [`update_conversation_model`] @@ -39,10 +37,9 @@ pub struct RetrieveConversationModelParams { pub struct UpdateConversationModelParams { /// The id of the conversation model to update pub model_id: String, - pub conversation_model_update_schema: models::ConversationModelUpdateSchema + pub conversation_model_update_schema: models::ConversationModelUpdateSchema, } - /// struct for typed errors of method [`create_conversation_model`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -79,12 +76,15 @@ pub enum UpdateConversationModelError { UnknownValue(serde_json::Value), } - /// Create a Conversation Model -pub async fn create_conversation_model(configuration: &configuration::Configuration, params: CreateConversationModelParams) -> Result> { - +pub async fn create_conversation_model( + configuration: &configuration::Configuration, + params: CreateConversationModelParams, +) -> Result> { let uri_str = format!("{}/conversations/models", configuration.base_path); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -114,21 +114,41 @@ pub async fn create_conversation_model(configuration: &configuration::Configurat let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Delete a conversation model -pub async fn delete_conversation_model(configuration: &configuration::Configuration, params: DeleteConversationModelParams) -> Result> { - - let uri_str = format!("{}/conversations/models/{modelId}", configuration.base_path, modelId=crate::apis::urlencode(params.model_id)); - let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_conversation_model( + configuration: &configuration::Configuration, + params: DeleteConversationModelParams, +) -> Result> { + let uri_str = format!( + "{}/conversations/models/{modelId}", + configuration.base_path, + modelId = crate::apis::urlencode(params.model_id) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -157,19 +177,32 @@ pub async fn delete_conversation_model(configuration: &configuration::Configurat let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve all conversation models -pub async fn retrieve_all_conversation_models(configuration: &configuration::Configuration) -> Result, Error> { - +pub async fn retrieve_all_conversation_models( + configuration: &configuration::Configuration, +) -> Result, Error> { let uri_str = format!("{}/conversations/models", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -200,20 +233,39 @@ pub async fn retrieve_all_conversation_models(configuration: &configuration::Con let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `Vec`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `Vec`" + )))); + } } } else { let content = resp.text().await?; - let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + let entity: Option = + serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve a conversation model -pub async fn retrieve_conversation_model(configuration: &configuration::Configuration, params: RetrieveConversationModelParams) -> Result> { - - let uri_str = format!("{}/conversations/models/{modelId}", configuration.base_path, modelId=crate::apis::urlencode(params.model_id)); +pub async fn retrieve_conversation_model( + configuration: &configuration::Configuration, + params: RetrieveConversationModelParams, +) -> Result> { + let uri_str = format!( + "{}/conversations/models/{modelId}", + configuration.base_path, + modelId = crate::apis::urlencode(params.model_id) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -243,20 +295,38 @@ pub async fn retrieve_conversation_model(configuration: &configuration::Configur let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Update a conversation model -pub async fn update_conversation_model(configuration: &configuration::Configuration, params: UpdateConversationModelParams) -> Result> { - - let uri_str = format!("{}/conversations/models/{modelId}", configuration.base_path, modelId=crate::apis::urlencode(params.model_id)); +pub async fn update_conversation_model( + configuration: &configuration::Configuration, + params: UpdateConversationModelParams, +) -> Result> { + let uri_str = format!( + "{}/conversations/models/{modelId}", + configuration.base_path, + modelId = crate::apis::urlencode(params.model_id) + ); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -287,13 +357,24 @@ pub async fn update_conversation_model(configuration: &configuration::Configurat let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } - diff --git a/typesense_codegen/src/apis/curation_api.rs b/typesense_codegen/src/apis/curation_api.rs index 4600ec6..853f07a 100644 --- a/typesense_codegen/src/apis/curation_api.rs +++ b/typesense_codegen/src/apis/curation_api.rs @@ -2,17 +2,15 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ - +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`delete_search_override`] #[derive(Clone, Debug)] @@ -20,14 +18,14 @@ pub struct DeleteSearchOverrideParams { /// The name of the collection pub collection_name: String, /// The ID of the search override to delete - pub override_id: String + pub override_id: String, } /// struct for passing parameters to the method [`get_search_overrides`] #[derive(Clone, Debug)] pub struct GetSearchOverridesParams { /// The name of the collection - pub collection_name: String + pub collection_name: String, } /// struct for passing parameters to the method [`upsert_search_override`] @@ -38,10 +36,9 @@ pub struct UpsertSearchOverrideParams { /// The ID of the search override to create/update pub override_id: String, /// The search override object to be created/updated - pub search_override_schema: models::SearchOverrideSchema + pub search_override_schema: models::SearchOverrideSchema, } - /// struct for typed errors of method [`delete_search_override`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -65,11 +62,19 @@ pub enum UpsertSearchOverrideError { UnknownValue(serde_json::Value), } - -pub async fn delete_search_override(configuration: &configuration::Configuration, params: DeleteSearchOverrideParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), overrideId=crate::apis::urlencode(params.override_id)); - let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_search_override( + configuration: &configuration::Configuration, + params: DeleteSearchOverrideParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/overrides/{overrideId}", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name), + overrideId = crate::apis::urlencode(params.override_id) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -98,19 +103,37 @@ pub async fn delete_search_override(configuration: &configuration::Configuration let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } -pub async fn get_search_overrides(configuration: &configuration::Configuration, params: GetSearchOverridesParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/overrides", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); +pub async fn get_search_overrides( + configuration: &configuration::Configuration, + params: GetSearchOverridesParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/overrides", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -140,20 +163,39 @@ pub async fn get_search_overrides(configuration: &configuration::Configuration, let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverridesResponse`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverridesResponse`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SearchOverridesResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverridesResponse`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Create or update an override to promote certain documents over others. Using overrides, you can include or exclude specific documents for a given query. -pub async fn upsert_search_override(configuration: &configuration::Configuration, params: UpsertSearchOverrideParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), overrideId=crate::apis::urlencode(params.override_id)); +pub async fn upsert_search_override( + configuration: &configuration::Configuration, + params: UpsertSearchOverrideParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/overrides/{overrideId}", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name), + overrideId = crate::apis::urlencode(params.override_id) + ); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -184,13 +226,24 @@ pub async fn upsert_search_override(configuration: &configuration::Configuration let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverride`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SearchOverride`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } - diff --git a/typesense_codegen/src/apis/debug_api.rs b/typesense_codegen/src/apis/debug_api.rs index 7fb161c..2d90714 100644 --- a/typesense_codegen/src/apis/debug_api.rs +++ b/typesense_codegen/src/apis/debug_api.rs @@ -2,18 +2,15 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ - +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration, ContentType}; - /// struct for typed errors of method [`debug`] #[derive(Debug, Clone, Serialize, Deserialize)] @@ -22,10 +19,10 @@ pub enum DebugError { UnknownValue(serde_json::Value), } - /// Print debugging information -pub async fn debug(configuration: &configuration::Configuration) -> Result> { - +pub async fn debug( + configuration: &configuration::Configuration, +) -> Result> { let uri_str = format!("{}/debug", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -56,13 +53,24 @@ pub async fn debug(configuration: &configuration::Configuration) -> Result serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::Debug200Response`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::Debug200Response`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::Debug200Response`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::Debug200Response`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } - diff --git a/typesense_codegen/src/apis/documents_api.rs b/typesense_codegen/src/apis/documents_api.rs index 5693578..3fcc069 100644 --- a/typesense_codegen/src/apis/documents_api.rs +++ b/typesense_codegen/src/apis/documents_api.rs @@ -2,17 +2,15 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ - +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`delete_document`] #[derive(Clone, Debug)] @@ -20,7 +18,7 @@ pub struct DeleteDocumentParams { /// The name of the collection to search for the document under pub collection_name: String, /// The Document ID - pub document_id: String + pub document_id: String, } /// struct for passing parameters to the method [`delete_documents`] @@ -31,7 +29,7 @@ pub struct DeleteDocumentsParams { pub filter_by: Option, pub batch_size: Option, pub ignore_not_found: Option, - pub truncate: Option + pub truncate: Option, } /// struct for passing parameters to the method [`delete_search_override`] @@ -40,7 +38,7 @@ pub struct DeleteSearchOverrideParams { /// The name of the collection pub collection_name: String, /// The ID of the search override to delete - pub override_id: String + pub override_id: String, } /// struct for passing parameters to the method [`export_documents`] @@ -50,7 +48,7 @@ pub struct ExportDocumentsParams { pub collection_name: String, pub filter_by: Option, pub include_fields: Option, - pub exclude_fields: Option + pub exclude_fields: Option, } /// struct for passing parameters to the method [`get_document`] @@ -59,7 +57,7 @@ pub struct GetDocumentParams { /// The name of the collection to search for the document under pub collection_name: String, /// The Document ID - pub document_id: String + pub document_id: String, } /// struct for passing parameters to the method [`get_search_override`] @@ -68,14 +66,14 @@ pub struct GetSearchOverrideParams { /// The name of the collection pub collection_name: String, /// The id of the search override - pub override_id: String + pub override_id: String, } /// struct for passing parameters to the method [`get_search_overrides`] #[derive(Clone, Debug)] pub struct GetSearchOverridesParams { /// The name of the collection - pub collection_name: String + pub collection_name: String, } /// struct for passing parameters to the method [`import_documents`] @@ -90,7 +88,7 @@ pub struct ImportDocumentsParams { pub remote_embedding_batch_size: Option, pub return_doc: Option, pub action: Option, - pub dirty_values: Option + pub dirty_values: Option, } /// struct for passing parameters to the method [`index_document`] @@ -103,7 +101,7 @@ pub struct IndexDocumentParams { /// Additional action to perform pub action: Option, /// Dealing with Dirty Data - pub dirty_values: Option + pub dirty_values: Option, } /// struct for passing parameters to the method [`multi_search`] @@ -173,7 +171,7 @@ pub struct MultiSearchParams { pub conversation: Option, pub conversation_model_id: Option, pub conversation_id: Option, - pub multi_search_searches_parameter: Option + pub multi_search_searches_parameter: Option, } /// struct for passing parameters to the method [`search_collection`] @@ -251,7 +249,7 @@ pub struct SearchCollectionParams { pub voice_query: Option, pub conversation: Option, pub conversation_model_id: Option, - pub conversation_id: Option + pub conversation_id: Option, } /// struct for passing parameters to the method [`update_document`] @@ -264,7 +262,7 @@ pub struct UpdateDocumentParams { /// The document object with fields to be updated pub body: serde_json::Value, /// Dealing with Dirty Data - pub dirty_values: Option + pub dirty_values: Option, } /// struct for passing parameters to the method [`update_documents`] @@ -274,7 +272,7 @@ pub struct UpdateDocumentsParams { pub collection_name: String, /// The document fields to be updated pub body: serde_json::Value, - pub filter_by: Option + pub filter_by: Option, } /// struct for passing parameters to the method [`upsert_search_override`] @@ -285,10 +283,9 @@ pub struct UpsertSearchOverrideParams { /// The ID of the search override to create/update pub override_id: String, /// The search override object to be created/updated - pub search_override_schema: models::SearchOverrideSchema + pub search_override_schema: models::SearchOverrideSchema, } - /// struct for typed errors of method [`delete_document`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -402,12 +399,20 @@ pub enum UpsertSearchOverrideError { UnknownValue(serde_json::Value), } - /// Delete an individual document from a collection by using its ID. -pub async fn delete_document(configuration: &configuration::Configuration, params: DeleteDocumentParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/documents/{documentId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), documentId=crate::apis::urlencode(params.document_id)); - let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_document( + configuration: &configuration::Configuration, + params: DeleteDocumentParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/documents/{documentId}", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name), + documentId = crate::apis::urlencode(params.document_id) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -436,21 +441,41 @@ pub async fn delete_document(configuration: &configuration::Configuration, param let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `serde_json::Value`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `serde_json::Value`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Delete a bunch of documents that match a specific filter condition. Use the `batch_size` parameter to control the number of documents that should deleted at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. -pub async fn delete_documents(configuration: &configuration::Configuration, params: DeleteDocumentsParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/documents", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); - let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_documents( + configuration: &configuration::Configuration, + params: DeleteDocumentsParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/documents", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); if let Some(ref param_value) = params.filter_by { req_builder = req_builder.query(&[("filter_by", ¶m_value.to_string())]); @@ -491,20 +516,41 @@ pub async fn delete_documents(configuration: &configuration::Configuration, para let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::DeleteDocuments200Response`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::DeleteDocuments200Response`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::DeleteDocuments200Response`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::DeleteDocuments200Response`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } -pub async fn delete_search_override(configuration: &configuration::Configuration, params: DeleteSearchOverrideParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), overrideId=crate::apis::urlencode(params.override_id)); - let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_search_override( + configuration: &configuration::Configuration, + params: DeleteSearchOverrideParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/overrides/{overrideId}", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name), + overrideId = crate::apis::urlencode(params.override_id) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -533,20 +579,38 @@ pub async fn delete_search_override(configuration: &configuration::Configuration let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Export all documents in a collection in JSON lines format. -pub async fn export_documents(configuration: &configuration::Configuration, params: ExportDocumentsParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/documents/export", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); +pub async fn export_documents( + configuration: &configuration::Configuration, + params: ExportDocumentsParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/documents/export", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref param_value) = params.filter_by { @@ -585,19 +649,34 @@ pub async fn export_documents(configuration: &configuration::Configuration, para let content = resp.text().await?; match content_type { ContentType::Json | ContentType::Text => return Ok(content), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `String`")))), + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `String`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Fetch an individual document from a collection by using its ID. -pub async fn get_document(configuration: &configuration::Configuration, params: GetDocumentParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/documents/{documentId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), documentId=crate::apis::urlencode(params.document_id)); +pub async fn get_document( + configuration: &configuration::Configuration, + params: GetDocumentParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/documents/{documentId}", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name), + documentId = crate::apis::urlencode(params.document_id) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -627,20 +706,39 @@ pub async fn get_document(configuration: &configuration::Configuration, params: let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `serde_json::Value`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `serde_json::Value`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve the details of a search override, given its id. -pub async fn get_search_override(configuration: &configuration::Configuration, params: GetSearchOverrideParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), overrideId=crate::apis::urlencode(params.override_id)); +pub async fn get_search_override( + configuration: &configuration::Configuration, + params: GetSearchOverrideParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/overrides/{overrideId}", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name), + overrideId = crate::apis::urlencode(params.override_id) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -670,19 +768,37 @@ pub async fn get_search_override(configuration: &configuration::Configuration, p let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverride`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SearchOverride`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } -pub async fn get_search_overrides(configuration: &configuration::Configuration, params: GetSearchOverridesParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/overrides", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); +pub async fn get_search_overrides( + configuration: &configuration::Configuration, + params: GetSearchOverridesParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/overrides", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -712,21 +828,41 @@ pub async fn get_search_overrides(configuration: &configuration::Configuration, let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverridesResponse`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverridesResponse`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SearchOverridesResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverridesResponse`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// The documents to be imported must be formatted in a newline delimited JSON structure. You can feed the output file from a Typesense export operation directly as import. -pub async fn import_documents(configuration: &configuration::Configuration, params: ImportDocumentsParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/documents/import", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); +pub async fn import_documents( + configuration: &configuration::Configuration, + params: ImportDocumentsParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/documents/import", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); if let Some(ref param_value) = params.batch_size { req_builder = req_builder.query(&[("batch_size", ¶m_value.to_string())]); @@ -735,7 +871,8 @@ pub async fn import_documents(configuration: &configuration::Configuration, para req_builder = req_builder.query(&[("return_id", ¶m_value.to_string())]); } if let Some(ref param_value) = params.remote_embedding_batch_size { - req_builder = req_builder.query(&[("remote_embedding_batch_size", ¶m_value.to_string())]); + req_builder = + req_builder.query(&[("remote_embedding_batch_size", ¶m_value.to_string())]); } if let Some(ref param_value) = params.return_doc { req_builder = req_builder.query(&[("return_doc", ¶m_value.to_string())]); @@ -757,7 +894,9 @@ pub async fn import_documents(configuration: &configuration::Configuration, para }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - req_builder = req_builder.header(reqwest::header::CONTENT_TYPE, "text/plain").body(params.body); + req_builder = req_builder + .header(reqwest::header::CONTENT_TYPE, "text/plain") + .body(params.body); let req = req_builder.build()?; let resp = configuration.client.execute(req).await?; @@ -774,20 +913,36 @@ pub async fn import_documents(configuration: &configuration::Configuration, para let content = resp.text().await?; match content_type { ContentType::Json | ContentType::Text => return Ok(content), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `String`")))), + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `String`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// A document to be indexed in a given collection must conform to the schema of the collection. -pub async fn index_document(configuration: &configuration::Configuration, params: IndexDocumentParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/documents", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); +pub async fn index_document( + configuration: &configuration::Configuration, + params: IndexDocumentParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/documents", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); if let Some(ref param_value) = params.action { req_builder = req_builder.query(&[("action", ¶m_value.to_string())]); @@ -823,21 +978,37 @@ pub async fn index_document(configuration: &configuration::Configuration, params let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `serde_json::Value`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `serde_json::Value`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// This is especially useful to avoid round-trip network latencies incurred otherwise if each of these requests are sent in separate HTTP requests. You can also use this feature to do a federated search across multiple collections in a single HTTP request. -pub async fn multi_search(configuration: &configuration::Configuration, params: MultiSearchParams) -> Result> { - +pub async fn multi_search( + configuration: &configuration::Configuration, + params: MultiSearchParams, +) -> Result> { let uri_str = format!("{}/multi_search", configuration.base_path); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); if let Some(ref param_value) = params.q { req_builder = req_builder.query(&[("q", ¶m_value.to_string())]); @@ -912,7 +1083,8 @@ pub async fn multi_search(configuration: &configuration::Configuration, params: req_builder = req_builder.query(&[("highlight_full_fields", ¶m_value.to_string())]); } if let Some(ref param_value) = params.highlight_affix_num_tokens { - req_builder = req_builder.query(&[("highlight_affix_num_tokens", ¶m_value.to_string())]); + req_builder = + req_builder.query(&[("highlight_affix_num_tokens", ¶m_value.to_string())]); } if let Some(ref param_value) = params.highlight_start_tag { req_builder = req_builder.query(&[("highlight_start_tag", ¶m_value.to_string())]); @@ -933,7 +1105,10 @@ pub async fn multi_search(configuration: &configuration::Configuration, params: req_builder = req_builder.query(&[("typo_tokens_threshold", ¶m_value.to_string())]); } if let Some(ref param_value) = params.enable_typos_for_alpha_numerical_tokens { - req_builder = req_builder.query(&[("enable_typos_for_alpha_numerical_tokens", ¶m_value.to_string())]); + req_builder = req_builder.query(&[( + "enable_typos_for_alpha_numerical_tokens", + ¶m_value.to_string(), + )]); } if let Some(ref param_value) = params.filter_curated_hits { req_builder = req_builder.query(&[("filter_curated_hits", ¶m_value.to_string())]); @@ -978,10 +1153,14 @@ pub async fn multi_search(configuration: &configuration::Configuration, params: req_builder = req_builder.query(&[("prioritize_token_position", ¶m_value.to_string())]); } if let Some(ref param_value) = params.prioritize_num_matching_fields { - req_builder = req_builder.query(&[("prioritize_num_matching_fields", ¶m_value.to_string())]); + req_builder = + req_builder.query(&[("prioritize_num_matching_fields", ¶m_value.to_string())]); } if let Some(ref param_value) = params.enable_typos_for_numerical_tokens { - req_builder = req_builder.query(&[("enable_typos_for_numerical_tokens", ¶m_value.to_string())]); + req_builder = req_builder.query(&[( + "enable_typos_for_numerical_tokens", + ¶m_value.to_string(), + )]); } if let Some(ref param_value) = params.exhaustive_search { req_builder = req_builder.query(&[("exhaustive_search", ¶m_value.to_string())]); @@ -1005,10 +1184,12 @@ pub async fn multi_search(configuration: &configuration::Configuration, params: req_builder = req_builder.query(&[("vector_query", ¶m_value.to_string())]); } if let Some(ref param_value) = params.remote_embedding_timeout_ms { - req_builder = req_builder.query(&[("remote_embedding_timeout_ms", ¶m_value.to_string())]); + req_builder = + req_builder.query(&[("remote_embedding_timeout_ms", ¶m_value.to_string())]); } if let Some(ref param_value) = params.remote_embedding_num_tries { - req_builder = req_builder.query(&[("remote_embedding_num_tries", ¶m_value.to_string())]); + req_builder = + req_builder.query(&[("remote_embedding_num_tries", ¶m_value.to_string())]); } if let Some(ref param_value) = params.facet_strategy { req_builder = req_builder.query(&[("facet_strategy", ¶m_value.to_string())]); @@ -1059,20 +1240,38 @@ pub async fn multi_search(configuration: &configuration::Configuration, params: let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `serde_json::Value`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `serde_json::Value`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Search for documents in a collection that match the search criteria. -pub async fn search_collection serde::Deserialize<'de> + Serialize>(configuration: &configuration::Configuration, params: SearchCollectionParams) -> Result, Error> { - - let uri_str = format!("{}/collections/{collectionName}/documents/search", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); +pub async fn search_collection serde::Deserialize<'de> + Serialize>( + configuration: &configuration::Configuration, + params: SearchCollectionParams, +) -> Result, Error> { + let uri_str = format!( + "{}/collections/{collectionName}/documents/search", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref param_value) = params.q { @@ -1157,7 +1356,8 @@ pub async fn search_collection serde::Deserialize<'de> + Serialize>( req_builder = req_builder.query(&[("highlight_full_fields", ¶m_value.to_string())]); } if let Some(ref param_value) = params.highlight_affix_num_tokens { - req_builder = req_builder.query(&[("highlight_affix_num_tokens", ¶m_value.to_string())]); + req_builder = + req_builder.query(&[("highlight_affix_num_tokens", ¶m_value.to_string())]); } if let Some(ref param_value) = params.highlight_start_tag { req_builder = req_builder.query(&[("highlight_start_tag", ¶m_value.to_string())]); @@ -1187,7 +1387,10 @@ pub async fn search_collection serde::Deserialize<'de> + Serialize>( req_builder = req_builder.query(&[("typo_tokens_threshold", ¶m_value.to_string())]); } if let Some(ref param_value) = params.enable_typos_for_alpha_numerical_tokens { - req_builder = req_builder.query(&[("enable_typos_for_alpha_numerical_tokens", ¶m_value.to_string())]); + req_builder = req_builder.query(&[( + "enable_typos_for_alpha_numerical_tokens", + ¶m_value.to_string(), + )]); } if let Some(ref param_value) = params.filter_curated_hits { req_builder = req_builder.query(&[("filter_curated_hits", ¶m_value.to_string())]); @@ -1235,10 +1438,14 @@ pub async fn search_collection serde::Deserialize<'de> + Serialize>( req_builder = req_builder.query(&[("prioritize_token_position", ¶m_value.to_string())]); } if let Some(ref param_value) = params.prioritize_num_matching_fields { - req_builder = req_builder.query(&[("prioritize_num_matching_fields", ¶m_value.to_string())]); + req_builder = + req_builder.query(&[("prioritize_num_matching_fields", ¶m_value.to_string())]); } if let Some(ref param_value) = params.enable_typos_for_numerical_tokens { - req_builder = req_builder.query(&[("enable_typos_for_numerical_tokens", ¶m_value.to_string())]); + req_builder = req_builder.query(&[( + "enable_typos_for_numerical_tokens", + ¶m_value.to_string(), + )]); } if let Some(ref param_value) = params.exhaustive_search { req_builder = req_builder.query(&[("exhaustive_search", ¶m_value.to_string())]); @@ -1262,10 +1469,12 @@ pub async fn search_collection serde::Deserialize<'de> + Serialize>( req_builder = req_builder.query(&[("vector_query", ¶m_value.to_string())]); } if let Some(ref param_value) = params.remote_embedding_timeout_ms { - req_builder = req_builder.query(&[("remote_embedding_timeout_ms", ¶m_value.to_string())]); + req_builder = + req_builder.query(&[("remote_embedding_timeout_ms", ¶m_value.to_string())]); } if let Some(ref param_value) = params.remote_embedding_num_tries { - req_builder = req_builder.query(&[("remote_embedding_num_tries", ¶m_value.to_string())]); + req_builder = + req_builder.query(&[("remote_embedding_num_tries", ¶m_value.to_string())]); } if let Some(ref param_value) = params.facet_strategy { req_builder = req_builder.query(&[("facet_strategy", ¶m_value.to_string())]); @@ -1315,21 +1524,42 @@ pub async fn search_collection serde::Deserialize<'de> + Serialize>( let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchResult`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchResult`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SearchResult`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SearchResult`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Update an individual document from a collection by using its ID. The update can be partial. -pub async fn update_document(configuration: &configuration::Configuration, params: UpdateDocumentParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/documents/{documentId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), documentId=crate::apis::urlencode(params.document_id)); - let mut req_builder = configuration.client.request(reqwest::Method::PATCH, &uri_str); +pub async fn update_document( + configuration: &configuration::Configuration, + params: UpdateDocumentParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/documents/{documentId}", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name), + documentId = crate::apis::urlencode(params.document_id) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::PATCH, &uri_str); if let Some(ref param_value) = params.dirty_values { req_builder = req_builder.query(&[("dirty_values", ¶m_value.to_string())]); @@ -1362,21 +1592,41 @@ pub async fn update_document(configuration: &configuration::Configuration, param let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `serde_json::Value`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `serde_json::Value`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// The filter_by query parameter is used to filter to specify a condition against which the documents are matched. The request body contains the fields that should be updated for any documents that match the filter condition. This endpoint is only available if the Typesense server is version `0.25.0.rc12` or later. -pub async fn update_documents(configuration: &configuration::Configuration, params: UpdateDocumentsParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/documents", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); - let mut req_builder = configuration.client.request(reqwest::Method::PATCH, &uri_str); +pub async fn update_documents( + configuration: &configuration::Configuration, + params: UpdateDocumentsParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/documents", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::PATCH, &uri_str); if let Some(ref param_value) = params.filter_by { req_builder = req_builder.query(&[("filter_by", ¶m_value.to_string())]); @@ -1409,20 +1659,39 @@ pub async fn update_documents(configuration: &configuration::Configuration, para let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::UpdateDocuments200Response`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::UpdateDocuments200Response`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::UpdateDocuments200Response`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::UpdateDocuments200Response`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Create or update an override to promote certain documents over others. Using overrides, you can include or exclude specific documents for a given query. -pub async fn upsert_search_override(configuration: &configuration::Configuration, params: UpsertSearchOverrideParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), overrideId=crate::apis::urlencode(params.override_id)); +pub async fn upsert_search_override( + configuration: &configuration::Configuration, + params: UpsertSearchOverrideParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/overrides/{overrideId}", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name), + overrideId = crate::apis::urlencode(params.override_id) + ); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -1453,13 +1722,24 @@ pub async fn upsert_search_override(configuration: &configuration::Configuration let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverride`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SearchOverride`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } - diff --git a/typesense_codegen/src/apis/health_api.rs b/typesense_codegen/src/apis/health_api.rs index 595b323..d615a43 100644 --- a/typesense_codegen/src/apis/health_api.rs +++ b/typesense_codegen/src/apis/health_api.rs @@ -2,18 +2,15 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ - +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration, ContentType}; - /// struct for typed errors of method [`health`] #[derive(Debug, Clone, Serialize, Deserialize)] @@ -22,10 +19,10 @@ pub enum HealthError { UnknownValue(serde_json::Value), } - /// Checks if Typesense server is ready to accept requests. -pub async fn health(configuration: &configuration::Configuration) -> Result> { - +pub async fn health( + configuration: &configuration::Configuration, +) -> Result> { let uri_str = format!("{}/health", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -56,13 +53,24 @@ pub async fn health(configuration: &configuration::Configuration) -> Result serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::HealthStatus`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::HealthStatus`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::HealthStatus`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::HealthStatus`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } - diff --git a/typesense_codegen/src/apis/keys_api.rs b/typesense_codegen/src/apis/keys_api.rs index be85909..dc1b6a7 100644 --- a/typesense_codegen/src/apis/keys_api.rs +++ b/typesense_codegen/src/apis/keys_api.rs @@ -2,40 +2,37 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ - +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`create_key`] #[derive(Clone, Debug)] pub struct CreateKeyParams { /// The object that describes API key scope - pub api_key_schema: Option + pub api_key_schema: Option, } /// struct for passing parameters to the method [`delete_key`] #[derive(Clone, Debug)] pub struct DeleteKeyParams { /// The ID of the key to delete - pub key_id: i64 + pub key_id: i64, } /// struct for passing parameters to the method [`get_key`] #[derive(Clone, Debug)] pub struct GetKeyParams { /// The ID of the key to retrieve - pub key_id: i64 + pub key_id: i64, } - /// struct for typed errors of method [`create_key`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -69,12 +66,15 @@ pub enum GetKeysError { UnknownValue(serde_json::Value), } - /// Create an API Key with fine-grain access control. You can restrict access on both a per-collection and per-action level. The generated key is returned only during creation. You want to store this key carefully in a secure place. -pub async fn create_key(configuration: &configuration::Configuration, params: CreateKeyParams) -> Result> { - +pub async fn create_key( + configuration: &configuration::Configuration, + params: CreateKeyParams, +) -> Result> { let uri_str = format!("{}/keys", configuration.base_path); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -104,20 +104,40 @@ pub async fn create_key(configuration: &configuration::Configuration, params: Cr let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ApiKey`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ApiKey`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::ApiKey`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::ApiKey`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } -pub async fn delete_key(configuration: &configuration::Configuration, params: DeleteKeyParams) -> Result> { - - let uri_str = format!("{}/keys/{keyId}", configuration.base_path, keyId=params.key_id); - let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_key( + configuration: &configuration::Configuration, + params: DeleteKeyParams, +) -> Result> { + let uri_str = format!( + "{}/keys/{keyId}", + configuration.base_path, + keyId = params.key_id + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -146,20 +166,38 @@ pub async fn delete_key(configuration: &configuration::Configuration, params: De let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ApiKeyDeleteResponse`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ApiKeyDeleteResponse`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::ApiKeyDeleteResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::ApiKeyDeleteResponse`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve (metadata about) a key. Only the key prefix is returned when you retrieve a key. Due to security reasons, only the create endpoint returns the full API key. -pub async fn get_key(configuration: &configuration::Configuration, params: GetKeyParams) -> Result> { - - let uri_str = format!("{}/keys/{keyId}", configuration.base_path, keyId=params.key_id); +pub async fn get_key( + configuration: &configuration::Configuration, + params: GetKeyParams, +) -> Result> { + let uri_str = format!( + "{}/keys/{keyId}", + configuration.base_path, + keyId = params.key_id + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -189,18 +227,31 @@ pub async fn get_key(configuration: &configuration::Configuration, params: GetKe let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ApiKey`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ApiKey`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::ApiKey`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::ApiKey`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } -pub async fn get_keys(configuration: &configuration::Configuration) -> Result> { - +pub async fn get_keys( + configuration: &configuration::Configuration, +) -> Result> { let uri_str = format!("{}/keys", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -231,13 +282,24 @@ pub async fn get_keys(configuration: &configuration::Configuration) -> Result serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ApiKeysResponse`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ApiKeysResponse`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::ApiKeysResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::ApiKeysResponse`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } - diff --git a/typesense_codegen/src/apis/nl_search_models_api.rs b/typesense_codegen/src/apis/nl_search_models_api.rs index e88bea3..2672a9b 100644 --- a/typesense_codegen/src/apis/nl_search_models_api.rs +++ b/typesense_codegen/src/apis/nl_search_models_api.rs @@ -2,37 +2,35 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ - +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`create_nl_search_model`] #[derive(Clone, Debug)] pub struct CreateNlSearchModelParams { /// The NL search model to be created - pub nl_search_model_create_schema: models::NlSearchModelCreateSchema + pub nl_search_model_create_schema: models::NlSearchModelCreateSchema, } /// struct for passing parameters to the method [`delete_nl_search_model`] #[derive(Clone, Debug)] pub struct DeleteNlSearchModelParams { /// The ID of the NL search model to delete - pub model_id: String + pub model_id: String, } /// struct for passing parameters to the method [`retrieve_nl_search_model`] #[derive(Clone, Debug)] pub struct RetrieveNlSearchModelParams { /// The ID of the NL search model to retrieve - pub model_id: String + pub model_id: String, } /// struct for passing parameters to the method [`update_nl_search_model`] @@ -41,10 +39,9 @@ pub struct UpdateNlSearchModelParams { /// The ID of the NL search model to update pub model_id: String, /// The NL search model fields to update - pub body: models::NlSearchModelCreateSchema + pub body: models::NlSearchModelCreateSchema, } - /// struct for typed errors of method [`create_nl_search_model`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -85,12 +82,15 @@ pub enum UpdateNlSearchModelError { UnknownValue(serde_json::Value), } - /// Create a new NL search model. -pub async fn create_nl_search_model(configuration: &configuration::Configuration, params: CreateNlSearchModelParams) -> Result> { - +pub async fn create_nl_search_model( + configuration: &configuration::Configuration, + params: CreateNlSearchModelParams, +) -> Result> { let uri_str = format!("{}/nl_search_models", configuration.base_path); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -120,21 +120,41 @@ pub async fn create_nl_search_model(configuration: &configuration::Configuration let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::NlSearchModelSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::NlSearchModelSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Delete a specific NL search model by its ID. -pub async fn delete_nl_search_model(configuration: &configuration::Configuration, params: DeleteNlSearchModelParams) -> Result> { - - let uri_str = format!("{}/nl_search_models/{modelId}", configuration.base_path, modelId=crate::apis::urlencode(params.model_id)); - let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_nl_search_model( + configuration: &configuration::Configuration, + params: DeleteNlSearchModelParams, +) -> Result> { + let uri_str = format!( + "{}/nl_search_models/{modelId}", + configuration.base_path, + modelId = crate::apis::urlencode(params.model_id) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -163,19 +183,32 @@ pub async fn delete_nl_search_model(configuration: &configuration::Configuration let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::NlSearchModelDeleteSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelDeleteSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::NlSearchModelDeleteSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelDeleteSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve all NL search models. -pub async fn retrieve_all_nl_search_models(configuration: &configuration::Configuration) -> Result, Error> { - +pub async fn retrieve_all_nl_search_models( + configuration: &configuration::Configuration, +) -> Result, Error> { let uri_str = format!("{}/nl_search_models", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -206,20 +239,38 @@ pub async fn retrieve_all_nl_search_models(configuration: &configuration::Config let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `Vec`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `Vec`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve a specific NL search model by its ID. -pub async fn retrieve_nl_search_model(configuration: &configuration::Configuration, params: RetrieveNlSearchModelParams) -> Result> { - - let uri_str = format!("{}/nl_search_models/{modelId}", configuration.base_path, modelId=crate::apis::urlencode(params.model_id)); +pub async fn retrieve_nl_search_model( + configuration: &configuration::Configuration, + params: RetrieveNlSearchModelParams, +) -> Result> { + let uri_str = format!( + "{}/nl_search_models/{modelId}", + configuration.base_path, + modelId = crate::apis::urlencode(params.model_id) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -249,20 +300,38 @@ pub async fn retrieve_nl_search_model(configuration: &configuration::Configurati let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::NlSearchModelSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::NlSearchModelSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Update an existing NL search model. -pub async fn update_nl_search_model(configuration: &configuration::Configuration, params: UpdateNlSearchModelParams) -> Result> { - - let uri_str = format!("{}/nl_search_models/{modelId}", configuration.base_path, modelId=crate::apis::urlencode(params.model_id)); +pub async fn update_nl_search_model( + configuration: &configuration::Configuration, + params: UpdateNlSearchModelParams, +) -> Result> { + let uri_str = format!( + "{}/nl_search_models/{modelId}", + configuration.base_path, + modelId = crate::apis::urlencode(params.model_id) + ); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -293,13 +362,24 @@ pub async fn update_nl_search_model(configuration: &configuration::Configuration let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::NlSearchModelSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::NlSearchModelSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } - diff --git a/typesense_codegen/src/apis/operations_api.rs b/typesense_codegen/src/apis/operations_api.rs index 4f88281..e111439 100644 --- a/typesense_codegen/src/apis/operations_api.rs +++ b/typesense_codegen/src/apis/operations_api.rs @@ -2,32 +2,29 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ - +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`take_snapshot`] #[derive(Clone, Debug)] pub struct TakeSnapshotParams { /// The directory on the server where the snapshot should be saved. - pub snapshot_path: String + pub snapshot_path: String, } /// struct for passing parameters to the method [`toggle_slow_request_log`] #[derive(Clone, Debug)] pub struct ToggleSlowRequestLogParams { - pub toggle_slow_request_log_request: Option + pub toggle_slow_request_log_request: Option, } - /// struct for typed errors of method [`clear_cache`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -84,12 +81,14 @@ pub enum VoteError { UnknownValue(serde_json::Value), } - /// Clear the cached responses of search requests that are sent with `use_cache` parameter in the LRU cache. -pub async fn clear_cache(configuration: &configuration::Configuration) -> Result> { - +pub async fn clear_cache( + configuration: &configuration::Configuration, +) -> Result> { let uri_str = format!("{}/operations/cache/clear", configuration.base_path); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -118,21 +117,36 @@ pub async fn clear_cache(configuration: &configuration::Configuration) -> Result let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Typesense uses RocksDB to store your documents on the disk. If you do frequent writes or updates, you could benefit from running a compaction of the underlying RocksDB database. This could reduce the size of the database and decrease read latency. While the database will not block during this operation, we recommend running it during off-peak hours. -pub async fn compact_db(configuration: &configuration::Configuration) -> Result> { - +pub async fn compact_db( + configuration: &configuration::Configuration, +) -> Result> { let uri_str = format!("{}/operations/db/compact", configuration.base_path); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -161,19 +175,32 @@ pub async fn compact_db(configuration: &configuration::Configuration) -> Result< let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Returns the status of any ongoing schema change operations. If no schema changes are in progress, returns an empty response. -pub async fn get_schema_changes(configuration: &configuration::Configuration) -> Result, Error> { - +pub async fn get_schema_changes( + configuration: &configuration::Configuration, +) -> Result, Error> { let uri_str = format!("{}/operations/schema_changes", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -204,19 +231,32 @@ pub async fn get_schema_changes(configuration: &configuration::Configuration) -> let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `Vec`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `Vec`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve the stats about API endpoints. -pub async fn retrieve_api_stats(configuration: &configuration::Configuration) -> Result> { - +pub async fn retrieve_api_stats( + configuration: &configuration::Configuration, +) -> Result> { let uri_str = format!("{}/stats.json", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -247,19 +287,32 @@ pub async fn retrieve_api_stats(configuration: &configuration::Configuration) -> let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ApiStatsResponse`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ApiStatsResponse`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::ApiStatsResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::ApiStatsResponse`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve the metrics. -pub async fn retrieve_metrics(configuration: &configuration::Configuration) -> Result> { - +pub async fn retrieve_metrics( + configuration: &configuration::Configuration, +) -> Result> { let uri_str = format!("{}/metrics.json", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -290,21 +343,37 @@ pub async fn retrieve_metrics(configuration: &configuration::Configuration) -> R let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `serde_json::Value`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `serde_json::Value`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Creates a point-in-time snapshot of a Typesense node's state and data in the specified directory. You can then backup the snapshot directory that gets created and later restore it as a data directory, as needed. -pub async fn take_snapshot(configuration: &configuration::Configuration, params: TakeSnapshotParams) -> Result> { - +pub async fn take_snapshot( + configuration: &configuration::Configuration, + params: TakeSnapshotParams, +) -> Result> { let uri_str = format!("{}/operations/snapshot", configuration.base_path); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); req_builder = req_builder.query(&[("snapshot_path", ¶ms.snapshot_path.to_string())]); if let Some(ref user_agent) = configuration.user_agent { @@ -334,21 +403,37 @@ pub async fn take_snapshot(configuration: &configuration::Configuration, params: let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Enable logging of requests that take over a defined threshold of time. Default is `-1` which disables slow request logging. Slow requests are logged to the primary log file, with the prefix SLOW REQUEST. -pub async fn toggle_slow_request_log(configuration: &configuration::Configuration, params: ToggleSlowRequestLogParams) -> Result> { - +pub async fn toggle_slow_request_log( + configuration: &configuration::Configuration, + params: ToggleSlowRequestLogParams, +) -> Result> { let uri_str = format!("{}/config", configuration.base_path); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -378,21 +463,36 @@ pub async fn toggle_slow_request_log(configuration: &configuration::Configuratio let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Triggers a follower node to initiate the raft voting process, which triggers leader re-election. The follower node that you run this operation against will become the new leader, once this command succeeds. -pub async fn vote(configuration: &configuration::Configuration) -> Result> { - +pub async fn vote( + configuration: &configuration::Configuration, +) -> Result> { let uri_str = format!("{}/operations/vote", configuration.base_path); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -421,13 +521,24 @@ pub async fn vote(configuration: &configuration::Configuration) -> Result serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } - diff --git a/typesense_codegen/src/apis/override_api.rs b/typesense_codegen/src/apis/override_api.rs index d05d16f..58b33a3 100644 --- a/typesense_codegen/src/apis/override_api.rs +++ b/typesense_codegen/src/apis/override_api.rs @@ -2,17 +2,15 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ - +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`get_search_override`] #[derive(Clone, Debug)] @@ -20,10 +18,9 @@ pub struct GetSearchOverrideParams { /// The name of the collection pub collection_name: String, /// The id of the search override - pub override_id: String + pub override_id: String, } - /// struct for typed errors of method [`get_search_override`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -31,11 +28,17 @@ pub enum GetSearchOverrideError { UnknownValue(serde_json::Value), } - /// Retrieve the details of a search override, given its id. -pub async fn get_search_override(configuration: &configuration::Configuration, params: GetSearchOverrideParams) -> Result> { - - let uri_str = format!("{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), overrideId=crate::apis::urlencode(params.override_id)); +pub async fn get_search_override( + configuration: &configuration::Configuration, + params: GetSearchOverrideParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/overrides/{overrideId}", + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name), + overrideId = crate::apis::urlencode(params.override_id) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -65,13 +68,24 @@ pub async fn get_search_override(configuration: &configuration::Configuration, p let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverride`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SearchOverride`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } - diff --git a/typesense_codegen/src/apis/presets_api.rs b/typesense_codegen/src/apis/presets_api.rs index 8f16f89..1f8722c 100644 --- a/typesense_codegen/src/apis/presets_api.rs +++ b/typesense_codegen/src/apis/presets_api.rs @@ -2,30 +2,28 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ - +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`delete_preset`] #[derive(Clone, Debug)] pub struct DeletePresetParams { /// The ID of the preset to delete. - pub preset_id: String + pub preset_id: String, } /// struct for passing parameters to the method [`retrieve_preset`] #[derive(Clone, Debug)] pub struct RetrievePresetParams { /// The ID of the preset to retrieve. - pub preset_id: String + pub preset_id: String, } /// struct for passing parameters to the method [`upsert_preset`] @@ -34,10 +32,9 @@ pub struct UpsertPresetParams { /// The name of the preset set to upsert. pub preset_id: String, /// The stopwords set to upsert. - pub preset_upsert_schema: models::PresetUpsertSchema + pub preset_upsert_schema: models::PresetUpsertSchema, } - /// struct for typed errors of method [`delete_preset`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -69,12 +66,19 @@ pub enum UpsertPresetError { UnknownValue(serde_json::Value), } - /// Permanently deletes a preset, given it's name. -pub async fn delete_preset(configuration: &configuration::Configuration, params: DeletePresetParams) -> Result> { - - let uri_str = format!("{}/presets/{presetId}", configuration.base_path, presetId=crate::apis::urlencode(params.preset_id)); - let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_preset( + configuration: &configuration::Configuration, + params: DeletePresetParams, +) -> Result> { + let uri_str = format!( + "{}/presets/{presetId}", + configuration.base_path, + presetId = crate::apis::urlencode(params.preset_id) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -103,19 +107,32 @@ pub async fn delete_preset(configuration: &configuration::Configuration, params: let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::PresetDeleteSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::PresetDeleteSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::PresetDeleteSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::PresetDeleteSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve the details of all presets -pub async fn retrieve_all_presets(configuration: &configuration::Configuration) -> Result> { - +pub async fn retrieve_all_presets( + configuration: &configuration::Configuration, +) -> Result> { let uri_str = format!("{}/presets", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -146,20 +163,38 @@ pub async fn retrieve_all_presets(configuration: &configuration::Configuration) let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::PresetsRetrieveSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::PresetsRetrieveSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::PresetsRetrieveSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::PresetsRetrieveSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve the details of a preset, given it's name. -pub async fn retrieve_preset(configuration: &configuration::Configuration, params: RetrievePresetParams) -> Result> { - - let uri_str = format!("{}/presets/{presetId}", configuration.base_path, presetId=crate::apis::urlencode(params.preset_id)); +pub async fn retrieve_preset( + configuration: &configuration::Configuration, + params: RetrievePresetParams, +) -> Result> { + let uri_str = format!( + "{}/presets/{presetId}", + configuration.base_path, + presetId = crate::apis::urlencode(params.preset_id) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -189,20 +224,38 @@ pub async fn retrieve_preset(configuration: &configuration::Configuration, param let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::PresetSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::PresetSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::PresetSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::PresetSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Create or update an existing preset. -pub async fn upsert_preset(configuration: &configuration::Configuration, params: UpsertPresetParams) -> Result> { - - let uri_str = format!("{}/presets/{presetId}", configuration.base_path, presetId=crate::apis::urlencode(params.preset_id)); +pub async fn upsert_preset( + configuration: &configuration::Configuration, + params: UpsertPresetParams, +) -> Result> { + let uri_str = format!( + "{}/presets/{presetId}", + configuration.base_path, + presetId = crate::apis::urlencode(params.preset_id) + ); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -233,13 +286,24 @@ pub async fn upsert_preset(configuration: &configuration::Configuration, params: let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::PresetSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::PresetSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::PresetSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::PresetSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } - diff --git a/typesense_codegen/src/apis/stemming_api.rs b/typesense_codegen/src/apis/stemming_api.rs index 3f2bebb..a8c0c2b 100644 --- a/typesense_codegen/src/apis/stemming_api.rs +++ b/typesense_codegen/src/apis/stemming_api.rs @@ -2,23 +2,21 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ - +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`get_stemming_dictionary`] #[derive(Clone, Debug)] pub struct GetStemmingDictionaryParams { /// The ID of the dictionary to retrieve - pub dictionary_id: String + pub dictionary_id: String, } /// struct for passing parameters to the method [`import_stemming_dictionary`] @@ -27,10 +25,9 @@ pub struct ImportStemmingDictionaryParams { /// The ID to assign to the dictionary pub id: String, /// The JSONL file containing word mappings - pub body: String + pub body: String, } - /// struct for typed errors of method [`get_stemming_dictionary`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -54,11 +51,16 @@ pub enum ListStemmingDictionariesError { UnknownValue(serde_json::Value), } - /// Fetch details of a specific stemming dictionary. -pub async fn get_stemming_dictionary(configuration: &configuration::Configuration, params: GetStemmingDictionaryParams) -> Result> { - - let uri_str = format!("{}/stemming/dictionaries/{dictionaryId}", configuration.base_path, dictionaryId=crate::apis::urlencode(params.dictionary_id)); +pub async fn get_stemming_dictionary( + configuration: &configuration::Configuration, + params: GetStemmingDictionaryParams, +) -> Result> { + let uri_str = format!( + "{}/stemming/dictionaries/{dictionaryId}", + configuration.base_path, + dictionaryId = crate::apis::urlencode(params.dictionary_id) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -88,21 +90,37 @@ pub async fn get_stemming_dictionary(configuration: &configuration::Configuratio let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::StemmingDictionary`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::StemmingDictionary`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::StemmingDictionary`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::StemmingDictionary`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Upload a JSONL file containing word mappings to create or update a stemming dictionary. -pub async fn import_stemming_dictionary(configuration: &configuration::Configuration, params: ImportStemmingDictionaryParams) -> Result> { - +pub async fn import_stemming_dictionary( + configuration: &configuration::Configuration, + params: ImportStemmingDictionaryParams, +) -> Result> { let uri_str = format!("{}/stemming/dictionaries/import", configuration.base_path); - let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); req_builder = req_builder.query(&[("id", ¶ms.id.to_string())]); if let Some(ref user_agent) = configuration.user_agent { @@ -133,19 +151,32 @@ pub async fn import_stemming_dictionary(configuration: &configuration::Configura let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `String`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `String`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `String`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `String`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve a list of all available stemming dictionaries. -pub async fn list_stemming_dictionaries(configuration: &configuration::Configuration) -> Result> { - +pub async fn list_stemming_dictionaries( + configuration: &configuration::Configuration, +) -> Result> { let uri_str = format!("{}/stemming/dictionaries", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -176,13 +207,24 @@ pub async fn list_stemming_dictionaries(configuration: &configuration::Configura let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ListStemmingDictionaries200Response`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ListStemmingDictionaries200Response`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::ListStemmingDictionaries200Response`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::ListStemmingDictionaries200Response`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } - diff --git a/typesense_codegen/src/apis/stopwords_api.rs b/typesense_codegen/src/apis/stopwords_api.rs index 9fd4519..b60555a 100644 --- a/typesense_codegen/src/apis/stopwords_api.rs +++ b/typesense_codegen/src/apis/stopwords_api.rs @@ -2,30 +2,28 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ - +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`delete_stopwords_set`] #[derive(Clone, Debug)] pub struct DeleteStopwordsSetParams { /// The ID of the stopwords set to delete. - pub set_id: String + pub set_id: String, } /// struct for passing parameters to the method [`retrieve_stopwords_set`] #[derive(Clone, Debug)] pub struct RetrieveStopwordsSetParams { /// The ID of the stopwords set to retrieve. - pub set_id: String + pub set_id: String, } /// struct for passing parameters to the method [`upsert_stopwords_set`] @@ -34,10 +32,9 @@ pub struct UpsertStopwordsSetParams { /// The ID of the stopwords set to upsert. pub set_id: String, /// The stopwords set to upsert. - pub stopwords_set_upsert_schema: models::StopwordsSetUpsertSchema + pub stopwords_set_upsert_schema: models::StopwordsSetUpsertSchema, } - /// struct for typed errors of method [`delete_stopwords_set`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -69,12 +66,19 @@ pub enum UpsertStopwordsSetError { UnknownValue(serde_json::Value), } - /// Permanently deletes a stopwords set, given it's name. -pub async fn delete_stopwords_set(configuration: &configuration::Configuration, params: DeleteStopwordsSetParams) -> Result> { - - let uri_str = format!("{}/stopwords/{setId}", configuration.base_path, setId=crate::apis::urlencode(params.set_id)); - let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_stopwords_set( + configuration: &configuration::Configuration, + params: DeleteStopwordsSetParams, +) -> Result> { + let uri_str = format!( + "{}/stopwords/{setId}", + configuration.base_path, + setId = crate::apis::urlencode(params.set_id) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -103,20 +107,38 @@ pub async fn delete_stopwords_set(configuration: &configuration::Configuration, let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::DeleteStopwordsSet200Response`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::DeleteStopwordsSet200Response`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::DeleteStopwordsSet200Response`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::DeleteStopwordsSet200Response`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve the details of a stopwords set, given it's name. -pub async fn retrieve_stopwords_set(configuration: &configuration::Configuration, params: RetrieveStopwordsSetParams) -> Result> { - - let uri_str = format!("{}/stopwords/{setId}", configuration.base_path, setId=crate::apis::urlencode(params.set_id)); +pub async fn retrieve_stopwords_set( + configuration: &configuration::Configuration, + params: RetrieveStopwordsSetParams, +) -> Result> { + let uri_str = format!( + "{}/stopwords/{setId}", + configuration.base_path, + setId = crate::apis::urlencode(params.set_id) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -146,19 +168,32 @@ pub async fn retrieve_stopwords_set(configuration: &configuration::Configuration let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::StopwordsSetRetrieveSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::StopwordsSetRetrieveSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::StopwordsSetRetrieveSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::StopwordsSetRetrieveSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve the details of all stopwords sets -pub async fn retrieve_stopwords_sets(configuration: &configuration::Configuration) -> Result> { - +pub async fn retrieve_stopwords_sets( + configuration: &configuration::Configuration, +) -> Result> { let uri_str = format!("{}/stopwords", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -189,20 +224,38 @@ pub async fn retrieve_stopwords_sets(configuration: &configuration::Configuratio let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::StopwordsSetsRetrieveAllSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::StopwordsSetsRetrieveAllSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::StopwordsSetsRetrieveAllSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::StopwordsSetsRetrieveAllSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// When an analytics rule is created, we give it a name and describe the type, the source collections and the destination collection. -pub async fn upsert_stopwords_set(configuration: &configuration::Configuration, params: UpsertStopwordsSetParams) -> Result> { - - let uri_str = format!("{}/stopwords/{setId}", configuration.base_path, setId=crate::apis::urlencode(params.set_id)); +pub async fn upsert_stopwords_set( + configuration: &configuration::Configuration, + params: UpsertStopwordsSetParams, +) -> Result> { + let uri_str = format!( + "{}/stopwords/{setId}", + configuration.base_path, + setId = crate::apis::urlencode(params.set_id) + ); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -233,13 +286,24 @@ pub async fn upsert_stopwords_set(configuration: &configuration::Configuration, let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::StopwordsSetSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::StopwordsSetSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::StopwordsSetSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::StopwordsSetSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } - diff --git a/typesense_codegen/src/apis/synonyms_api.rs b/typesense_codegen/src/apis/synonyms_api.rs index 65473af..70d92ce 100644 --- a/typesense_codegen/src/apis/synonyms_api.rs +++ b/typesense_codegen/src/apis/synonyms_api.rs @@ -2,30 +2,28 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ - +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; use reqwest; use serde::{Deserialize, Serialize, de::Error as _}; -use crate::{apis::ResponseContent, models}; -use super::{Error, configuration, ContentType}; /// struct for passing parameters to the method [`delete_synonym_set`] #[derive(Clone, Debug)] pub struct DeleteSynonymSetParams { /// The name of the synonym set to delete - pub synonym_set_name: String + pub synonym_set_name: String, } /// struct for passing parameters to the method [`retrieve_synonym_set`] #[derive(Clone, Debug)] pub struct RetrieveSynonymSetParams { /// The name of the synonym set to retrieve - pub synonym_set_name: String + pub synonym_set_name: String, } /// struct for passing parameters to the method [`upsert_synonym_set`] @@ -34,10 +32,9 @@ pub struct UpsertSynonymSetParams { /// The name of the synonym set to create/update pub synonym_set_name: String, /// The synonym set to be created/updated - pub synonym_set_create_schema: models::SynonymSetCreateSchema + pub synonym_set_create_schema: models::SynonymSetCreateSchema, } - /// struct for typed errors of method [`delete_synonym_set`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -69,12 +66,19 @@ pub enum UpsertSynonymSetError { UnknownValue(serde_json::Value), } - /// Delete a specific synonym set by its name -pub async fn delete_synonym_set(configuration: &configuration::Configuration, params: DeleteSynonymSetParams) -> Result> { - - let uri_str = format!("{}/synonym_sets/{synonymSetName}", configuration.base_path, synonymSetName=crate::apis::urlencode(params.synonym_set_name)); - let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); +pub async fn delete_synonym_set( + configuration: &configuration::Configuration, + params: DeleteSynonymSetParams, +) -> Result> { + let uri_str = format!( + "{}/synonym_sets/{synonymSetName}", + configuration.base_path, + synonymSetName = crate::apis::urlencode(params.synonym_set_name) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); @@ -103,20 +107,38 @@ pub async fn delete_synonym_set(configuration: &configuration::Configuration, pa let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SynonymSetDeleteSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SynonymSetDeleteSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SynonymSetDeleteSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SynonymSetDeleteSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve a specific synonym set by its name -pub async fn retrieve_synonym_set(configuration: &configuration::Configuration, params: RetrieveSynonymSetParams) -> Result> { - - let uri_str = format!("{}/synonym_sets/{synonymSetName}", configuration.base_path, synonymSetName=crate::apis::urlencode(params.synonym_set_name)); +pub async fn retrieve_synonym_set( + configuration: &configuration::Configuration, + params: RetrieveSynonymSetParams, +) -> Result> { + let uri_str = format!( + "{}/synonym_sets/{synonymSetName}", + configuration.base_path, + synonymSetName = crate::apis::urlencode(params.synonym_set_name) + ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -146,19 +168,32 @@ pub async fn retrieve_synonym_set(configuration: &configuration::Configuration, let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SynonymSetCreateSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SynonymSetCreateSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SynonymSetCreateSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SynonymSetCreateSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve all synonym sets -pub async fn retrieve_synonym_sets(configuration: &configuration::Configuration) -> Result, Error> { - +pub async fn retrieve_synonym_sets( + configuration: &configuration::Configuration, +) -> Result, Error> { let uri_str = format!("{}/synonym_sets", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -189,20 +224,38 @@ pub async fn retrieve_synonym_sets(configuration: &configuration::Configuration) let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `Vec`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `Vec`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Create or update a synonym set with the given name -pub async fn upsert_synonym_set(configuration: &configuration::Configuration, params: UpsertSynonymSetParams) -> Result> { - - let uri_str = format!("{}/synonym_sets/{synonymSetName}", configuration.base_path, synonymSetName=crate::apis::urlencode(params.synonym_set_name)); +pub async fn upsert_synonym_set( + configuration: &configuration::Configuration, + params: UpsertSynonymSetParams, +) -> Result> { + let uri_str = format!( + "{}/synonym_sets/{synonymSetName}", + configuration.base_path, + synonymSetName = crate::apis::urlencode(params.synonym_set_name) + ); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -233,13 +286,24 @@ pub async fn upsert_synonym_set(configuration: &configuration::Configuration, pa let content = resp.text().await?; match content_type { ContentType::Json => serde_json::from_str(&content).map_err(Error::from), - ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SynonymSetSchema`"))), - ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SynonymSetSchema`")))), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SynonymSetSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SynonymSetSchema`" + )))); + } } } else { let content = resp.text().await?; let entity: Option = serde_json::from_str(&content).ok(); - Err(Error::ResponseError(ResponseContent { status, content, entity })) + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } - diff --git a/typesense_codegen/src/models/analytics_event.rs b/typesense_codegen/src/models/analytics_event.rs index 4559896..805e7e3 100644 --- a/typesense_codegen/src/models/analytics_event.rs +++ b/typesense_codegen/src/models/analytics_event.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -24,7 +23,11 @@ pub struct AnalyticsEvent { } impl AnalyticsEvent { - pub fn new(name: String, event_type: String, data: models::AnalyticsEventData) -> AnalyticsEvent{ + pub fn new( + name: String, + event_type: String, + data: models::AnalyticsEventData, + ) -> AnalyticsEvent { AnalyticsEvent { name, event_type, @@ -32,4 +35,3 @@ impl AnalyticsEvent { } } } - diff --git a/typesense_codegen/src/models/analytics_event_create_response.rs b/typesense_codegen/src/models/analytics_event_create_response.rs index c15ca25..9f2b9fa 100644 --- a/typesense_codegen/src/models/analytics_event_create_response.rs +++ b/typesense_codegen/src/models/analytics_event_create_response.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +17,7 @@ pub struct AnalyticsEventCreateResponse { } impl AnalyticsEventCreateResponse { - pub fn new(ok: bool) -> AnalyticsEventCreateResponse{ - AnalyticsEventCreateResponse { - ok, - } + pub fn new(ok: bool) -> AnalyticsEventCreateResponse { + AnalyticsEventCreateResponse { ok } } } - diff --git a/typesense_codegen/src/models/analytics_event_data.rs b/typesense_codegen/src/models/analytics_event_data.rs index 75b44f9..e4bf678 100644 --- a/typesense_codegen/src/models/analytics_event_data.rs +++ b/typesense_codegen/src/models/analytics_event_data.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -28,7 +27,7 @@ pub struct AnalyticsEventData { impl AnalyticsEventData { /// Event payload - pub fn new() -> AnalyticsEventData{ + pub fn new() -> AnalyticsEventData { AnalyticsEventData { user_id: None, doc_id: None, @@ -38,4 +37,3 @@ impl AnalyticsEventData { } } } - diff --git a/typesense_codegen/src/models/analytics_events_response.rs b/typesense_codegen/src/models/analytics_events_response.rs index fafd98b..a218617 100644 --- a/typesense_codegen/src/models/analytics_events_response.rs +++ b/typesense_codegen/src/models/analytics_events_response.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +17,7 @@ pub struct AnalyticsEventsResponse { } impl AnalyticsEventsResponse { - pub fn new(events: Vec) -> AnalyticsEventsResponse{ - AnalyticsEventsResponse { - events, - } + pub fn new(events: Vec) -> AnalyticsEventsResponse { + AnalyticsEventsResponse { events } } } - diff --git a/typesense_codegen/src/models/analytics_events_response_events_inner.rs b/typesense_codegen/src/models/analytics_events_response_events_inner.rs index 93f9dfc..971fbdc 100644 --- a/typesense_codegen/src/models/analytics_events_response_events_inner.rs +++ b/typesense_codegen/src/models/analytics_events_response_events_inner.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -32,7 +31,7 @@ pub struct AnalyticsEventsResponseEventsInner { } impl AnalyticsEventsResponseEventsInner { - pub fn new() -> AnalyticsEventsResponseEventsInner{ + pub fn new() -> AnalyticsEventsResponseEventsInner { AnalyticsEventsResponseEventsInner { name: None, event_type: None, @@ -45,4 +44,3 @@ impl AnalyticsEventsResponseEventsInner { } } } - diff --git a/typesense_codegen/src/models/analytics_rule.rs b/typesense_codegen/src/models/analytics_rule.rs index cc15a1d..31a29ea 100644 --- a/typesense_codegen/src/models/analytics_rule.rs +++ b/typesense_codegen/src/models/analytics_rule.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -28,7 +27,12 @@ pub struct AnalyticsRule { } impl AnalyticsRule { - pub fn new(name: String, r#type: Type, collection: String, event_type: String) -> AnalyticsRule{ + pub fn new( + name: String, + r#type: Type, + collection: String, + event_type: String, + ) -> AnalyticsRule { AnalyticsRule { name, r#type, @@ -39,7 +43,7 @@ impl AnalyticsRule { } } } -/// +/// #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum Type { #[serde(rename = "popular_queries")] @@ -57,4 +61,3 @@ impl Default for Type { Self::PopularQueries } } - diff --git a/typesense_codegen/src/models/analytics_rule_create.rs b/typesense_codegen/src/models/analytics_rule_create.rs index 9373230..819bde2 100644 --- a/typesense_codegen/src/models/analytics_rule_create.rs +++ b/typesense_codegen/src/models/analytics_rule_create.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -28,7 +27,12 @@ pub struct AnalyticsRuleCreate { } impl AnalyticsRuleCreate { - pub fn new(name: String, r#type: Type, collection: String, event_type: String) -> AnalyticsRuleCreate{ + pub fn new( + name: String, + r#type: Type, + collection: String, + event_type: String, + ) -> AnalyticsRuleCreate { AnalyticsRuleCreate { name, r#type, @@ -39,7 +43,7 @@ impl AnalyticsRuleCreate { } } } -/// +/// #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum Type { #[serde(rename = "popular_queries")] @@ -57,4 +61,3 @@ impl Default for Type { Self::PopularQueries } } - diff --git a/typesense_codegen/src/models/analytics_rule_create_params.rs b/typesense_codegen/src/models/analytics_rule_create_params.rs index de7cf5a..e53c4db 100644 --- a/typesense_codegen/src/models/analytics_rule_create_params.rs +++ b/typesense_codegen/src/models/analytics_rule_create_params.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -13,11 +12,17 @@ use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct AnalyticsRuleCreateParams { - #[serde(rename = "destination_collection", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "destination_collection", + skip_serializing_if = "Option::is_none" + )] pub destination_collection: Option, #[serde(rename = "limit", skip_serializing_if = "Option::is_none")] pub limit: Option, - #[serde(rename = "capture_search_requests", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "capture_search_requests", + skip_serializing_if = "Option::is_none" + )] pub capture_search_requests: Option, #[serde(rename = "meta_fields", skip_serializing_if = "Option::is_none")] pub meta_fields: Option>, @@ -30,7 +35,7 @@ pub struct AnalyticsRuleCreateParams { } impl AnalyticsRuleCreateParams { - pub fn new() -> AnalyticsRuleCreateParams{ + pub fn new() -> AnalyticsRuleCreateParams { AnalyticsRuleCreateParams { destination_collection: None, limit: None, @@ -42,4 +47,3 @@ impl AnalyticsRuleCreateParams { } } } - diff --git a/typesense_codegen/src/models/analytics_rule_update.rs b/typesense_codegen/src/models/analytics_rule_update.rs index 66ad385..68015ed 100644 --- a/typesense_codegen/src/models/analytics_rule_update.rs +++ b/typesense_codegen/src/models/analytics_rule_update.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -24,7 +23,7 @@ pub struct AnalyticsRuleUpdate { impl AnalyticsRuleUpdate { /// Fields allowed to update on an analytics rule - pub fn new() -> AnalyticsRuleUpdate{ + pub fn new() -> AnalyticsRuleUpdate { AnalyticsRuleUpdate { name: None, rule_tag: None, @@ -32,4 +31,3 @@ impl AnalyticsRuleUpdate { } } } - diff --git a/typesense_codegen/src/models/analytics_status.rs b/typesense_codegen/src/models/analytics_status.rs index 9d1b6bf..ffed203 100644 --- a/typesense_codegen/src/models/analytics_status.rs +++ b/typesense_codegen/src/models/analytics_status.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -13,15 +12,24 @@ use serde::{Deserialize, Serialize}; #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct AnalyticsStatus { - #[serde(rename = "popular_prefix_queries", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "popular_prefix_queries", + skip_serializing_if = "Option::is_none" + )] pub popular_prefix_queries: Option, - #[serde(rename = "nohits_prefix_queries", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "nohits_prefix_queries", + skip_serializing_if = "Option::is_none" + )] pub nohits_prefix_queries: Option, #[serde(rename = "log_prefix_queries", skip_serializing_if = "Option::is_none")] pub log_prefix_queries: Option, #[serde(rename = "query_log_events", skip_serializing_if = "Option::is_none")] pub query_log_events: Option, - #[serde(rename = "query_counter_events", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "query_counter_events", + skip_serializing_if = "Option::is_none" + )] pub query_counter_events: Option, #[serde(rename = "doc_log_events", skip_serializing_if = "Option::is_none")] pub doc_log_events: Option, @@ -30,7 +38,7 @@ pub struct AnalyticsStatus { } impl AnalyticsStatus { - pub fn new() -> AnalyticsStatus{ + pub fn new() -> AnalyticsStatus { AnalyticsStatus { popular_prefix_queries: None, nohits_prefix_queries: None, @@ -42,4 +50,3 @@ impl AnalyticsStatus { } } } - diff --git a/typesense_codegen/src/models/api_key.rs b/typesense_codegen/src/models/api_key.rs index f108ead..2fce4d2 100644 --- a/typesense_codegen/src/models/api_key.rs +++ b/typesense_codegen/src/models/api_key.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -30,7 +29,7 @@ pub struct ApiKey { } impl ApiKey { - pub fn new(description: String, actions: Vec, collections: Vec) -> ApiKey{ + pub fn new(description: String, actions: Vec, collections: Vec) -> ApiKey { ApiKey { value: None, description, @@ -42,4 +41,3 @@ impl ApiKey { } } } - diff --git a/typesense_codegen/src/models/api_key_delete_response.rs b/typesense_codegen/src/models/api_key_delete_response.rs index c12440d..1969865 100644 --- a/typesense_codegen/src/models/api_key_delete_response.rs +++ b/typesense_codegen/src/models/api_key_delete_response.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,10 +18,7 @@ pub struct ApiKeyDeleteResponse { } impl ApiKeyDeleteResponse { - pub fn new(id: i64) -> ApiKeyDeleteResponse{ - ApiKeyDeleteResponse { - id, - } + pub fn new(id: i64) -> ApiKeyDeleteResponse { + ApiKeyDeleteResponse { id } } } - diff --git a/typesense_codegen/src/models/api_key_schema.rs b/typesense_codegen/src/models/api_key_schema.rs index 3e8c2ab..585aeef 100644 --- a/typesense_codegen/src/models/api_key_schema.rs +++ b/typesense_codegen/src/models/api_key_schema.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -26,7 +25,11 @@ pub struct ApiKeySchema { } impl ApiKeySchema { - pub fn new(description: String, actions: Vec, collections: Vec) -> ApiKeySchema{ + pub fn new( + description: String, + actions: Vec, + collections: Vec, + ) -> ApiKeySchema { ApiKeySchema { value: None, description, @@ -36,4 +39,3 @@ impl ApiKeySchema { } } } - diff --git a/typesense_codegen/src/models/api_keys_response.rs b/typesense_codegen/src/models/api_keys_response.rs index ca7686c..5a4a893 100644 --- a/typesense_codegen/src/models/api_keys_response.rs +++ b/typesense_codegen/src/models/api_keys_response.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +17,7 @@ pub struct ApiKeysResponse { } impl ApiKeysResponse { - pub fn new(keys: Vec) -> ApiKeysResponse{ - ApiKeysResponse { - keys, - } + pub fn new(keys: Vec) -> ApiKeysResponse { + ApiKeysResponse { keys } } } - diff --git a/typesense_codegen/src/models/api_response.rs b/typesense_codegen/src/models/api_response.rs index 08c2c11..b6b5a90 100644 --- a/typesense_codegen/src/models/api_response.rs +++ b/typesense_codegen/src/models/api_response.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +17,7 @@ pub struct ApiResponse { } impl ApiResponse { - pub fn new(message: String) -> ApiResponse{ - ApiResponse { - message, - } + pub fn new(message: String) -> ApiResponse { + ApiResponse { message } } } - diff --git a/typesense_codegen/src/models/api_stats_response.rs b/typesense_codegen/src/models/api_stats_response.rs index d8d2933..efd8b83 100644 --- a/typesense_codegen/src/models/api_stats_response.rs +++ b/typesense_codegen/src/models/api_stats_response.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -15,34 +14,58 @@ use serde::{Deserialize, Serialize}; pub struct ApiStatsResponse { #[serde(rename = "delete_latency_ms", skip_serializing_if = "Option::is_none")] pub delete_latency_ms: Option, - #[serde(rename = "delete_requests_per_second", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "delete_requests_per_second", + skip_serializing_if = "Option::is_none" + )] pub delete_requests_per_second: Option, #[serde(rename = "import_latency_ms", skip_serializing_if = "Option::is_none")] pub import_latency_ms: Option, - #[serde(rename = "import_requests_per_second", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "import_requests_per_second", + skip_serializing_if = "Option::is_none" + )] pub import_requests_per_second: Option, #[serde(rename = "latency_ms", skip_serializing_if = "Option::is_none")] pub latency_ms: Option, - #[serde(rename = "overloaded_requests_per_second", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "overloaded_requests_per_second", + skip_serializing_if = "Option::is_none" + )] pub overloaded_requests_per_second: Option, - #[serde(rename = "pending_write_batches", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "pending_write_batches", + skip_serializing_if = "Option::is_none" + )] pub pending_write_batches: Option, - #[serde(rename = "requests_per_second", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "requests_per_second", + skip_serializing_if = "Option::is_none" + )] pub requests_per_second: Option, #[serde(rename = "search_latency_ms", skip_serializing_if = "Option::is_none")] pub search_latency_ms: Option, - #[serde(rename = "search_requests_per_second", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "search_requests_per_second", + skip_serializing_if = "Option::is_none" + )] pub search_requests_per_second: Option, - #[serde(rename = "total_requests_per_second", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "total_requests_per_second", + skip_serializing_if = "Option::is_none" + )] pub total_requests_per_second: Option, #[serde(rename = "write_latency_ms", skip_serializing_if = "Option::is_none")] pub write_latency_ms: Option, - #[serde(rename = "write_requests_per_second", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "write_requests_per_second", + skip_serializing_if = "Option::is_none" + )] pub write_requests_per_second: Option, } impl ApiStatsResponse { - pub fn new() -> ApiStatsResponse{ + pub fn new() -> ApiStatsResponse { ApiStatsResponse { delete_latency_ms: None, delete_requests_per_second: None, @@ -60,4 +83,3 @@ impl ApiStatsResponse { } } } - diff --git a/typesense_codegen/src/models/collection_alias.rs b/typesense_codegen/src/models/collection_alias.rs index f94f6a2..8b6623e 100644 --- a/typesense_codegen/src/models/collection_alias.rs +++ b/typesense_codegen/src/models/collection_alias.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -22,11 +21,10 @@ pub struct CollectionAlias { } impl CollectionAlias { - pub fn new(name: String, collection_name: String) -> CollectionAlias{ + pub fn new(name: String, collection_name: String) -> CollectionAlias { CollectionAlias { name, collection_name, } } } - diff --git a/typesense_codegen/src/models/collection_alias_schema.rs b/typesense_codegen/src/models/collection_alias_schema.rs index 3a67ea0..8bb1001 100644 --- a/typesense_codegen/src/models/collection_alias_schema.rs +++ b/typesense_codegen/src/models/collection_alias_schema.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,10 +18,7 @@ pub struct CollectionAliasSchema { } impl CollectionAliasSchema { - pub fn new(collection_name: String) -> CollectionAliasSchema{ - CollectionAliasSchema { - collection_name, - } + pub fn new(collection_name: String) -> CollectionAliasSchema { + CollectionAliasSchema { collection_name } } } - diff --git a/typesense_codegen/src/models/collection_aliases_response.rs b/typesense_codegen/src/models/collection_aliases_response.rs index 0db53a1..ab2b741 100644 --- a/typesense_codegen/src/models/collection_aliases_response.rs +++ b/typesense_codegen/src/models/collection_aliases_response.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +17,7 @@ pub struct CollectionAliasesResponse { } impl CollectionAliasesResponse { - pub fn new(aliases: Vec) -> CollectionAliasesResponse{ - CollectionAliasesResponse { - aliases, - } + pub fn new(aliases: Vec) -> CollectionAliasesResponse { + CollectionAliasesResponse { aliases } } } - diff --git a/typesense_codegen/src/models/collection_response.rs b/typesense_codegen/src/models/collection_response.rs index d664428..d65cc95 100644 --- a/typesense_codegen/src/models/collection_response.rs +++ b/typesense_codegen/src/models/collection_response.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -20,23 +19,29 @@ pub struct CollectionResponse { #[serde(rename = "fields")] pub fields: Vec, /// The name of an int32 / float field that determines the order in which the search results are ranked when a sort_by clause is not provided during searching. This field must indicate some kind of popularity. - #[serde(rename = "default_sorting_field", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "default_sorting_field", + skip_serializing_if = "Option::is_none" + )] pub default_sorting_field: Option, - /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. + /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. #[serde(rename = "token_separators", skip_serializing_if = "Option::is_none")] pub token_separators: Option>, /// List of synonym set names to associate with this collection #[serde(rename = "synonym_sets", skip_serializing_if = "Option::is_none")] pub synonym_sets: Option>, /// Enables experimental support at a collection level for nested object or object array fields. This field is only available if the Typesense server is version `0.24.0.rcn34` or later. - #[serde(rename = "enable_nested_fields", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "enable_nested_fields", + skip_serializing_if = "Option::is_none" + )] pub enable_nested_fields: Option, - /// List of symbols or special characters to be indexed. + /// List of symbols or special characters to be indexed. #[serde(rename = "symbols_to_index", skip_serializing_if = "Option::is_none")] pub symbols_to_index: Option>, #[serde(rename = "voice_query_model", skip_serializing_if = "Option::is_none")] pub voice_query_model: Option>, - /// Optional details about the collection, e.g., when it was created, who created it etc. + /// Optional details about the collection, e.g., when it was created, who created it etc. #[serde(rename = "metadata", skip_serializing_if = "Option::is_none")] pub metadata: Option, /// Number of documents in the collection @@ -48,7 +53,12 @@ pub struct CollectionResponse { } impl CollectionResponse { - pub fn new(name: String, fields: Vec, num_documents: i64, created_at: i64) -> CollectionResponse{ + pub fn new( + name: String, + fields: Vec, + num_documents: i64, + created_at: i64, + ) -> CollectionResponse { CollectionResponse { name, fields, @@ -64,4 +74,3 @@ impl CollectionResponse { } } } - diff --git a/typesense_codegen/src/models/collection_schema.rs b/typesense_codegen/src/models/collection_schema.rs index 7e2c754..177ff60 100644 --- a/typesense_codegen/src/models/collection_schema.rs +++ b/typesense_codegen/src/models/collection_schema.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -22,29 +21,35 @@ pub struct CollectionSchema { #[serde(rename = "fields")] pub fields: Vec, /// The name of an int32 / float field that determines the order in which the search results are ranked when a sort_by clause is not provided during searching. This field must indicate some kind of popularity. - #[serde(rename = "default_sorting_field", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "default_sorting_field", + skip_serializing_if = "Option::is_none" + )] pub default_sorting_field: Option, - /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. + /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. #[serde(rename = "token_separators", skip_serializing_if = "Option::is_none")] pub token_separators: Option>, /// List of synonym set names to associate with this collection #[serde(rename = "synonym_sets", skip_serializing_if = "Option::is_none")] pub synonym_sets: Option>, /// Enables experimental support at a collection level for nested object or object array fields. This field is only available if the Typesense server is version `0.24.0.rcn34` or later. - #[serde(rename = "enable_nested_fields", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "enable_nested_fields", + skip_serializing_if = "Option::is_none" + )] pub enable_nested_fields: Option, - /// List of symbols or special characters to be indexed. + /// List of symbols or special characters to be indexed. #[serde(rename = "symbols_to_index", skip_serializing_if = "Option::is_none")] pub symbols_to_index: Option>, #[serde(rename = "voice_query_model", skip_serializing_if = "Option::is_none")] pub voice_query_model: Option>, - /// Optional details about the collection, e.g., when it was created, who created it etc. + /// Optional details about the collection, e.g., when it was created, who created it etc. #[serde(rename = "metadata", skip_serializing_if = "Option::is_none")] pub metadata: Option, } impl CollectionSchema { - pub fn new(name: String, fields: Vec) -> CollectionSchema{ + pub fn new(name: String, fields: Vec) -> CollectionSchema { CollectionSchema { name, fields, @@ -58,4 +63,3 @@ impl CollectionSchema { } } } - diff --git a/typesense_codegen/src/models/collection_update_schema.rs b/typesense_codegen/src/models/collection_update_schema.rs index ca45a78..4446d29 100644 --- a/typesense_codegen/src/models/collection_update_schema.rs +++ b/typesense_codegen/src/models/collection_update_schema.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,13 +18,13 @@ pub struct CollectionUpdateSchema { /// List of synonym set names to associate with this collection #[serde(rename = "synonym_sets", skip_serializing_if = "Option::is_none")] pub synonym_sets: Option>, - /// Optional details about the collection, e.g., when it was created, who created it etc. + /// Optional details about the collection, e.g., when it was created, who created it etc. #[serde(rename = "metadata", skip_serializing_if = "Option::is_none")] pub metadata: Option, } impl CollectionUpdateSchema { - pub fn new(fields: Vec) -> CollectionUpdateSchema{ + pub fn new(fields: Vec) -> CollectionUpdateSchema { CollectionUpdateSchema { fields, synonym_sets: None, @@ -33,4 +32,3 @@ impl CollectionUpdateSchema { } } } - diff --git a/typesense_codegen/src/models/conversation_model_create_schema.rs b/typesense_codegen/src/models/conversation_model_create_schema.rs index 3a2ed5b..418b696 100644 --- a/typesense_codegen/src/models/conversation_model_create_schema.rs +++ b/typesense_codegen/src/models/conversation_model_create_schema.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -31,10 +30,10 @@ pub struct ConversationModelCreateSchema { /// The system prompt that contains special instructions to the LLM #[serde(rename = "system_prompt", skip_serializing_if = "Option::is_none")] pub system_prompt: Option, - /// Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) + /// Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) #[serde(rename = "ttl", skip_serializing_if = "Option::is_none")] pub ttl: Option, - /// The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. + /// The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. #[serde(rename = "max_bytes")] pub max_bytes: i32, /// URL of vLLM service @@ -43,7 +42,11 @@ pub struct ConversationModelCreateSchema { } impl ConversationModelCreateSchema { - pub fn new(model_name: String, history_collection: String, max_bytes: i32) -> ConversationModelCreateSchema{ + pub fn new( + model_name: String, + history_collection: String, + max_bytes: i32, + ) -> ConversationModelCreateSchema { ConversationModelCreateSchema { id: None, model_name, @@ -57,4 +60,3 @@ impl ConversationModelCreateSchema { } } } - diff --git a/typesense_codegen/src/models/conversation_model_schema.rs b/typesense_codegen/src/models/conversation_model_schema.rs index 828988d..356d03f 100644 --- a/typesense_codegen/src/models/conversation_model_schema.rs +++ b/typesense_codegen/src/models/conversation_model_schema.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -31,10 +30,10 @@ pub struct ConversationModelSchema { /// The system prompt that contains special instructions to the LLM #[serde(rename = "system_prompt", skip_serializing_if = "Option::is_none")] pub system_prompt: Option, - /// Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) + /// Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) #[serde(rename = "ttl", skip_serializing_if = "Option::is_none")] pub ttl: Option, - /// The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. + /// The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. #[serde(rename = "max_bytes")] pub max_bytes: i32, /// URL of vLLM service @@ -43,7 +42,12 @@ pub struct ConversationModelSchema { } impl ConversationModelSchema { - pub fn new(id: String, model_name: String, history_collection: String, max_bytes: i32) -> ConversationModelSchema{ + pub fn new( + id: String, + model_name: String, + history_collection: String, + max_bytes: i32, + ) -> ConversationModelSchema { ConversationModelSchema { id, model_name, @@ -57,4 +61,3 @@ impl ConversationModelSchema { } } } - diff --git a/typesense_codegen/src/models/conversation_model_update_schema.rs b/typesense_codegen/src/models/conversation_model_update_schema.rs index 7ac5e40..636bcde 100644 --- a/typesense_codegen/src/models/conversation_model_update_schema.rs +++ b/typesense_codegen/src/models/conversation_model_update_schema.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -31,10 +30,10 @@ pub struct ConversationModelUpdateSchema { /// The system prompt that contains special instructions to the LLM #[serde(rename = "system_prompt", skip_serializing_if = "Option::is_none")] pub system_prompt: Option, - /// Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) + /// Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) #[serde(rename = "ttl", skip_serializing_if = "Option::is_none")] pub ttl: Option, - /// The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. + /// The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. #[serde(rename = "max_bytes", skip_serializing_if = "Option::is_none")] pub max_bytes: Option, /// URL of vLLM service @@ -43,7 +42,7 @@ pub struct ConversationModelUpdateSchema { } impl ConversationModelUpdateSchema { - pub fn new() -> ConversationModelUpdateSchema{ + pub fn new() -> ConversationModelUpdateSchema { ConversationModelUpdateSchema { id: None, model_name: None, @@ -57,4 +56,3 @@ impl ConversationModelUpdateSchema { } } } - diff --git a/typesense_codegen/src/models/create_analytics_rule_200_response.rs b/typesense_codegen/src/models/create_analytics_rule_200_response.rs index 6d45dca..b1fb869 100644 --- a/typesense_codegen/src/models/create_analytics_rule_200_response.rs +++ b/typesense_codegen/src/models/create_analytics_rule_200_response.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -23,7 +22,7 @@ impl Default for CreateAnalyticsRule200Response { Self::AnalyticsRule(Default::default()) } } -/// +/// #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum Type { #[serde(rename = "popular_queries")] @@ -41,4 +40,3 @@ impl Default for Type { Self::PopularQueries } } - diff --git a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs index 8e773e2..86ba06a 100644 --- a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs +++ b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -30,7 +29,12 @@ pub struct CreateAnalyticsRule200ResponseOneOfInner { } impl CreateAnalyticsRule200ResponseOneOfInner { - pub fn new(name: String, r#type: Type, collection: String, event_type: String) -> CreateAnalyticsRule200ResponseOneOfInner{ + pub fn new( + name: String, + r#type: Type, + collection: String, + event_type: String, + ) -> CreateAnalyticsRule200ResponseOneOfInner { CreateAnalyticsRule200ResponseOneOfInner { name, r#type, @@ -42,7 +46,7 @@ impl CreateAnalyticsRule200ResponseOneOfInner { } } } -/// +/// #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum Type { #[serde(rename = "popular_queries")] @@ -60,4 +64,3 @@ impl Default for Type { Self::PopularQueries } } - diff --git a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs index 12f7422..c10566b 100644 --- a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs +++ b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +17,7 @@ pub struct CreateAnalyticsRule200ResponseOneOfInnerAnyOf { } impl CreateAnalyticsRule200ResponseOneOfInnerAnyOf { - pub fn new() -> CreateAnalyticsRule200ResponseOneOfInnerAnyOf{ - CreateAnalyticsRule200ResponseOneOfInnerAnyOf { - error: None, - } + pub fn new() -> CreateAnalyticsRule200ResponseOneOfInnerAnyOf { + CreateAnalyticsRule200ResponseOneOfInnerAnyOf { error: None } } } - diff --git a/typesense_codegen/src/models/create_analytics_rule_request.rs b/typesense_codegen/src/models/create_analytics_rule_request.rs index 597dec9..b01b6b0 100644 --- a/typesense_codegen/src/models/create_analytics_rule_request.rs +++ b/typesense_codegen/src/models/create_analytics_rule_request.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -23,7 +22,7 @@ impl Default for CreateAnalyticsRuleRequest { Self::AnalyticsRuleCreate(Default::default()) } } -/// +/// #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum Type { #[serde(rename = "popular_queries")] @@ -41,4 +40,3 @@ impl Default for Type { Self::PopularQueries } } - diff --git a/typesense_codegen/src/models/debug_200_response.rs b/typesense_codegen/src/models/debug_200_response.rs index 0c88dd7..f166294 100644 --- a/typesense_codegen/src/models/debug_200_response.rs +++ b/typesense_codegen/src/models/debug_200_response.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +17,7 @@ pub struct Debug200Response { } impl Debug200Response { - pub fn new() -> Debug200Response{ - Debug200Response { - version: None, - } + pub fn new() -> Debug200Response { + Debug200Response { version: None } } } - diff --git a/typesense_codegen/src/models/delete_documents_200_response.rs b/typesense_codegen/src/models/delete_documents_200_response.rs index 5779adf..670c8dd 100644 --- a/typesense_codegen/src/models/delete_documents_200_response.rs +++ b/typesense_codegen/src/models/delete_documents_200_response.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +17,7 @@ pub struct DeleteDocuments200Response { } impl DeleteDocuments200Response { - pub fn new(num_deleted: i32) -> DeleteDocuments200Response{ - DeleteDocuments200Response { - num_deleted, - } + pub fn new(num_deleted: i32) -> DeleteDocuments200Response { + DeleteDocuments200Response { num_deleted } } } - diff --git a/typesense_codegen/src/models/delete_documents_parameters.rs b/typesense_codegen/src/models/delete_documents_parameters.rs index 903d717..d8ed65f 100644 --- a/typesense_codegen/src/models/delete_documents_parameters.rs +++ b/typesense_codegen/src/models/delete_documents_parameters.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -26,7 +25,7 @@ pub struct DeleteDocumentsParameters { } impl DeleteDocumentsParameters { - pub fn new(filter_by: String) -> DeleteDocumentsParameters{ + pub fn new(filter_by: String) -> DeleteDocumentsParameters { DeleteDocumentsParameters { filter_by, batch_size: None, @@ -35,4 +34,3 @@ impl DeleteDocumentsParameters { } } } - diff --git a/typesense_codegen/src/models/delete_stopwords_set_200_response.rs b/typesense_codegen/src/models/delete_stopwords_set_200_response.rs index 87fa748..dea1137 100644 --- a/typesense_codegen/src/models/delete_stopwords_set_200_response.rs +++ b/typesense_codegen/src/models/delete_stopwords_set_200_response.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +17,7 @@ pub struct DeleteStopwordsSet200Response { } impl DeleteStopwordsSet200Response { - pub fn new(id: String) -> DeleteStopwordsSet200Response{ - DeleteStopwordsSet200Response { - id, - } + pub fn new(id: String) -> DeleteStopwordsSet200Response { + DeleteStopwordsSet200Response { id } } } - diff --git a/typesense_codegen/src/models/dirty_values.rs b/typesense_codegen/src/models/dirty_values.rs index 5c3a422..a9aab89 100644 --- a/typesense_codegen/src/models/dirty_values.rs +++ b/typesense_codegen/src/models/dirty_values.rs @@ -2,16 +2,15 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ use crate::models; use serde::{Deserialize, Serialize}; -/// +/// #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum DirtyValues { #[serde(rename = "coerce_or_reject")] @@ -22,7 +21,6 @@ pub enum DirtyValues { Drop, #[serde(rename = "reject")] Reject, - } impl std::fmt::Display for DirtyValues { @@ -41,4 +39,3 @@ impl Default for DirtyValues { Self::CoerceOrReject } } - diff --git a/typesense_codegen/src/models/drop_tokens_mode.rs b/typesense_codegen/src/models/drop_tokens_mode.rs index 9769869..01eced2 100644 --- a/typesense_codegen/src/models/drop_tokens_mode.rs +++ b/typesense_codegen/src/models/drop_tokens_mode.rs @@ -2,17 +2,16 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ use crate::models; use serde::{Deserialize, Serialize}; -/// DropTokensMode : Dictates the direction in which the words in the query must be dropped when the original words in the query do not appear in any document. Values: right_to_left (default), left_to_right, both_sides:3 A note on both_sides:3 - for queries up to 3 tokens (words) in length, this mode will drop tokens from both sides and exhaustively rank all matching results. If query length is greater than 3 words, Typesense will just fallback to default behavior of right_to_left -/// Dictates the direction in which the words in the query must be dropped when the original words in the query do not appear in any document. Values: right_to_left (default), left_to_right, both_sides:3 A note on both_sides:3 - for queries up to 3 tokens (words) in length, this mode will drop tokens from both sides and exhaustively rank all matching results. If query length is greater than 3 words, Typesense will just fallback to default behavior of right_to_left +/// DropTokensMode : Dictates the direction in which the words in the query must be dropped when the original words in the query do not appear in any document. Values: right_to_left (default), left_to_right, both_sides:3 A note on both_sides:3 - for queries up to 3 tokens (words) in length, this mode will drop tokens from both sides and exhaustively rank all matching results. If query length is greater than 3 words, Typesense will just fallback to default behavior of right_to_left +/// Dictates the direction in which the words in the query must be dropped when the original words in the query do not appear in any document. Values: right_to_left (default), left_to_right, both_sides:3 A note on both_sides:3 - for queries up to 3 tokens (words) in length, this mode will drop tokens from both sides and exhaustively rank all matching results. If query length is greater than 3 words, Typesense will just fallback to default behavior of right_to_left #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum DropTokensMode { #[serde(rename = "right_to_left")] @@ -21,7 +20,6 @@ pub enum DropTokensMode { LeftToRight, #[serde(rename = "both_sides:3")] BothSidesColon3, - } impl std::fmt::Display for DropTokensMode { @@ -39,4 +37,3 @@ impl Default for DropTokensMode { Self::RightToLeft } } - diff --git a/typesense_codegen/src/models/export_documents_parameters.rs b/typesense_codegen/src/models/export_documents_parameters.rs index b1defbb..22fdd2c 100644 --- a/typesense_codegen/src/models/export_documents_parameters.rs +++ b/typesense_codegen/src/models/export_documents_parameters.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -25,7 +24,7 @@ pub struct ExportDocumentsParameters { } impl ExportDocumentsParameters { - pub fn new() -> ExportDocumentsParameters{ + pub fn new() -> ExportDocumentsParameters { ExportDocumentsParameters { filter_by: None, include_fields: None, @@ -33,4 +32,3 @@ impl ExportDocumentsParameters { } } } - diff --git a/typesense_codegen/src/models/facet_counts.rs b/typesense_codegen/src/models/facet_counts.rs index a56913a..14437c8 100644 --- a/typesense_codegen/src/models/facet_counts.rs +++ b/typesense_codegen/src/models/facet_counts.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -22,7 +21,7 @@ pub struct FacetCounts { } impl FacetCounts { - pub fn new() -> FacetCounts{ + pub fn new() -> FacetCounts { FacetCounts { counts: None, field_name: None, @@ -30,4 +29,3 @@ impl FacetCounts { } } } - diff --git a/typesense_codegen/src/models/facet_counts_counts_inner.rs b/typesense_codegen/src/models/facet_counts_counts_inner.rs index 9b732a5..2f2405b 100644 --- a/typesense_codegen/src/models/facet_counts_counts_inner.rs +++ b/typesense_codegen/src/models/facet_counts_counts_inner.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -24,7 +23,7 @@ pub struct FacetCountsCountsInner { } impl FacetCountsCountsInner { - pub fn new() -> FacetCountsCountsInner{ + pub fn new() -> FacetCountsCountsInner { FacetCountsCountsInner { count: None, highlighted: None, @@ -33,4 +32,3 @@ impl FacetCountsCountsInner { } } } - diff --git a/typesense_codegen/src/models/facet_counts_stats.rs b/typesense_codegen/src/models/facet_counts_stats.rs index 24a8e63..45e8a91 100644 --- a/typesense_codegen/src/models/facet_counts_stats.rs +++ b/typesense_codegen/src/models/facet_counts_stats.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -26,7 +25,7 @@ pub struct FacetCountsStats { } impl FacetCountsStats { - pub fn new() -> FacetCountsStats{ + pub fn new() -> FacetCountsStats { FacetCountsStats { max: None, min: None, @@ -36,4 +35,3 @@ impl FacetCountsStats { } } } - diff --git a/typesense_codegen/src/models/field.rs b/typesense_codegen/src/models/field.rs index b3fd4d7..548e721 100644 --- a/typesense_codegen/src/models/field.rs +++ b/typesense_codegen/src/models/field.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -31,32 +30,32 @@ pub struct Field { pub sort: Option, #[serde(rename = "infix", skip_serializing_if = "Option::is_none")] pub infix: Option, - /// Name of a field in another collection that should be linked to this collection so that it can be joined during query. + /// Name of a field in another collection that should be linked to this collection so that it can be joined during query. #[serde(rename = "reference", skip_serializing_if = "Option::is_none")] pub reference: Option, #[serde(rename = "num_dim", skip_serializing_if = "Option::is_none")] pub num_dim: Option, #[serde(rename = "drop", skip_serializing_if = "Option::is_none")] pub drop: Option, - /// When set to false, the field value will not be stored on disk. Default: true. + /// When set to false, the field value will not be stored on disk. Default: true. #[serde(rename = "store", skip_serializing_if = "Option::is_none")] pub store: Option, - /// The distance metric to be used for vector search. Default: `cosine`. You can also use `ip` for inner product. + /// The distance metric to be used for vector search. Default: `cosine`. You can also use `ip` for inner product. #[serde(rename = "vec_dist", skip_serializing_if = "Option::is_none")] pub vec_dist: Option, - /// Enables an index optimized for range filtering on numerical fields (e.g. rating:>3.5). Default: false. + /// Enables an index optimized for range filtering on numerical fields (e.g. rating:>3.5). Default: false. #[serde(rename = "range_index", skip_serializing_if = "Option::is_none")] pub range_index: Option, - /// Values are stemmed before indexing in-memory. Default: false. + /// Values are stemmed before indexing in-memory. Default: false. #[serde(rename = "stem", skip_serializing_if = "Option::is_none")] pub stem: Option, /// Name of the stemming dictionary to use for this field #[serde(rename = "stem_dictionary", skip_serializing_if = "Option::is_none")] pub stem_dictionary: Option, - /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. + /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. #[serde(rename = "token_separators", skip_serializing_if = "Option::is_none")] pub token_separators: Option>, - /// List of symbols or special characters to be indexed. + /// List of symbols or special characters to be indexed. #[serde(rename = "symbols_to_index", skip_serializing_if = "Option::is_none")] pub symbols_to_index: Option>, #[serde(rename = "embed", skip_serializing_if = "Option::is_none")] @@ -64,7 +63,7 @@ pub struct Field { } impl Field { - pub fn new(name: String, r#type: String) -> Field{ + pub fn new(name: String, r#type: String) -> Field { Field { name, r#type, @@ -88,4 +87,3 @@ impl Field { } } } - diff --git a/typesense_codegen/src/models/field_embed.rs b/typesense_codegen/src/models/field_embed.rs index 2b9b203..274e47c 100644 --- a/typesense_codegen/src/models/field_embed.rs +++ b/typesense_codegen/src/models/field_embed.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -20,11 +19,10 @@ pub struct FieldEmbed { } impl FieldEmbed { - pub fn new(from: Vec, model_config: models::FieldEmbedModelConfig) -> FieldEmbed{ + pub fn new(from: Vec, model_config: models::FieldEmbedModelConfig) -> FieldEmbed { FieldEmbed { from, model_config: Box::new(model_config), } } } - diff --git a/typesense_codegen/src/models/field_embed_model_config.rs b/typesense_codegen/src/models/field_embed_model_config.rs index 407e32f..6aca8a1 100644 --- a/typesense_codegen/src/models/field_embed_model_config.rs +++ b/typesense_codegen/src/models/field_embed_model_config.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -36,7 +35,7 @@ pub struct FieldEmbedModelConfig { } impl FieldEmbedModelConfig { - pub fn new(model_name: String) -> FieldEmbedModelConfig{ + pub fn new(model_name: String) -> FieldEmbedModelConfig { FieldEmbedModelConfig { model_name, api_key: None, @@ -51,4 +50,3 @@ impl FieldEmbedModelConfig { } } } - diff --git a/typesense_codegen/src/models/get_collections_parameters.rs b/typesense_codegen/src/models/get_collections_parameters.rs index 01226a7..8ecdcbe 100644 --- a/typesense_codegen/src/models/get_collections_parameters.rs +++ b/typesense_codegen/src/models/get_collections_parameters.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -16,7 +15,7 @@ pub struct GetCollectionsParameters { /// Comma-separated list of fields from the collection to exclude from the response #[serde(rename = "exclude_fields", skip_serializing_if = "Option::is_none")] pub exclude_fields: Option, - /// Number of collections to fetch. Default: returns all collections. + /// Number of collections to fetch. Default: returns all collections. #[serde(rename = "limit", skip_serializing_if = "Option::is_none")] pub limit: Option, /// Identifies the starting point to return collections when paginating. @@ -25,7 +24,7 @@ pub struct GetCollectionsParameters { } impl GetCollectionsParameters { - pub fn new() -> GetCollectionsParameters{ + pub fn new() -> GetCollectionsParameters { GetCollectionsParameters { exclude_fields: None, limit: None, @@ -33,4 +32,3 @@ impl GetCollectionsParameters { } } } - diff --git a/typesense_codegen/src/models/health_status.rs b/typesense_codegen/src/models/health_status.rs index 82a4489..7a7489c 100644 --- a/typesense_codegen/src/models/health_status.rs +++ b/typesense_codegen/src/models/health_status.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +17,7 @@ pub struct HealthStatus { } impl HealthStatus { - pub fn new(ok: bool) -> HealthStatus{ - HealthStatus { - ok, - } + pub fn new(ok: bool) -> HealthStatus { + HealthStatus { ok } } } - diff --git a/typesense_codegen/src/models/import_documents_parameters.rs b/typesense_codegen/src/models/import_documents_parameters.rs index 0b7abab..b5fbc23 100644 --- a/typesense_codegen/src/models/import_documents_parameters.rs +++ b/typesense_codegen/src/models/import_documents_parameters.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,7 +17,10 @@ pub struct ImportDocumentsParameters { /// Returning the id of the imported documents. If you want the import response to return the ingested document's id in the response, you can use the return_id parameter. #[serde(rename = "return_id", skip_serializing_if = "Option::is_none")] pub return_id: Option, - #[serde(rename = "remote_embedding_batch_size", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "remote_embedding_batch_size", + skip_serializing_if = "Option::is_none" + )] pub remote_embedding_batch_size: Option, #[serde(rename = "return_doc", skip_serializing_if = "Option::is_none")] pub return_doc: Option, @@ -29,7 +31,7 @@ pub struct ImportDocumentsParameters { } impl ImportDocumentsParameters { - pub fn new() -> ImportDocumentsParameters{ + pub fn new() -> ImportDocumentsParameters { ImportDocumentsParameters { batch_size: None, return_id: None, @@ -40,4 +42,3 @@ impl ImportDocumentsParameters { } } } - diff --git a/typesense_codegen/src/models/index_action.rs b/typesense_codegen/src/models/index_action.rs index 7bce745..207dfe3 100644 --- a/typesense_codegen/src/models/index_action.rs +++ b/typesense_codegen/src/models/index_action.rs @@ -2,16 +2,15 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ use crate::models; use serde::{Deserialize, Serialize}; -/// +/// #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum IndexAction { #[serde(rename = "create")] @@ -22,7 +21,6 @@ pub enum IndexAction { Upsert, #[serde(rename = "emplace")] Emplace, - } impl std::fmt::Display for IndexAction { @@ -41,4 +39,3 @@ impl Default for IndexAction { Self::Create } } - diff --git a/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs b/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs index 75a8ddf..f4c66ee 100644 --- a/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs +++ b/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +17,7 @@ pub struct ListStemmingDictionaries200Response { } impl ListStemmingDictionaries200Response { - pub fn new() -> ListStemmingDictionaries200Response{ - ListStemmingDictionaries200Response { - dictionaries: None, - } + pub fn new() -> ListStemmingDictionaries200Response { + ListStemmingDictionaries200Response { dictionaries: None } } } - diff --git a/typesense_codegen/src/models/multi_search_collection_parameters.rs b/typesense_codegen/src/models/multi_search_collection_parameters.rs index cc5a457..ff03484 100644 --- a/typesense_codegen/src/models/multi_search_collection_parameters.rs +++ b/typesense_codegen/src/models/multi_search_collection_parameters.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -54,7 +53,7 @@ pub struct MultiSearchCollectionParameters { /// Facet values that are returned can now be filtered via this parameter. The matching facet text is also highlighted. For example, when faceting by `category`, you can set `facet_query=category:shoe` to return only facet values that contain the prefix \"shoe\". #[serde(rename = "facet_query", skip_serializing_if = "Option::is_none")] pub facet_query: Option, - /// The number of typographical errors (1 or 2) that would be tolerated. Default: 2 + /// The number of typographical errors (1 or 2) that would be tolerated. Default: 2 #[serde(rename = "num_typos", skip_serializing_if = "Option::is_none")] pub num_typos: Option, /// Results from this specific page number would be fetched. @@ -63,7 +62,7 @@ pub struct MultiSearchCollectionParameters { /// Number of results to fetch per page. Default: 10 #[serde(rename = "per_page", skip_serializing_if = "Option::is_none")] pub per_page: Option, - /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. + /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. #[serde(rename = "limit", skip_serializing_if = "Option::is_none")] pub limit: Option, /// Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. @@ -72,11 +71,14 @@ pub struct MultiSearchCollectionParameters { /// You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. #[serde(rename = "group_by", skip_serializing_if = "Option::is_none")] pub group_by: Option, - /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 + /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 #[serde(rename = "group_limit", skip_serializing_if = "Option::is_none")] pub group_limit: Option, - /// Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true - #[serde(rename = "group_missing_values", skip_serializing_if = "Option::is_none")] + /// Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true + #[serde( + rename = "group_missing_values", + skip_serializing_if = "Option::is_none" + )] pub group_missing_values: Option, /// List of fields from the document to include in the search result #[serde(rename = "include_fields", skip_serializing_if = "Option::is_none")] @@ -85,140 +87,194 @@ pub struct MultiSearchCollectionParameters { #[serde(rename = "exclude_fields", skip_serializing_if = "Option::is_none")] pub exclude_fields: Option, /// List of fields which should be highlighted fully without snippeting - #[serde(rename = "highlight_full_fields", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "highlight_full_fields", + skip_serializing_if = "Option::is_none" + )] pub highlight_full_fields: Option, - /// The number of tokens that should surround the highlighted text on each side. Default: 4 - #[serde(rename = "highlight_affix_num_tokens", skip_serializing_if = "Option::is_none")] + /// The number of tokens that should surround the highlighted text on each side. Default: 4 + #[serde( + rename = "highlight_affix_num_tokens", + skip_serializing_if = "Option::is_none" + )] pub highlight_affix_num_tokens: Option, - /// The start tag used for the highlighted snippets. Default: `` - #[serde(rename = "highlight_start_tag", skip_serializing_if = "Option::is_none")] + /// The start tag used for the highlighted snippets. Default: `` + #[serde( + rename = "highlight_start_tag", + skip_serializing_if = "Option::is_none" + )] pub highlight_start_tag: Option, - /// The end tag used for the highlighted snippets. Default: `` + /// The end tag used for the highlighted snippets. Default: `` #[serde(rename = "highlight_end_tag", skip_serializing_if = "Option::is_none")] pub highlight_end_tag: Option, - /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 + /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 #[serde(rename = "snippet_threshold", skip_serializing_if = "Option::is_none")] pub snippet_threshold: Option, - /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 - #[serde(rename = "drop_tokens_threshold", skip_serializing_if = "Option::is_none")] + /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 + #[serde( + rename = "drop_tokens_threshold", + skip_serializing_if = "Option::is_none" + )] pub drop_tokens_threshold: Option, #[serde(rename = "drop_tokens_mode", skip_serializing_if = "Option::is_none")] pub drop_tokens_mode: Option, - /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 - #[serde(rename = "typo_tokens_threshold", skip_serializing_if = "Option::is_none")] + /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 + #[serde( + rename = "typo_tokens_threshold", + skip_serializing_if = "Option::is_none" + )] pub typo_tokens_threshold: Option, - /// Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. - #[serde(rename = "enable_typos_for_alpha_numerical_tokens", skip_serializing_if = "Option::is_none")] + /// Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + #[serde( + rename = "enable_typos_for_alpha_numerical_tokens", + skip_serializing_if = "Option::is_none" + )] pub enable_typos_for_alpha_numerical_tokens: Option, - /// Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false - #[serde(rename = "filter_curated_hits", skip_serializing_if = "Option::is_none")] + /// Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + #[serde( + rename = "filter_curated_hits", + skip_serializing_if = "Option::is_none" + )] pub filter_curated_hits: Option, - /// If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + /// If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true #[serde(rename = "enable_synonyms", skip_serializing_if = "Option::is_none")] pub enable_synonyms: Option, - /// Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). + /// Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). #[serde(rename = "enable_analytics", skip_serializing_if = "Option::is_none")] pub enable_analytics: Option, - /// Allow synonym resolution on word prefixes in the query. Default: false + /// Allow synonym resolution on word prefixes in the query. Default: false #[serde(rename = "synonym_prefix", skip_serializing_if = "Option::is_none")] pub synonym_prefix: Option, - /// Allow synonym resolution on typo-corrected words in the query. Default: 0 + /// Allow synonym resolution on typo-corrected words in the query. Default: 0 #[serde(rename = "synonym_num_typos", skip_serializing_if = "Option::is_none")] pub synonym_num_typos: Option, - /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "pinned_hits", skip_serializing_if = "Option::is_none")] pub pinned_hits: Option, - /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "hidden_hits", skip_serializing_if = "Option::is_none")] pub hidden_hits: Option, /// Comma separated list of tags to trigger the curations rules that match the tags. #[serde(rename = "override_tags", skip_serializing_if = "Option::is_none")] pub override_tags: Option, - /// A list of custom fields that must be highlighted even if you don't query for them + /// A list of custom fields that must be highlighted even if you don't query for them #[serde(rename = "highlight_fields", skip_serializing_if = "Option::is_none")] pub highlight_fields: Option, - /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same - #[serde(rename = "pre_segmented_query", skip_serializing_if = "Option::is_none")] + /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same + #[serde( + rename = "pre_segmented_query", + skip_serializing_if = "Option::is_none" + )] pub pre_segmented_query: Option, - /// Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. + /// Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. #[serde(rename = "preset", skip_serializing_if = "Option::is_none")] pub preset: Option, - /// If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false + /// If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false #[serde(rename = "enable_overrides", skip_serializing_if = "Option::is_none")] pub enable_overrides: Option, - /// Set this parameter to true to ensure that an exact match is ranked above the others - #[serde(rename = "prioritize_exact_match", skip_serializing_if = "Option::is_none")] + /// Set this parameter to true to ensure that an exact match is ranked above the others + #[serde( + rename = "prioritize_exact_match", + skip_serializing_if = "Option::is_none" + )] pub prioritize_exact_match: Option, - /// Make Typesense prioritize documents where the query words appear earlier in the text. - #[serde(rename = "prioritize_token_position", skip_serializing_if = "Option::is_none")] + /// Make Typesense prioritize documents where the query words appear earlier in the text. + #[serde( + rename = "prioritize_token_position", + skip_serializing_if = "Option::is_none" + )] pub prioritize_token_position: Option, - /// Make Typesense prioritize documents where the query words appear in more number of fields. - #[serde(rename = "prioritize_num_matching_fields", skip_serializing_if = "Option::is_none")] + /// Make Typesense prioritize documents where the query words appear in more number of fields. + #[serde( + rename = "prioritize_num_matching_fields", + skip_serializing_if = "Option::is_none" + )] pub prioritize_num_matching_fields: Option, - /// Make Typesense disable typos for numerical tokens. - #[serde(rename = "enable_typos_for_numerical_tokens", skip_serializing_if = "Option::is_none")] + /// Make Typesense disable typos for numerical tokens. + #[serde( + rename = "enable_typos_for_numerical_tokens", + skip_serializing_if = "Option::is_none" + )] pub enable_typos_for_numerical_tokens: Option, - /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). + /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). #[serde(rename = "exhaustive_search", skip_serializing_if = "Option::is_none")] pub exhaustive_search: Option, - /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. + /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. #[serde(rename = "search_cutoff_ms", skip_serializing_if = "Option::is_none")] pub search_cutoff_ms: Option, - /// Enable server side caching of search query results. By default, caching is disabled. + /// Enable server side caching of search query results. By default, caching is disabled. #[serde(rename = "use_cache", skip_serializing_if = "Option::is_none")] pub use_cache: Option, - /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. + /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. #[serde(rename = "cache_ttl", skip_serializing_if = "Option::is_none")] pub cache_ttl: Option, - /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_1typo", skip_serializing_if = "Option::is_none")] pub min_len_1typo: Option, - /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_2typo", skip_serializing_if = "Option::is_none")] pub min_len_2typo: Option, - /// Vector query expression for fetching documents \"closest\" to a given query/document vector. + /// Vector query expression for fetching documents \"closest\" to a given query/document vector. #[serde(rename = "vector_query", skip_serializing_if = "Option::is_none")] pub vector_query: Option, - /// Timeout (in milliseconds) for fetching remote embeddings. - #[serde(rename = "remote_embedding_timeout_ms", skip_serializing_if = "Option::is_none")] + /// Timeout (in milliseconds) for fetching remote embeddings. + #[serde( + rename = "remote_embedding_timeout_ms", + skip_serializing_if = "Option::is_none" + )] pub remote_embedding_timeout_ms: Option, - /// Number of times to retry fetching remote embeddings. - #[serde(rename = "remote_embedding_num_tries", skip_serializing_if = "Option::is_none")] + /// Number of times to retry fetching remote embeddings. + #[serde( + rename = "remote_embedding_num_tries", + skip_serializing_if = "Option::is_none" + )] pub remote_embedding_num_tries: Option, - /// Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). + /// Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). #[serde(rename = "facet_strategy", skip_serializing_if = "Option::is_none")] pub facet_strategy: Option, - /// Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. + /// Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. #[serde(rename = "stopwords", skip_serializing_if = "Option::is_none")] pub stopwords: Option, - /// Comma separated string of nested facet fields whose parent object should be returned in facet response. - #[serde(rename = "facet_return_parent", skip_serializing_if = "Option::is_none")] + /// Comma separated string of nested facet fields whose parent object should be returned in facet response. + #[serde( + rename = "facet_return_parent", + skip_serializing_if = "Option::is_none" + )] pub facet_return_parent: Option, - /// The base64 encoded audio file in 16 khz 16-bit WAV format. + /// The base64 encoded audio file in 16 khz 16-bit WAV format. #[serde(rename = "voice_query", skip_serializing_if = "Option::is_none")] pub voice_query: Option, - /// Enable conversational search. + /// Enable conversational search. #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] pub conversation: Option, - /// The Id of Conversation Model to be used. - #[serde(rename = "conversation_model_id", skip_serializing_if = "Option::is_none")] + /// The Id of Conversation Model to be used. + #[serde( + rename = "conversation_model_id", + skip_serializing_if = "Option::is_none" + )] pub conversation_model_id: Option, - /// The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + /// The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. #[serde(rename = "conversation_id", skip_serializing_if = "Option::is_none")] pub conversation_id: Option, - /// The collection to search in. + /// The collection to search in. #[serde(rename = "collection", skip_serializing_if = "Option::is_none")] pub collection: Option, /// A separate search API key for each search within a multi_search request - #[serde(rename = "x-typesense-api-key", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "x-typesense-api-key", + skip_serializing_if = "Option::is_none" + )] pub x_typesense_api_key: Option, - /// When true, computes both text match and vector distance scores for all matches in hybrid search. Documents found only through keyword search will get a vector distance score, and documents found only through vector search will get a text match score. - #[serde(rename = "rerank_hybrid_matches", skip_serializing_if = "Option::is_none")] + /// When true, computes both text match and vector distance scores for all matches in hybrid search. Documents found only through keyword search will get a vector distance score, and documents found only through vector search will get a text match score. + #[serde( + rename = "rerank_hybrid_matches", + skip_serializing_if = "Option::is_none" + )] pub rerank_hybrid_matches: Option, } impl MultiSearchCollectionParameters { - pub fn new() -> MultiSearchCollectionParameters{ + pub fn new() -> MultiSearchCollectionParameters { MultiSearchCollectionParameters { q: None, query_by: None, @@ -290,4 +346,3 @@ impl MultiSearchCollectionParameters { } } } - diff --git a/typesense_codegen/src/models/multi_search_parameters.rs b/typesense_codegen/src/models/multi_search_parameters.rs index 7602ca5..8d4cbda 100644 --- a/typesense_codegen/src/models/multi_search_parameters.rs +++ b/typesense_codegen/src/models/multi_search_parameters.rs @@ -2,16 +2,15 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ use crate::models; use serde::{Deserialize, Serialize}; -/// MultiSearchParameters : Parameters for the multi search API. +/// MultiSearchParameters : Parameters for the multi search API. #[derive(bon::Builder)] #[builder(on(String, into))] #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] @@ -55,7 +54,7 @@ pub struct MultiSearchParameters { /// Facet values that are returned can now be filtered via this parameter. The matching facet text is also highlighted. For example, when faceting by `category`, you can set `facet_query=category:shoe` to return only facet values that contain the prefix \"shoe\". #[serde(rename = "facet_query", skip_serializing_if = "Option::is_none")] pub facet_query: Option, - /// The number of typographical errors (1 or 2) that would be tolerated. Default: 2 + /// The number of typographical errors (1 or 2) that would be tolerated. Default: 2 #[serde(rename = "num_typos", skip_serializing_if = "Option::is_none")] pub num_typos: Option, /// Results from this specific page number would be fetched. @@ -64,7 +63,7 @@ pub struct MultiSearchParameters { /// Number of results to fetch per page. Default: 10 #[serde(rename = "per_page", skip_serializing_if = "Option::is_none")] pub per_page: Option, - /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. + /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. #[serde(rename = "limit", skip_serializing_if = "Option::is_none")] pub limit: Option, /// Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. @@ -73,11 +72,14 @@ pub struct MultiSearchParameters { /// You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. #[serde(rename = "group_by", skip_serializing_if = "Option::is_none")] pub group_by: Option, - /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 + /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 #[serde(rename = "group_limit", skip_serializing_if = "Option::is_none")] pub group_limit: Option, - /// Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true - #[serde(rename = "group_missing_values", skip_serializing_if = "Option::is_none")] + /// Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true + #[serde( + rename = "group_missing_values", + skip_serializing_if = "Option::is_none" + )] pub group_missing_values: Option, /// List of fields from the document to include in the search result #[serde(rename = "include_fields", skip_serializing_if = "Option::is_none")] @@ -86,132 +88,180 @@ pub struct MultiSearchParameters { #[serde(rename = "exclude_fields", skip_serializing_if = "Option::is_none")] pub exclude_fields: Option, /// List of fields which should be highlighted fully without snippeting - #[serde(rename = "highlight_full_fields", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "highlight_full_fields", + skip_serializing_if = "Option::is_none" + )] pub highlight_full_fields: Option, - /// The number of tokens that should surround the highlighted text on each side. Default: 4 - #[serde(rename = "highlight_affix_num_tokens", skip_serializing_if = "Option::is_none")] + /// The number of tokens that should surround the highlighted text on each side. Default: 4 + #[serde( + rename = "highlight_affix_num_tokens", + skip_serializing_if = "Option::is_none" + )] pub highlight_affix_num_tokens: Option, - /// The start tag used for the highlighted snippets. Default: `` - #[serde(rename = "highlight_start_tag", skip_serializing_if = "Option::is_none")] + /// The start tag used for the highlighted snippets. Default: `` + #[serde( + rename = "highlight_start_tag", + skip_serializing_if = "Option::is_none" + )] pub highlight_start_tag: Option, - /// The end tag used for the highlighted snippets. Default: `` + /// The end tag used for the highlighted snippets. Default: `` #[serde(rename = "highlight_end_tag", skip_serializing_if = "Option::is_none")] pub highlight_end_tag: Option, - /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 + /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 #[serde(rename = "snippet_threshold", skip_serializing_if = "Option::is_none")] pub snippet_threshold: Option, - /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 - #[serde(rename = "drop_tokens_threshold", skip_serializing_if = "Option::is_none")] + /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 + #[serde( + rename = "drop_tokens_threshold", + skip_serializing_if = "Option::is_none" + )] pub drop_tokens_threshold: Option, #[serde(rename = "drop_tokens_mode", skip_serializing_if = "Option::is_none")] pub drop_tokens_mode: Option, - /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 - #[serde(rename = "typo_tokens_threshold", skip_serializing_if = "Option::is_none")] + /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 + #[serde( + rename = "typo_tokens_threshold", + skip_serializing_if = "Option::is_none" + )] pub typo_tokens_threshold: Option, - /// Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. - #[serde(rename = "enable_typos_for_alpha_numerical_tokens", skip_serializing_if = "Option::is_none")] + /// Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + #[serde( + rename = "enable_typos_for_alpha_numerical_tokens", + skip_serializing_if = "Option::is_none" + )] pub enable_typos_for_alpha_numerical_tokens: Option, - /// Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false - #[serde(rename = "filter_curated_hits", skip_serializing_if = "Option::is_none")] + /// Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + #[serde( + rename = "filter_curated_hits", + skip_serializing_if = "Option::is_none" + )] pub filter_curated_hits: Option, - /// If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + /// If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true #[serde(rename = "enable_synonyms", skip_serializing_if = "Option::is_none")] pub enable_synonyms: Option, - /// Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). + /// Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). #[serde(rename = "enable_analytics", skip_serializing_if = "Option::is_none")] pub enable_analytics: Option, - /// Allow synonym resolution on word prefixes in the query. Default: false + /// Allow synonym resolution on word prefixes in the query. Default: false #[serde(rename = "synonym_prefix", skip_serializing_if = "Option::is_none")] pub synonym_prefix: Option, - /// Allow synonym resolution on typo-corrected words in the query. Default: 0 + /// Allow synonym resolution on typo-corrected words in the query. Default: 0 #[serde(rename = "synonym_num_typos", skip_serializing_if = "Option::is_none")] pub synonym_num_typos: Option, - /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "pinned_hits", skip_serializing_if = "Option::is_none")] pub pinned_hits: Option, - /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "hidden_hits", skip_serializing_if = "Option::is_none")] pub hidden_hits: Option, /// Comma separated list of tags to trigger the curations rules that match the tags. #[serde(rename = "override_tags", skip_serializing_if = "Option::is_none")] pub override_tags: Option, - /// A list of custom fields that must be highlighted even if you don't query for them + /// A list of custom fields that must be highlighted even if you don't query for them #[serde(rename = "highlight_fields", skip_serializing_if = "Option::is_none")] pub highlight_fields: Option, - /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same - #[serde(rename = "pre_segmented_query", skip_serializing_if = "Option::is_none")] + /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same + #[serde( + rename = "pre_segmented_query", + skip_serializing_if = "Option::is_none" + )] pub pre_segmented_query: Option, - /// Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. + /// Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. #[serde(rename = "preset", skip_serializing_if = "Option::is_none")] pub preset: Option, - /// If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false + /// If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false #[serde(rename = "enable_overrides", skip_serializing_if = "Option::is_none")] pub enable_overrides: Option, - /// Set this parameter to true to ensure that an exact match is ranked above the others - #[serde(rename = "prioritize_exact_match", skip_serializing_if = "Option::is_none")] + /// Set this parameter to true to ensure that an exact match is ranked above the others + #[serde( + rename = "prioritize_exact_match", + skip_serializing_if = "Option::is_none" + )] pub prioritize_exact_match: Option, - /// Make Typesense prioritize documents where the query words appear earlier in the text. - #[serde(rename = "prioritize_token_position", skip_serializing_if = "Option::is_none")] + /// Make Typesense prioritize documents where the query words appear earlier in the text. + #[serde( + rename = "prioritize_token_position", + skip_serializing_if = "Option::is_none" + )] pub prioritize_token_position: Option, - /// Make Typesense prioritize documents where the query words appear in more number of fields. - #[serde(rename = "prioritize_num_matching_fields", skip_serializing_if = "Option::is_none")] + /// Make Typesense prioritize documents where the query words appear in more number of fields. + #[serde( + rename = "prioritize_num_matching_fields", + skip_serializing_if = "Option::is_none" + )] pub prioritize_num_matching_fields: Option, - /// Make Typesense disable typos for numerical tokens. - #[serde(rename = "enable_typos_for_numerical_tokens", skip_serializing_if = "Option::is_none")] + /// Make Typesense disable typos for numerical tokens. + #[serde( + rename = "enable_typos_for_numerical_tokens", + skip_serializing_if = "Option::is_none" + )] pub enable_typos_for_numerical_tokens: Option, - /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). + /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). #[serde(rename = "exhaustive_search", skip_serializing_if = "Option::is_none")] pub exhaustive_search: Option, - /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. + /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. #[serde(rename = "search_cutoff_ms", skip_serializing_if = "Option::is_none")] pub search_cutoff_ms: Option, - /// Enable server side caching of search query results. By default, caching is disabled. + /// Enable server side caching of search query results. By default, caching is disabled. #[serde(rename = "use_cache", skip_serializing_if = "Option::is_none")] pub use_cache: Option, - /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. + /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. #[serde(rename = "cache_ttl", skip_serializing_if = "Option::is_none")] pub cache_ttl: Option, - /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_1typo", skip_serializing_if = "Option::is_none")] pub min_len_1typo: Option, - /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_2typo", skip_serializing_if = "Option::is_none")] pub min_len_2typo: Option, - /// Vector query expression for fetching documents \"closest\" to a given query/document vector. + /// Vector query expression for fetching documents \"closest\" to a given query/document vector. #[serde(rename = "vector_query", skip_serializing_if = "Option::is_none")] pub vector_query: Option, - /// Timeout (in milliseconds) for fetching remote embeddings. - #[serde(rename = "remote_embedding_timeout_ms", skip_serializing_if = "Option::is_none")] + /// Timeout (in milliseconds) for fetching remote embeddings. + #[serde( + rename = "remote_embedding_timeout_ms", + skip_serializing_if = "Option::is_none" + )] pub remote_embedding_timeout_ms: Option, - /// Number of times to retry fetching remote embeddings. - #[serde(rename = "remote_embedding_num_tries", skip_serializing_if = "Option::is_none")] + /// Number of times to retry fetching remote embeddings. + #[serde( + rename = "remote_embedding_num_tries", + skip_serializing_if = "Option::is_none" + )] pub remote_embedding_num_tries: Option, - /// Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). + /// Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). #[serde(rename = "facet_strategy", skip_serializing_if = "Option::is_none")] pub facet_strategy: Option, - /// Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. + /// Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. #[serde(rename = "stopwords", skip_serializing_if = "Option::is_none")] pub stopwords: Option, - /// Comma separated string of nested facet fields whose parent object should be returned in facet response. - #[serde(rename = "facet_return_parent", skip_serializing_if = "Option::is_none")] + /// Comma separated string of nested facet fields whose parent object should be returned in facet response. + #[serde( + rename = "facet_return_parent", + skip_serializing_if = "Option::is_none" + )] pub facet_return_parent: Option, - /// The base64 encoded audio file in 16 khz 16-bit WAV format. + /// The base64 encoded audio file in 16 khz 16-bit WAV format. #[serde(rename = "voice_query", skip_serializing_if = "Option::is_none")] pub voice_query: Option, - /// Enable conversational search. + /// Enable conversational search. #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] pub conversation: Option, - /// The Id of Conversation Model to be used. - #[serde(rename = "conversation_model_id", skip_serializing_if = "Option::is_none")] + /// The Id of Conversation Model to be used. + #[serde( + rename = "conversation_model_id", + skip_serializing_if = "Option::is_none" + )] pub conversation_model_id: Option, - /// The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + /// The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. #[serde(rename = "conversation_id", skip_serializing_if = "Option::is_none")] pub conversation_id: Option, } impl MultiSearchParameters { - /// Parameters for the multi search API. - pub fn new() -> MultiSearchParameters{ + /// Parameters for the multi search API. + pub fn new() -> MultiSearchParameters { MultiSearchParameters { q: None, query_by: None, @@ -280,4 +330,3 @@ impl MultiSearchParameters { } } } - diff --git a/typesense_codegen/src/models/multi_search_result.rs b/typesense_codegen/src/models/multi_search_result.rs index d3ffd67..30e4d0c 100644 --- a/typesense_codegen/src/models/multi_search_result.rs +++ b/typesense_codegen/src/models/multi_search_result.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -20,11 +19,10 @@ pub struct MultiSearchResult { } impl MultiSearchResult { - pub fn new(results: Vec>) -> MultiSearchResult{ + pub fn new(results: Vec>) -> MultiSearchResult { MultiSearchResult { results, conversation: None, } } } - diff --git a/typesense_codegen/src/models/multi_search_result_item.rs b/typesense_codegen/src/models/multi_search_result_item.rs index 6f4c8bc..7cc6252 100644 --- a/typesense_codegen/src/models/multi_search_result_item.rs +++ b/typesense_codegen/src/models/multi_search_result_item.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -42,7 +41,10 @@ pub struct MultiSearchResultItem { #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] pub conversation: Option>, /// Returned only for union query response. - #[serde(rename = "union_request_params", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "union_request_params", + skip_serializing_if = "Option::is_none" + )] pub union_request_params: Option>, /// HTTP error code #[serde(rename = "code", skip_serializing_if = "Option::is_none")] @@ -53,7 +55,7 @@ pub struct MultiSearchResultItem { } impl MultiSearchResultItem { - pub fn new() -> MultiSearchResultItem{ + pub fn new() -> MultiSearchResultItem { MultiSearchResultItem { facet_counts: None, found: None, @@ -72,4 +74,3 @@ impl MultiSearchResultItem { } } } - diff --git a/typesense_codegen/src/models/multi_search_searches_parameter.rs b/typesense_codegen/src/models/multi_search_searches_parameter.rs index f8e69d3..faded5b 100644 --- a/typesense_codegen/src/models/multi_search_searches_parameter.rs +++ b/typesense_codegen/src/models/multi_search_searches_parameter.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -21,11 +20,12 @@ pub struct MultiSearchSearchesParameter { } impl MultiSearchSearchesParameter { - pub fn new(searches: Vec) -> MultiSearchSearchesParameter{ + pub fn new( + searches: Vec, + ) -> MultiSearchSearchesParameter { MultiSearchSearchesParameter { union: None, searches, } } } - diff --git a/typesense_codegen/src/models/nl_search_model_base.rs b/typesense_codegen/src/models/nl_search_model_base.rs index 4e08735..d5c8523 100644 --- a/typesense_codegen/src/models/nl_search_model_base.rs +++ b/typesense_codegen/src/models/nl_search_model_base.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -70,7 +69,7 @@ pub struct NlSearchModelBase { } impl NlSearchModelBase { - pub fn new() -> NlSearchModelBase{ + pub fn new() -> NlSearchModelBase { NlSearchModelBase { model_name: None, api_key: None, @@ -93,4 +92,3 @@ impl NlSearchModelBase { } } } - diff --git a/typesense_codegen/src/models/nl_search_model_create_schema.rs b/typesense_codegen/src/models/nl_search_model_create_schema.rs index 4259d0a..86b3173 100644 --- a/typesense_codegen/src/models/nl_search_model_create_schema.rs +++ b/typesense_codegen/src/models/nl_search_model_create_schema.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -73,7 +72,7 @@ pub struct NlSearchModelCreateSchema { } impl NlSearchModelCreateSchema { - pub fn new() -> NlSearchModelCreateSchema{ + pub fn new() -> NlSearchModelCreateSchema { NlSearchModelCreateSchema { model_name: None, api_key: None, @@ -97,4 +96,3 @@ impl NlSearchModelCreateSchema { } } } - diff --git a/typesense_codegen/src/models/nl_search_model_delete_schema.rs b/typesense_codegen/src/models/nl_search_model_delete_schema.rs index 20dbf83..670ba3e 100644 --- a/typesense_codegen/src/models/nl_search_model_delete_schema.rs +++ b/typesense_codegen/src/models/nl_search_model_delete_schema.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,10 +18,7 @@ pub struct NlSearchModelDeleteSchema { } impl NlSearchModelDeleteSchema { - pub fn new(id: String) -> NlSearchModelDeleteSchema{ - NlSearchModelDeleteSchema { - id, - } + pub fn new(id: String) -> NlSearchModelDeleteSchema { + NlSearchModelDeleteSchema { id } } } - diff --git a/typesense_codegen/src/models/nl_search_model_schema.rs b/typesense_codegen/src/models/nl_search_model_schema.rs index 9a24637..809b9ca 100644 --- a/typesense_codegen/src/models/nl_search_model_schema.rs +++ b/typesense_codegen/src/models/nl_search_model_schema.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -73,7 +72,7 @@ pub struct NlSearchModelSchema { } impl NlSearchModelSchema { - pub fn new(id: String) -> NlSearchModelSchema{ + pub fn new(id: String) -> NlSearchModelSchema { NlSearchModelSchema { model_name: None, api_key: None, @@ -97,4 +96,3 @@ impl NlSearchModelSchema { } } } - diff --git a/typesense_codegen/src/models/preset_delete_schema.rs b/typesense_codegen/src/models/preset_delete_schema.rs index 77294d0..325f9b2 100644 --- a/typesense_codegen/src/models/preset_delete_schema.rs +++ b/typesense_codegen/src/models/preset_delete_schema.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +17,7 @@ pub struct PresetDeleteSchema { } impl PresetDeleteSchema { - pub fn new(name: String) -> PresetDeleteSchema{ - PresetDeleteSchema { - name, - } + pub fn new(name: String) -> PresetDeleteSchema { + PresetDeleteSchema { name } } } - diff --git a/typesense_codegen/src/models/preset_schema.rs b/typesense_codegen/src/models/preset_schema.rs index 8c9352c..959f873 100644 --- a/typesense_codegen/src/models/preset_schema.rs +++ b/typesense_codegen/src/models/preset_schema.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -20,11 +19,10 @@ pub struct PresetSchema { } impl PresetSchema { - pub fn new(value: models::PresetUpsertSchemaValue, name: String) -> PresetSchema{ + pub fn new(value: models::PresetUpsertSchemaValue, name: String) -> PresetSchema { PresetSchema { value: Box::new(value), name, } } } - diff --git a/typesense_codegen/src/models/preset_upsert_schema.rs b/typesense_codegen/src/models/preset_upsert_schema.rs index 92203f8..298465d 100644 --- a/typesense_codegen/src/models/preset_upsert_schema.rs +++ b/typesense_codegen/src/models/preset_upsert_schema.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +17,9 @@ pub struct PresetUpsertSchema { } impl PresetUpsertSchema { - pub fn new(value: models::PresetUpsertSchemaValue) -> PresetUpsertSchema{ + pub fn new(value: models::PresetUpsertSchemaValue) -> PresetUpsertSchema { PresetUpsertSchema { value: Box::new(value), } } } - diff --git a/typesense_codegen/src/models/preset_upsert_schema_value.rs b/typesense_codegen/src/models/preset_upsert_schema_value.rs index f6a502f..3dae812 100644 --- a/typesense_codegen/src/models/preset_upsert_schema_value.rs +++ b/typesense_codegen/src/models/preset_upsert_schema_value.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -23,4 +22,3 @@ impl Default for PresetUpsertSchemaValue { Self::SearchParameters(Default::default()) } } - diff --git a/typesense_codegen/src/models/presets_retrieve_schema.rs b/typesense_codegen/src/models/presets_retrieve_schema.rs index e13bc93..f80b028 100644 --- a/typesense_codegen/src/models/presets_retrieve_schema.rs +++ b/typesense_codegen/src/models/presets_retrieve_schema.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +17,7 @@ pub struct PresetsRetrieveSchema { } impl PresetsRetrieveSchema { - pub fn new(presets: Vec) -> PresetsRetrieveSchema{ - PresetsRetrieveSchema { - presets, - } + pub fn new(presets: Vec) -> PresetsRetrieveSchema { + PresetsRetrieveSchema { presets } } } - diff --git a/typesense_codegen/src/models/schema_change_status.rs b/typesense_codegen/src/models/schema_change_status.rs index f051a9b..f1d32b0 100644 --- a/typesense_codegen/src/models/schema_change_status.rs +++ b/typesense_codegen/src/models/schema_change_status.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -25,7 +24,7 @@ pub struct SchemaChangeStatus { } impl SchemaChangeStatus { - pub fn new() -> SchemaChangeStatus{ + pub fn new() -> SchemaChangeStatus { SchemaChangeStatus { collection: None, validated_docs: None, @@ -33,4 +32,3 @@ impl SchemaChangeStatus { } } } - diff --git a/typesense_codegen/src/models/search_grouped_hit.rs b/typesense_codegen/src/models/search_grouped_hit.rs index 73d9292..f8af648 100644 --- a/typesense_codegen/src/models/search_grouped_hit.rs +++ b/typesense_codegen/src/models/search_grouped_hit.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -23,7 +22,10 @@ pub struct SearchGroupedHit { } impl SearchGroupedHit { - pub fn new(group_key: Vec, hits: Vec>) -> SearchGroupedHit{ + pub fn new( + group_key: Vec, + hits: Vec>, + ) -> SearchGroupedHit { SearchGroupedHit { found: None, group_key, @@ -31,4 +33,3 @@ impl SearchGroupedHit { } } } - diff --git a/typesense_codegen/src/models/search_highlight.rs b/typesense_codegen/src/models/search_highlight.rs index 0b5101d..248c63c 100644 --- a/typesense_codegen/src/models/search_highlight.rs +++ b/typesense_codegen/src/models/search_highlight.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -35,7 +34,7 @@ pub struct SearchHighlight { } impl SearchHighlight { - pub fn new() -> SearchHighlight{ + pub fn new() -> SearchHighlight { SearchHighlight { field: None, snippet: None, @@ -47,4 +46,3 @@ impl SearchHighlight { } } } - diff --git a/typesense_codegen/src/models/search_override.rs b/typesense_codegen/src/models/search_override.rs index 0740e2d..981e36e 100644 --- a/typesense_codegen/src/models/search_override.rs +++ b/typesense_codegen/src/models/search_override.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -21,31 +20,37 @@ pub struct SearchOverride { /// List of document `id`s that should be excluded from the search results. #[serde(rename = "excludes", skip_serializing_if = "Option::is_none")] pub excludes: Option>, - /// A filter by clause that is applied to any search query that matches the override rule. + /// A filter by clause that is applied to any search query that matches the override rule. #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] pub filter_by: Option, - /// Indicates whether search query tokens that exist in the override's rule should be removed from the search query. - #[serde(rename = "remove_matched_tokens", skip_serializing_if = "Option::is_none")] + /// Indicates whether search query tokens that exist in the override's rule should be removed from the search query. + #[serde( + rename = "remove_matched_tokens", + skip_serializing_if = "Option::is_none" + )] pub remove_matched_tokens: Option, - /// Return a custom JSON object in the Search API response, when this rule is triggered. This can can be used to display a pre-defined message (eg: a promotion banner) on the front-end when a particular rule is triggered. + /// Return a custom JSON object in the Search API response, when this rule is triggered. This can can be used to display a pre-defined message (eg: a promotion banner) on the front-end when a particular rule is triggered. #[serde(rename = "metadata", skip_serializing_if = "Option::is_none")] pub metadata: Option, - /// A sort by clause that is applied to any search query that matches the override rule. + /// A sort by clause that is applied to any search query that matches the override rule. #[serde(rename = "sort_by", skip_serializing_if = "Option::is_none")] pub sort_by: Option, - /// Replaces the current search query with this value, when the search query matches the override rule. + /// Replaces the current search query with this value, when the search query matches the override rule. #[serde(rename = "replace_query", skip_serializing_if = "Option::is_none")] pub replace_query: Option, - /// When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. - #[serde(rename = "filter_curated_hits", skip_serializing_if = "Option::is_none")] + /// When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. + #[serde( + rename = "filter_curated_hits", + skip_serializing_if = "Option::is_none" + )] pub filter_curated_hits: Option, - /// A Unix timestamp that indicates the date/time from which the override will be active. You can use this to create override rules that start applying from a future point in time. + /// A Unix timestamp that indicates the date/time from which the override will be active. You can use this to create override rules that start applying from a future point in time. #[serde(rename = "effective_from_ts", skip_serializing_if = "Option::is_none")] pub effective_from_ts: Option, - /// A Unix timestamp that indicates the date/time until which the override will be active. You can use this to create override rules that stop applying after a period of time. + /// A Unix timestamp that indicates the date/time until which the override will be active. You can use this to create override rules that stop applying after a period of time. #[serde(rename = "effective_to_ts", skip_serializing_if = "Option::is_none")] pub effective_to_ts: Option, - /// When set to true, override processing will stop at the first matching rule. When set to false override processing will continue and multiple override actions will be triggered in sequence. Overrides are processed in the lexical sort order of their id field. Default: true. + /// When set to true, override processing will stop at the first matching rule. When set to false override processing will continue and multiple override actions will be triggered in sequence. Overrides are processed in the lexical sort order of their id field. Default: true. #[serde(rename = "stop_processing", skip_serializing_if = "Option::is_none")] pub stop_processing: Option, #[serde(rename = "id")] @@ -53,7 +58,7 @@ pub struct SearchOverride { } impl SearchOverride { - pub fn new(rule: models::SearchOverrideRule, id: String) -> SearchOverride{ + pub fn new(rule: models::SearchOverrideRule, id: String) -> SearchOverride { SearchOverride { rule: Box::new(rule), includes: None, @@ -71,4 +76,3 @@ impl SearchOverride { } } } - diff --git a/typesense_codegen/src/models/search_override_delete_response.rs b/typesense_codegen/src/models/search_override_delete_response.rs index 23bc8f4..d49997c 100644 --- a/typesense_codegen/src/models/search_override_delete_response.rs +++ b/typesense_codegen/src/models/search_override_delete_response.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,10 +18,7 @@ pub struct SearchOverrideDeleteResponse { } impl SearchOverrideDeleteResponse { - pub fn new(id: String) -> SearchOverrideDeleteResponse{ - SearchOverrideDeleteResponse { - id, - } + pub fn new(id: String) -> SearchOverrideDeleteResponse { + SearchOverrideDeleteResponse { id } } } - diff --git a/typesense_codegen/src/models/search_override_exclude.rs b/typesense_codegen/src/models/search_override_exclude.rs index e6c0dee..b79ad04 100644 --- a/typesense_codegen/src/models/search_override_exclude.rs +++ b/typesense_codegen/src/models/search_override_exclude.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,10 +18,7 @@ pub struct SearchOverrideExclude { } impl SearchOverrideExclude { - pub fn new(id: String) -> SearchOverrideExclude{ - SearchOverrideExclude { - id, - } + pub fn new(id: String) -> SearchOverrideExclude { + SearchOverrideExclude { id } } } - diff --git a/typesense_codegen/src/models/search_override_include.rs b/typesense_codegen/src/models/search_override_include.rs index 5344b55..f932f3b 100644 --- a/typesense_codegen/src/models/search_override_include.rs +++ b/typesense_codegen/src/models/search_override_include.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -22,11 +21,7 @@ pub struct SearchOverrideInclude { } impl SearchOverrideInclude { - pub fn new(id: String, position: i32) -> SearchOverrideInclude{ - SearchOverrideInclude { - id, - position, - } + pub fn new(id: String, position: i32) -> SearchOverrideInclude { + SearchOverrideInclude { id, position } } } - diff --git a/typesense_codegen/src/models/search_override_rule.rs b/typesense_codegen/src/models/search_override_rule.rs index 3ce37a4..ffd8516 100644 --- a/typesense_codegen/src/models/search_override_rule.rs +++ b/typesense_codegen/src/models/search_override_rule.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,16 +18,16 @@ pub struct SearchOverrideRule { /// Indicates what search queries should be overridden #[serde(rename = "query", skip_serializing_if = "Option::is_none")] pub query: Option, - /// Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. + /// Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. #[serde(rename = "match", skip_serializing_if = "Option::is_none")] pub r#match: Option, - /// Indicates that the override should apply when the filter_by parameter in a search query exactly matches the string specified here (including backticks, spaces, brackets, etc). + /// Indicates that the override should apply when the filter_by parameter in a search query exactly matches the string specified here (including backticks, spaces, brackets, etc). #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] pub filter_by: Option, } impl SearchOverrideRule { - pub fn new() -> SearchOverrideRule{ + pub fn new() -> SearchOverrideRule { SearchOverrideRule { tags: None, query: None, @@ -37,7 +36,7 @@ impl SearchOverrideRule { } } } -/// Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. +/// Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum Match { #[serde(rename = "exact")] @@ -51,4 +50,3 @@ impl Default for Match { Self::Exact } } - diff --git a/typesense_codegen/src/models/search_override_schema.rs b/typesense_codegen/src/models/search_override_schema.rs index 8dfdd8c..f4ebed0 100644 --- a/typesense_codegen/src/models/search_override_schema.rs +++ b/typesense_codegen/src/models/search_override_schema.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -21,37 +20,43 @@ pub struct SearchOverrideSchema { /// List of document `id`s that should be excluded from the search results. #[serde(rename = "excludes", skip_serializing_if = "Option::is_none")] pub excludes: Option>, - /// A filter by clause that is applied to any search query that matches the override rule. + /// A filter by clause that is applied to any search query that matches the override rule. #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] pub filter_by: Option, - /// Indicates whether search query tokens that exist in the override's rule should be removed from the search query. - #[serde(rename = "remove_matched_tokens", skip_serializing_if = "Option::is_none")] + /// Indicates whether search query tokens that exist in the override's rule should be removed from the search query. + #[serde( + rename = "remove_matched_tokens", + skip_serializing_if = "Option::is_none" + )] pub remove_matched_tokens: Option, - /// Return a custom JSON object in the Search API response, when this rule is triggered. This can can be used to display a pre-defined message (eg: a promotion banner) on the front-end when a particular rule is triggered. + /// Return a custom JSON object in the Search API response, when this rule is triggered. This can can be used to display a pre-defined message (eg: a promotion banner) on the front-end when a particular rule is triggered. #[serde(rename = "metadata", skip_serializing_if = "Option::is_none")] pub metadata: Option, - /// A sort by clause that is applied to any search query that matches the override rule. + /// A sort by clause that is applied to any search query that matches the override rule. #[serde(rename = "sort_by", skip_serializing_if = "Option::is_none")] pub sort_by: Option, - /// Replaces the current search query with this value, when the search query matches the override rule. + /// Replaces the current search query with this value, when the search query matches the override rule. #[serde(rename = "replace_query", skip_serializing_if = "Option::is_none")] pub replace_query: Option, - /// When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. - #[serde(rename = "filter_curated_hits", skip_serializing_if = "Option::is_none")] + /// When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. + #[serde( + rename = "filter_curated_hits", + skip_serializing_if = "Option::is_none" + )] pub filter_curated_hits: Option, - /// A Unix timestamp that indicates the date/time from which the override will be active. You can use this to create override rules that start applying from a future point in time. + /// A Unix timestamp that indicates the date/time from which the override will be active. You can use this to create override rules that start applying from a future point in time. #[serde(rename = "effective_from_ts", skip_serializing_if = "Option::is_none")] pub effective_from_ts: Option, - /// A Unix timestamp that indicates the date/time until which the override will be active. You can use this to create override rules that stop applying after a period of time. + /// A Unix timestamp that indicates the date/time until which the override will be active. You can use this to create override rules that stop applying after a period of time. #[serde(rename = "effective_to_ts", skip_serializing_if = "Option::is_none")] pub effective_to_ts: Option, - /// When set to true, override processing will stop at the first matching rule. When set to false override processing will continue and multiple override actions will be triggered in sequence. Overrides are processed in the lexical sort order of their id field. Default: true. + /// When set to true, override processing will stop at the first matching rule. When set to false override processing will continue and multiple override actions will be triggered in sequence. Overrides are processed in the lexical sort order of their id field. Default: true. #[serde(rename = "stop_processing", skip_serializing_if = "Option::is_none")] pub stop_processing: Option, } impl SearchOverrideSchema { - pub fn new(rule: models::SearchOverrideRule) -> SearchOverrideSchema{ + pub fn new(rule: models::SearchOverrideRule) -> SearchOverrideSchema { SearchOverrideSchema { rule: Box::new(rule), includes: None, @@ -68,4 +73,3 @@ impl SearchOverrideSchema { } } } - diff --git a/typesense_codegen/src/models/search_overrides_response.rs b/typesense_codegen/src/models/search_overrides_response.rs index eaef52b..c778bab 100644 --- a/typesense_codegen/src/models/search_overrides_response.rs +++ b/typesense_codegen/src/models/search_overrides_response.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +17,7 @@ pub struct SearchOverridesResponse { } impl SearchOverridesResponse { - pub fn new(overrides: Vec) -> SearchOverridesResponse{ - SearchOverridesResponse { - overrides, - } + pub fn new(overrides: Vec) -> SearchOverridesResponse { + SearchOverridesResponse { overrides } } } - diff --git a/typesense_codegen/src/models/search_parameters.rs b/typesense_codegen/src/models/search_parameters.rs index d1f8f89..9fe147c 100644 --- a/typesense_codegen/src/models/search_parameters.rs +++ b/typesense_codegen/src/models/search_parameters.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -49,7 +48,10 @@ pub struct SearchParameters { #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] pub filter_by: Option, /// Controls the number of similar words that Typesense considers during fuzzy search on filter_by values. Useful for controlling prefix matches like company_name:Acm*. - #[serde(rename = "max_filter_by_candidates", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "max_filter_by_candidates", + skip_serializing_if = "Option::is_none" + )] pub max_filter_by_candidates: Option, /// A list of numerical fields and their corresponding sort orders that will be used for ordering your results. Up to 3 sort fields can be specified. The text similarity score is exposed as a special `_text_match` field that you can use in the list of sorting fields. If no `sort_by` parameter is specified, results are sorted by `_text_match:desc,default_sorting_field:desc` #[serde(rename = "sort_by", skip_serializing_if = "Option::is_none")] @@ -63,7 +65,7 @@ pub struct SearchParameters { /// Facet values that are returned can now be filtered via this parameter. The matching facet text is also highlighted. For example, when faceting by `category`, you can set `facet_query=category:shoe` to return only facet values that contain the prefix \"shoe\". #[serde(rename = "facet_query", skip_serializing_if = "Option::is_none")] pub facet_query: Option, - /// The number of typographical errors (1 or 2) that would be tolerated. Default: 2 + /// The number of typographical errors (1 or 2) that would be tolerated. Default: 2 #[serde(rename = "num_typos", skip_serializing_if = "Option::is_none")] pub num_typos: Option, /// Results from this specific page number would be fetched. @@ -72,7 +74,7 @@ pub struct SearchParameters { /// Number of results to fetch per page. Default: 10 #[serde(rename = "per_page", skip_serializing_if = "Option::is_none")] pub per_page: Option, - /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. + /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. #[serde(rename = "limit", skip_serializing_if = "Option::is_none")] pub limit: Option, /// Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. @@ -81,11 +83,14 @@ pub struct SearchParameters { /// You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. #[serde(rename = "group_by", skip_serializing_if = "Option::is_none")] pub group_by: Option, - /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 + /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 #[serde(rename = "group_limit", skip_serializing_if = "Option::is_none")] pub group_limit: Option, - /// Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true - #[serde(rename = "group_missing_values", skip_serializing_if = "Option::is_none")] + /// Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true + #[serde( + rename = "group_missing_values", + skip_serializing_if = "Option::is_none" + )] pub group_missing_values: Option, /// List of fields from the document to include in the search result #[serde(rename = "include_fields", skip_serializing_if = "Option::is_none")] @@ -94,143 +99,194 @@ pub struct SearchParameters { #[serde(rename = "exclude_fields", skip_serializing_if = "Option::is_none")] pub exclude_fields: Option, /// List of fields which should be highlighted fully without snippeting - #[serde(rename = "highlight_full_fields", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "highlight_full_fields", + skip_serializing_if = "Option::is_none" + )] pub highlight_full_fields: Option, - /// The number of tokens that should surround the highlighted text on each side. Default: 4 - #[serde(rename = "highlight_affix_num_tokens", skip_serializing_if = "Option::is_none")] + /// The number of tokens that should surround the highlighted text on each side. Default: 4 + #[serde( + rename = "highlight_affix_num_tokens", + skip_serializing_if = "Option::is_none" + )] pub highlight_affix_num_tokens: Option, - /// The start tag used for the highlighted snippets. Default: `` - #[serde(rename = "highlight_start_tag", skip_serializing_if = "Option::is_none")] + /// The start tag used for the highlighted snippets. Default: `` + #[serde( + rename = "highlight_start_tag", + skip_serializing_if = "Option::is_none" + )] pub highlight_start_tag: Option, - /// The end tag used for the highlighted snippets. Default: `` + /// The end tag used for the highlighted snippets. Default: `` #[serde(rename = "highlight_end_tag", skip_serializing_if = "Option::is_none")] pub highlight_end_tag: Option, - /// Flag for enabling/disabling the deprecated, old highlight structure in the response. Default: true - #[serde(rename = "enable_highlight_v1", skip_serializing_if = "Option::is_none")] + /// Flag for enabling/disabling the deprecated, old highlight structure in the response. Default: true + #[serde( + rename = "enable_highlight_v1", + skip_serializing_if = "Option::is_none" + )] pub enable_highlight_v1: Option, - /// Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). + /// Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). #[serde(rename = "enable_analytics", skip_serializing_if = "Option::is_none")] pub enable_analytics: Option, - /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 + /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 #[serde(rename = "snippet_threshold", skip_serializing_if = "Option::is_none")] pub snippet_threshold: Option, /// List of synonym set names to associate with this search query #[serde(rename = "synonym_sets", skip_serializing_if = "Option::is_none")] pub synonym_sets: Option, - /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 - #[serde(rename = "drop_tokens_threshold", skip_serializing_if = "Option::is_none")] + /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 + #[serde( + rename = "drop_tokens_threshold", + skip_serializing_if = "Option::is_none" + )] pub drop_tokens_threshold: Option, #[serde(rename = "drop_tokens_mode", skip_serializing_if = "Option::is_none")] pub drop_tokens_mode: Option, - /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 - #[serde(rename = "typo_tokens_threshold", skip_serializing_if = "Option::is_none")] + /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 + #[serde( + rename = "typo_tokens_threshold", + skip_serializing_if = "Option::is_none" + )] pub typo_tokens_threshold: Option, - /// Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. - #[serde(rename = "enable_typos_for_alpha_numerical_tokens", skip_serializing_if = "Option::is_none")] + /// Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + #[serde( + rename = "enable_typos_for_alpha_numerical_tokens", + skip_serializing_if = "Option::is_none" + )] pub enable_typos_for_alpha_numerical_tokens: Option, - /// Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false - #[serde(rename = "filter_curated_hits", skip_serializing_if = "Option::is_none")] + /// Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + #[serde( + rename = "filter_curated_hits", + skip_serializing_if = "Option::is_none" + )] pub filter_curated_hits: Option, - /// If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + /// If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true #[serde(rename = "enable_synonyms", skip_serializing_if = "Option::is_none")] pub enable_synonyms: Option, - /// Allow synonym resolution on word prefixes in the query. Default: false + /// Allow synonym resolution on word prefixes in the query. Default: false #[serde(rename = "synonym_prefix", skip_serializing_if = "Option::is_none")] pub synonym_prefix: Option, - /// Allow synonym resolution on typo-corrected words in the query. Default: 0 + /// Allow synonym resolution on typo-corrected words in the query. Default: 0 #[serde(rename = "synonym_num_typos", skip_serializing_if = "Option::is_none")] pub synonym_num_typos: Option, - /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "pinned_hits", skip_serializing_if = "Option::is_none")] pub pinned_hits: Option, - /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "hidden_hits", skip_serializing_if = "Option::is_none")] pub hidden_hits: Option, /// Comma separated list of tags to trigger the curations rules that match the tags. #[serde(rename = "override_tags", skip_serializing_if = "Option::is_none")] pub override_tags: Option, - /// A list of custom fields that must be highlighted even if you don't query for them + /// A list of custom fields that must be highlighted even if you don't query for them #[serde(rename = "highlight_fields", skip_serializing_if = "Option::is_none")] pub highlight_fields: Option, - /// Treat space as typo: search for q=basket ball if q=basketball is not found or vice-versa. Splitting/joining of tokens will only be attempted if the original query produces no results. To always trigger this behavior, set value to `always``. To disable, set value to `off`. Default is `fallback`. + /// Treat space as typo: search for q=basket ball if q=basketball is not found or vice-versa. Splitting/joining of tokens will only be attempted if the original query produces no results. To always trigger this behavior, set value to `always``. To disable, set value to `off`. Default is `fallback`. #[serde(rename = "split_join_tokens", skip_serializing_if = "Option::is_none")] pub split_join_tokens: Option, - /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same - #[serde(rename = "pre_segmented_query", skip_serializing_if = "Option::is_none")] + /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same + #[serde( + rename = "pre_segmented_query", + skip_serializing_if = "Option::is_none" + )] pub pre_segmented_query: Option, - /// Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. + /// Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. #[serde(rename = "preset", skip_serializing_if = "Option::is_none")] pub preset: Option, - /// If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false + /// If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false #[serde(rename = "enable_overrides", skip_serializing_if = "Option::is_none")] pub enable_overrides: Option, - /// Set this parameter to true to ensure that an exact match is ranked above the others - #[serde(rename = "prioritize_exact_match", skip_serializing_if = "Option::is_none")] + /// Set this parameter to true to ensure that an exact match is ranked above the others + #[serde( + rename = "prioritize_exact_match", + skip_serializing_if = "Option::is_none" + )] pub prioritize_exact_match: Option, - /// Control the number of words that Typesense considers for typo and prefix searching. + /// Control the number of words that Typesense considers for typo and prefix searching. #[serde(rename = "max_candidates", skip_serializing_if = "Option::is_none")] pub max_candidates: Option, - /// Make Typesense prioritize documents where the query words appear earlier in the text. - #[serde(rename = "prioritize_token_position", skip_serializing_if = "Option::is_none")] + /// Make Typesense prioritize documents where the query words appear earlier in the text. + #[serde( + rename = "prioritize_token_position", + skip_serializing_if = "Option::is_none" + )] pub prioritize_token_position: Option, - /// Make Typesense prioritize documents where the query words appear in more number of fields. - #[serde(rename = "prioritize_num_matching_fields", skip_serializing_if = "Option::is_none")] + /// Make Typesense prioritize documents where the query words appear in more number of fields. + #[serde( + rename = "prioritize_num_matching_fields", + skip_serializing_if = "Option::is_none" + )] pub prioritize_num_matching_fields: Option, - /// Make Typesense disable typos for numerical tokens. - #[serde(rename = "enable_typos_for_numerical_tokens", skip_serializing_if = "Option::is_none")] + /// Make Typesense disable typos for numerical tokens. + #[serde( + rename = "enable_typos_for_numerical_tokens", + skip_serializing_if = "Option::is_none" + )] pub enable_typos_for_numerical_tokens: Option, - /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). + /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). #[serde(rename = "exhaustive_search", skip_serializing_if = "Option::is_none")] pub exhaustive_search: Option, - /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. + /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. #[serde(rename = "search_cutoff_ms", skip_serializing_if = "Option::is_none")] pub search_cutoff_ms: Option, - /// Enable server side caching of search query results. By default, caching is disabled. + /// Enable server side caching of search query results. By default, caching is disabled. #[serde(rename = "use_cache", skip_serializing_if = "Option::is_none")] pub use_cache: Option, - /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. + /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. #[serde(rename = "cache_ttl", skip_serializing_if = "Option::is_none")] pub cache_ttl: Option, - /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_1typo", skip_serializing_if = "Option::is_none")] pub min_len_1typo: Option, - /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_2typo", skip_serializing_if = "Option::is_none")] pub min_len_2typo: Option, - /// Vector query expression for fetching documents \"closest\" to a given query/document vector. + /// Vector query expression for fetching documents \"closest\" to a given query/document vector. #[serde(rename = "vector_query", skip_serializing_if = "Option::is_none")] pub vector_query: Option, - /// Timeout (in milliseconds) for fetching remote embeddings. - #[serde(rename = "remote_embedding_timeout_ms", skip_serializing_if = "Option::is_none")] + /// Timeout (in milliseconds) for fetching remote embeddings. + #[serde( + rename = "remote_embedding_timeout_ms", + skip_serializing_if = "Option::is_none" + )] pub remote_embedding_timeout_ms: Option, - /// Number of times to retry fetching remote embeddings. - #[serde(rename = "remote_embedding_num_tries", skip_serializing_if = "Option::is_none")] + /// Number of times to retry fetching remote embeddings. + #[serde( + rename = "remote_embedding_num_tries", + skip_serializing_if = "Option::is_none" + )] pub remote_embedding_num_tries: Option, - /// Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). + /// Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). #[serde(rename = "facet_strategy", skip_serializing_if = "Option::is_none")] pub facet_strategy: Option, - /// Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. + /// Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. #[serde(rename = "stopwords", skip_serializing_if = "Option::is_none")] pub stopwords: Option, - /// Comma separated string of nested facet fields whose parent object should be returned in facet response. - #[serde(rename = "facet_return_parent", skip_serializing_if = "Option::is_none")] + /// Comma separated string of nested facet fields whose parent object should be returned in facet response. + #[serde( + rename = "facet_return_parent", + skip_serializing_if = "Option::is_none" + )] pub facet_return_parent: Option, - /// The base64 encoded audio file in 16 khz 16-bit WAV format. + /// The base64 encoded audio file in 16 khz 16-bit WAV format. #[serde(rename = "voice_query", skip_serializing_if = "Option::is_none")] pub voice_query: Option, - /// Enable conversational search. + /// Enable conversational search. #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] pub conversation: Option, - /// The Id of Conversation Model to be used. - #[serde(rename = "conversation_model_id", skip_serializing_if = "Option::is_none")] + /// The Id of Conversation Model to be used. + #[serde( + rename = "conversation_model_id", + skip_serializing_if = "Option::is_none" + )] pub conversation_model_id: Option, - /// The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + /// The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. #[serde(rename = "conversation_id", skip_serializing_if = "Option::is_none")] pub conversation_id: Option, } impl SearchParameters { - pub fn new() -> SearchParameters{ + pub fn new() -> SearchParameters { SearchParameters { q: None, query_by: None, @@ -306,4 +362,3 @@ impl SearchParameters { } } } - diff --git a/typesense_codegen/src/models/search_request_params.rs b/typesense_codegen/src/models/search_request_params.rs index 727ebb7..43cb36d 100644 --- a/typesense_codegen/src/models/search_request_params.rs +++ b/typesense_codegen/src/models/search_request_params.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -24,7 +23,7 @@ pub struct SearchRequestParams { } impl SearchRequestParams { - pub fn new(collection_name: String, q: String, per_page: i32) -> SearchRequestParams{ + pub fn new(collection_name: String, q: String, per_page: i32) -> SearchRequestParams { SearchRequestParams { collection_name, q, @@ -33,4 +32,3 @@ impl SearchRequestParams { } } } - diff --git a/typesense_codegen/src/models/search_request_params_voice_query.rs b/typesense_codegen/src/models/search_request_params_voice_query.rs index b5fd5a3..5a91f01 100644 --- a/typesense_codegen/src/models/search_request_params_voice_query.rs +++ b/typesense_codegen/src/models/search_request_params_voice_query.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +17,9 @@ pub struct SearchRequestParamsVoiceQuery { } impl SearchRequestParamsVoiceQuery { - pub fn new() -> SearchRequestParamsVoiceQuery{ + pub fn new() -> SearchRequestParamsVoiceQuery { SearchRequestParamsVoiceQuery { transcribed_query: None, } } } - diff --git a/typesense_codegen/src/models/search_result.rs b/typesense_codegen/src/models/search_result.rs index b1630c9..2bd87b9 100644 --- a/typesense_codegen/src/models/search_result.rs +++ b/typesense_codegen/src/models/search_result.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -42,12 +41,15 @@ pub struct SearchResult { #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] pub conversation: Option>, /// Returned only for union query response. - #[serde(rename = "union_request_params", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "union_request_params", + skip_serializing_if = "Option::is_none" + )] pub union_request_params: Option>, } impl SearchResult { - pub fn new() -> SearchResult{ + pub fn new() -> SearchResult { SearchResult { facet_counts: None, found: None, @@ -64,4 +66,3 @@ impl SearchResult { } } } - diff --git a/typesense_codegen/src/models/search_result_conversation.rs b/typesense_codegen/src/models/search_result_conversation.rs index c47f800..880066e 100644 --- a/typesense_codegen/src/models/search_result_conversation.rs +++ b/typesense_codegen/src/models/search_result_conversation.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -24,7 +23,12 @@ pub struct SearchResultConversation { } impl SearchResultConversation { - pub fn new(answer: String, conversation_history: Vec, conversation_id: String, query: String) -> SearchResultConversation{ + pub fn new( + answer: String, + conversation_history: Vec, + conversation_id: String, + query: String, + ) -> SearchResultConversation { SearchResultConversation { answer, conversation_history, @@ -33,4 +37,3 @@ impl SearchResultConversation { } } } - diff --git a/typesense_codegen/src/models/search_result_hit.rs b/typesense_codegen/src/models/search_result_hit.rs index 8ffb5e4..0ab30a1 100644 --- a/typesense_codegen/src/models/search_result_hit.rs +++ b/typesense_codegen/src/models/search_result_hit.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -27,7 +26,10 @@ pub struct SearchResultHit { #[serde(rename = "text_match_info", skip_serializing_if = "Option::is_none")] pub text_match_info: Option>, /// Can be any key-value pair - #[serde(rename = "geo_distance_meters", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "geo_distance_meters", + skip_serializing_if = "Option::is_none" + )] pub geo_distance_meters: Option>, /// Distance between the query vector and matching document's vector value #[serde(rename = "vector_distance", skip_serializing_if = "Option::is_none")] @@ -40,7 +42,7 @@ pub struct SearchResultHit { } impl SearchResultHit { - pub fn new() -> SearchResultHit{ + pub fn new() -> SearchResultHit { SearchResultHit { highlights: None, highlight: None, @@ -54,4 +56,3 @@ impl SearchResultHit { } } } - diff --git a/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs b/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs index def14c5..19b072a 100644 --- a/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs +++ b/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -21,10 +20,9 @@ pub struct SearchResultHitHybridSearchInfo { impl SearchResultHitHybridSearchInfo { /// Information about hybrid search scoring - pub fn new() -> SearchResultHitHybridSearchInfo{ + pub fn new() -> SearchResultHitHybridSearchInfo { SearchResultHitHybridSearchInfo { rank_fusion_score: None, } } } - diff --git a/typesense_codegen/src/models/search_result_hit_text_match_info.rs b/typesense_codegen/src/models/search_result_hit_text_match_info.rs index 6ad7736..69b3500 100644 --- a/typesense_codegen/src/models/search_result_hit_text_match_info.rs +++ b/typesense_codegen/src/models/search_result_hit_text_match_info.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -30,7 +29,7 @@ pub struct SearchResultHitTextMatchInfo { } impl SearchResultHitTextMatchInfo { - pub fn new() -> SearchResultHitTextMatchInfo{ + pub fn new() -> SearchResultHitTextMatchInfo { SearchResultHitTextMatchInfo { best_field_score: None, best_field_weight: None, @@ -42,4 +41,3 @@ impl SearchResultHitTextMatchInfo { } } } - diff --git a/typesense_codegen/src/models/search_synonym.rs b/typesense_codegen/src/models/search_synonym.rs index 4310dab..3e2b22a 100644 --- a/typesense_codegen/src/models/search_synonym.rs +++ b/typesense_codegen/src/models/search_synonym.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -30,7 +29,7 @@ pub struct SearchSynonym { } impl SearchSynonym { - pub fn new(synonyms: Vec, id: String) -> SearchSynonym{ + pub fn new(synonyms: Vec, id: String) -> SearchSynonym { SearchSynonym { root: None, synonyms, @@ -40,4 +39,3 @@ impl SearchSynonym { } } } - diff --git a/typesense_codegen/src/models/search_synonym_delete_response.rs b/typesense_codegen/src/models/search_synonym_delete_response.rs index d138eab..8da893a 100644 --- a/typesense_codegen/src/models/search_synonym_delete_response.rs +++ b/typesense_codegen/src/models/search_synonym_delete_response.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,10 +18,7 @@ pub struct SearchSynonymDeleteResponse { } impl SearchSynonymDeleteResponse { - pub fn new(id: String) -> SearchSynonymDeleteResponse{ - SearchSynonymDeleteResponse { - id, - } + pub fn new(id: String) -> SearchSynonymDeleteResponse { + SearchSynonymDeleteResponse { id } } } - diff --git a/typesense_codegen/src/models/search_synonym_schema.rs b/typesense_codegen/src/models/search_synonym_schema.rs index 99a96a9..49aa1a5 100644 --- a/typesense_codegen/src/models/search_synonym_schema.rs +++ b/typesense_codegen/src/models/search_synonym_schema.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -28,7 +27,7 @@ pub struct SearchSynonymSchema { } impl SearchSynonymSchema { - pub fn new(synonyms: Vec) -> SearchSynonymSchema{ + pub fn new(synonyms: Vec) -> SearchSynonymSchema { SearchSynonymSchema { root: None, synonyms, @@ -37,4 +36,3 @@ impl SearchSynonymSchema { } } } - diff --git a/typesense_codegen/src/models/search_synonyms_response.rs b/typesense_codegen/src/models/search_synonyms_response.rs index eab2311..17866d6 100644 --- a/typesense_codegen/src/models/search_synonyms_response.rs +++ b/typesense_codegen/src/models/search_synonyms_response.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +17,7 @@ pub struct SearchSynonymsResponse { } impl SearchSynonymsResponse { - pub fn new(synonyms: Vec) -> SearchSynonymsResponse{ - SearchSynonymsResponse { - synonyms, - } + pub fn new(synonyms: Vec) -> SearchSynonymsResponse { + SearchSynonymsResponse { synonyms } } } - diff --git a/typesense_codegen/src/models/stemming_dictionary.rs b/typesense_codegen/src/models/stemming_dictionary.rs index 3976e9c..c2b31ee 100644 --- a/typesense_codegen/src/models/stemming_dictionary.rs +++ b/typesense_codegen/src/models/stemming_dictionary.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -22,11 +21,7 @@ pub struct StemmingDictionary { } impl StemmingDictionary { - pub fn new(id: String, words: Vec) -> StemmingDictionary{ - StemmingDictionary { - id, - words, - } + pub fn new(id: String, words: Vec) -> StemmingDictionary { + StemmingDictionary { id, words } } } - diff --git a/typesense_codegen/src/models/stemming_dictionary_words_inner.rs b/typesense_codegen/src/models/stemming_dictionary_words_inner.rs index c712b4b..a9ffaf0 100644 --- a/typesense_codegen/src/models/stemming_dictionary_words_inner.rs +++ b/typesense_codegen/src/models/stemming_dictionary_words_inner.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -22,11 +21,7 @@ pub struct StemmingDictionaryWordsInner { } impl StemmingDictionaryWordsInner { - pub fn new(word: String, root: String) -> StemmingDictionaryWordsInner{ - StemmingDictionaryWordsInner { - word, - root, - } + pub fn new(word: String, root: String) -> StemmingDictionaryWordsInner { + StemmingDictionaryWordsInner { word, root } } } - diff --git a/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs b/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs index c3b7b9c..43348b3 100644 --- a/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs +++ b/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +17,9 @@ pub struct StopwordsSetRetrieveSchema { } impl StopwordsSetRetrieveSchema { - pub fn new(stopwords: models::StopwordsSetSchema) -> StopwordsSetRetrieveSchema{ + pub fn new(stopwords: models::StopwordsSetSchema) -> StopwordsSetRetrieveSchema { StopwordsSetRetrieveSchema { stopwords: Box::new(stopwords), } } } - diff --git a/typesense_codegen/src/models/stopwords_set_schema.rs b/typesense_codegen/src/models/stopwords_set_schema.rs index bf1dace..f31e4cb 100644 --- a/typesense_codegen/src/models/stopwords_set_schema.rs +++ b/typesense_codegen/src/models/stopwords_set_schema.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -22,7 +21,7 @@ pub struct StopwordsSetSchema { } impl StopwordsSetSchema { - pub fn new(id: String, stopwords: Vec) -> StopwordsSetSchema{ + pub fn new(id: String, stopwords: Vec) -> StopwordsSetSchema { StopwordsSetSchema { id, stopwords, @@ -30,4 +29,3 @@ impl StopwordsSetSchema { } } } - diff --git a/typesense_codegen/src/models/stopwords_set_upsert_schema.rs b/typesense_codegen/src/models/stopwords_set_upsert_schema.rs index 2feb7f1..5145f5e 100644 --- a/typesense_codegen/src/models/stopwords_set_upsert_schema.rs +++ b/typesense_codegen/src/models/stopwords_set_upsert_schema.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -20,11 +19,10 @@ pub struct StopwordsSetUpsertSchema { } impl StopwordsSetUpsertSchema { - pub fn new(stopwords: Vec) -> StopwordsSetUpsertSchema{ + pub fn new(stopwords: Vec) -> StopwordsSetUpsertSchema { StopwordsSetUpsertSchema { stopwords, locale: None, } } } - diff --git a/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs b/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs index 8e26e17..a0838e4 100644 --- a/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs +++ b/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +17,7 @@ pub struct StopwordsSetsRetrieveAllSchema { } impl StopwordsSetsRetrieveAllSchema { - pub fn new(stopwords: Vec) -> StopwordsSetsRetrieveAllSchema{ - StopwordsSetsRetrieveAllSchema { - stopwords, - } + pub fn new(stopwords: Vec) -> StopwordsSetsRetrieveAllSchema { + StopwordsSetsRetrieveAllSchema { stopwords } } } - diff --git a/typesense_codegen/src/models/success_status.rs b/typesense_codegen/src/models/success_status.rs index 9b1f636..3056e25 100644 --- a/typesense_codegen/src/models/success_status.rs +++ b/typesense_codegen/src/models/success_status.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +17,7 @@ pub struct SuccessStatus { } impl SuccessStatus { - pub fn new(success: bool) -> SuccessStatus{ - SuccessStatus { - success, - } + pub fn new(success: bool) -> SuccessStatus { + SuccessStatus { success } } } - diff --git a/typesense_codegen/src/models/synonym_item_schema.rs b/typesense_codegen/src/models/synonym_item_schema.rs index 8b1d84b..ab068c8 100644 --- a/typesense_codegen/src/models/synonym_item_schema.rs +++ b/typesense_codegen/src/models/synonym_item_schema.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -31,7 +30,7 @@ pub struct SynonymItemSchema { } impl SynonymItemSchema { - pub fn new(id: String, synonyms: Vec) -> SynonymItemSchema{ + pub fn new(id: String, synonyms: Vec) -> SynonymItemSchema { SynonymItemSchema { id, synonyms, @@ -41,4 +40,3 @@ impl SynonymItemSchema { } } } - diff --git a/typesense_codegen/src/models/synonym_set_create_schema.rs b/typesense_codegen/src/models/synonym_set_create_schema.rs index c52dac9..3ec60f2 100644 --- a/typesense_codegen/src/models/synonym_set_create_schema.rs +++ b/typesense_codegen/src/models/synonym_set_create_schema.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,10 +18,7 @@ pub struct SynonymSetCreateSchema { } impl SynonymSetCreateSchema { - pub fn new(items: Vec) -> SynonymSetCreateSchema{ - SynonymSetCreateSchema { - items, - } + pub fn new(items: Vec) -> SynonymSetCreateSchema { + SynonymSetCreateSchema { items } } } - diff --git a/typesense_codegen/src/models/synonym_set_delete_schema.rs b/typesense_codegen/src/models/synonym_set_delete_schema.rs index e345e32..18f5746 100644 --- a/typesense_codegen/src/models/synonym_set_delete_schema.rs +++ b/typesense_codegen/src/models/synonym_set_delete_schema.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,10 +18,7 @@ pub struct SynonymSetDeleteSchema { } impl SynonymSetDeleteSchema { - pub fn new(name: String) -> SynonymSetDeleteSchema{ - SynonymSetDeleteSchema { - name, - } + pub fn new(name: String) -> SynonymSetDeleteSchema { + SynonymSetDeleteSchema { name } } } - diff --git a/typesense_codegen/src/models/synonym_set_schema.rs b/typesense_codegen/src/models/synonym_set_schema.rs index b500baf..dbdd6e6 100644 --- a/typesense_codegen/src/models/synonym_set_schema.rs +++ b/typesense_codegen/src/models/synonym_set_schema.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -22,11 +21,7 @@ pub struct SynonymSetSchema { } impl SynonymSetSchema { - pub fn new(items: Vec, name: String) -> SynonymSetSchema{ - SynonymSetSchema { - items, - name, - } + pub fn new(items: Vec, name: String) -> SynonymSetSchema { + SynonymSetSchema { items, name } } } - diff --git a/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs b/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs index ac28af6..ca1262b 100644 --- a/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs +++ b/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,10 +18,7 @@ pub struct SynonymSetsRetrieveSchema { } impl SynonymSetsRetrieveSchema { - pub fn new(synonym_sets: Vec) -> SynonymSetsRetrieveSchema{ - SynonymSetsRetrieveSchema { - synonym_sets, - } + pub fn new(synonym_sets: Vec) -> SynonymSetsRetrieveSchema { + SynonymSetsRetrieveSchema { synonym_sets } } } - diff --git a/typesense_codegen/src/models/toggle_slow_request_log_request.rs b/typesense_codegen/src/models/toggle_slow_request_log_request.rs index fdce446..8ed0754 100644 --- a/typesense_codegen/src/models/toggle_slow_request_log_request.rs +++ b/typesense_codegen/src/models/toggle_slow_request_log_request.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +17,9 @@ pub struct ToggleSlowRequestLogRequest { } impl ToggleSlowRequestLogRequest { - pub fn new(log_slow_requests_time_ms: i32) -> ToggleSlowRequestLogRequest{ + pub fn new(log_slow_requests_time_ms: i32) -> ToggleSlowRequestLogRequest { ToggleSlowRequestLogRequest { log_slow_requests_time_ms, } } } - diff --git a/typesense_codegen/src/models/update_documents_200_response.rs b/typesense_codegen/src/models/update_documents_200_response.rs index 48d8905..10bf4f9 100644 --- a/typesense_codegen/src/models/update_documents_200_response.rs +++ b/typesense_codegen/src/models/update_documents_200_response.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -19,10 +18,7 @@ pub struct UpdateDocuments200Response { } impl UpdateDocuments200Response { - pub fn new(num_updated: i32) -> UpdateDocuments200Response{ - UpdateDocuments200Response { - num_updated, - } + pub fn new(num_updated: i32) -> UpdateDocuments200Response { + UpdateDocuments200Response { num_updated } } } - diff --git a/typesense_codegen/src/models/update_documents_parameters.rs b/typesense_codegen/src/models/update_documents_parameters.rs index 36ce061..d1dc93f 100644 --- a/typesense_codegen/src/models/update_documents_parameters.rs +++ b/typesense_codegen/src/models/update_documents_parameters.rs @@ -2,9 +2,8 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -18,10 +17,7 @@ pub struct UpdateDocumentsParameters { } impl UpdateDocumentsParameters { - pub fn new() -> UpdateDocumentsParameters{ - UpdateDocumentsParameters { - filter_by: None, - } + pub fn new() -> UpdateDocumentsParameters { + UpdateDocumentsParameters { filter_by: None } } } - diff --git a/typesense_codegen/src/models/voice_query_model_collection_config.rs b/typesense_codegen/src/models/voice_query_model_collection_config.rs index 99cb770..9250347 100644 --- a/typesense_codegen/src/models/voice_query_model_collection_config.rs +++ b/typesense_codegen/src/models/voice_query_model_collection_config.rs @@ -2,16 +2,15 @@ * Typesense API * * An open source search engine for building delightful search experiences. - * * The version of the OpenAPI document: 30.0 - * + * * Generated by: https://openapi-generator.tech */ use crate::models; use serde::{Deserialize, Serialize}; -/// VoiceQueryModelCollectionConfig : Configuration for the voice query model +/// VoiceQueryModelCollectionConfig : Configuration for the voice query model #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct VoiceQueryModelCollectionConfig { #[serde(rename = "model_name", skip_serializing_if = "Option::is_none")] @@ -19,11 +18,8 @@ pub struct VoiceQueryModelCollectionConfig { } impl VoiceQueryModelCollectionConfig { - /// Configuration for the voice query model - pub fn new() -> VoiceQueryModelCollectionConfig{ - VoiceQueryModelCollectionConfig { - model_name: None, - } + /// Configuration for the voice query model + pub fn new() -> VoiceQueryModelCollectionConfig { + VoiceQueryModelCollectionConfig { model_name: None } } } - diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 3687251..1ef8017 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -136,5 +136,20 @@ fn task_codegen() -> Result<()> { println!("✅ Codegen task finished successfully."); println!(" Generated code is available in '{}'", OUTPUT_DIR); + + // Run cargo fmt after codegen + println!("▶️ Running cargo fmt..."); + let fmt_status = Command::new("cargo") + .arg("fmt") + .arg("--all") + .status() + .context("Failed to run cargo fmt")?; + + if !fmt_status.success() { + eprintln!("⚠️ cargo fmt failed (check your Rust installation)."); + } else { + println!("✅ Successfully formatted the code."); + } + Ok(()) } From 6a7a4122f6b66819df84fb0ec66b6531fcee2c6e Mon Sep 17 00:00:00 2001 From: RoDmitry Date: Fri, 12 Sep 2025 12:06:56 +0000 Subject: [PATCH 26/41] Refactor execute_wrapper --- typesense/src/client/mod.rs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/typesense/src/client/mod.rs b/typesense/src/client/mod.rs index 38804b4..1289404 100644 --- a/typesense/src/client/mod.rs +++ b/typesense/src/client/mod.rs @@ -140,12 +140,9 @@ use web_time::{Duration, Instant}; #[macro_export] macro_rules! execute_wrapper { ($self:ident, $call:expr) => { - $self - .client - .execute(|config: &typesense_codegen::apis::configuration::Configuration| $call(config)) - .await + $self.client.execute($call).await }; - ($self:ident, $call:expr, $params:expr) => { + ($self:ident, $call:expr, $params:ident) => { $self .client .execute( From 9d85528347e3dac64da9822ff42dbd938cf1f382 Mon Sep 17 00:00:00 2001 From: RoDmitry Date: Fri, 12 Sep 2025 12:59:22 +0000 Subject: [PATCH 27/41] collection_name ref str --- typesense/src/client/collection/document.rs | 10 ++++----- typesense/src/client/collection/documents.rs | 10 ++++----- typesense/src/client/collection/mod.rs | 22 ++++++++------------ typesense/src/client/collections.rs | 8 +++---- typesense/src/client/key.rs | 8 +++---- typesense/src/client/keys.rs | 8 +++---- typesense/src/client/mod.rs | 14 ++++++------- typesense/src/client/multi_search.rs | 8 +++---- 8 files changed, 42 insertions(+), 46 deletions(-) diff --git a/typesense/src/client/collection/document.rs b/typesense/src/client/collection/document.rs index 5f97a4b..81f5550 100644 --- a/typesense/src/client/collection/document.rs +++ b/typesense/src/client/collection/document.rs @@ -13,23 +13,23 @@ use typesense_codegen::apis::documents_api; /// This struct is created by calling a method like `client.collection("collection_name").document("document_id")` or `client.collection_of::("collection_name").document("document_id")`. /// The generic `T` represents the shape of the document and must implement `Serialize` and `DeserializeOwned`. /// If `T` is not specified, it defaults to `serde_json::Value` for schemaless interactions. -pub struct Document<'a, T = serde_json::Value> +pub struct Document<'c, 'n, T = serde_json::Value> where T: DeserializeOwned + Serialize + Send + Sync, { - pub(super) client: &'a Client, - pub(super) collection_name: String, + pub(super) client: &'c Client, + pub(super) collection_name: &'n str, pub(super) document_id: String, pub(super) _phantom: std::marker::PhantomData, } -impl<'a, T> Document<'a, T> +impl<'c, 'n, T> Document<'c, 'n, T> where T: DeserializeOwned + Serialize + Send + Sync, { /// Creates a new `Document` instance for a specific document ID. #[inline] - pub(super) fn new(client: &'a Client, collection_name: String, document_id: String) -> Self { + pub(super) fn new(client: &'c Client, collection_name: &'n str, document_id: String) -> Self { Self { client, collection_name, diff --git a/typesense/src/client/collection/documents.rs b/typesense/src/client/collection/documents.rs index 908519b..5da26aa 100644 --- a/typesense/src/client/collection/documents.rs +++ b/typesense/src/client/collection/documents.rs @@ -21,22 +21,22 @@ use typesense_codegen::{ /// This struct is generic over the document type `T`. If created via `client.collection(...)`, /// `T` defaults to `serde_json::Value`. If created via `client.collection_of::(...)`, /// `T` will be `MyType`. -pub struct Documents<'a, T = serde_json::Value> +pub struct Documents<'c, 'n, T = serde_json::Value> where T: DeserializeOwned + Serialize + Send + Sync, { - pub(super) client: &'a Client, - pub(super) collection_name: String, + pub(super) client: &'c Client, + pub(super) collection_name: &'n str, pub(super) _phantom: std::marker::PhantomData, } -impl<'a, T> Documents<'a, T> +impl<'c, 'n, T> Documents<'c, 'n, T> where T: DeserializeOwned + Serialize + Send + Sync, { /// Creates a new `Documents` instance. #[inline] - pub(super) fn new(client: &'a Client, collection_name: String) -> Self { + pub(super) fn new(client: &'c Client, collection_name: &'n str) -> Self { Self { client, collection_name, diff --git a/typesense/src/client/collection/mod.rs b/typesense/src/client/collection/mod.rs index 3d2ca26..05807fd 100644 --- a/typesense/src/client/collection/mod.rs +++ b/typesense/src/client/collection/mod.rs @@ -12,22 +12,22 @@ use typesense_codegen::{apis::collections_api, models}; /// Provides methods for interacting with a Typesense collection. /// /// This struct is created by calling `client.collection("collection_name")`. -pub struct Collection<'a, T = serde_json::Value> +pub struct Collection<'c, 'n, T = serde_json::Value> where T: DeserializeOwned + Serialize + Send + Sync, { - pub(super) client: &'a Client, - pub(super) collection_name: String, + pub(super) client: &'c Client, + pub(super) collection_name: &'n str, pub(super) _phantom: std::marker::PhantomData, } -impl<'a, T> Collection<'a, T> +impl<'c, 'n, T> Collection<'c, 'n, T> where T: DeserializeOwned + Serialize + Send + Sync, { /// Creates a new `Collection` instance. #[inline] - pub(super) fn new(client: &'a Client, collection_name: String) -> Self { + pub(super) fn new(client: &'c Client, collection_name: &'n str) -> Self { Self { client, collection_name, @@ -37,18 +37,14 @@ where /// Provides access to the document-related API endpoints for a specific collection. #[inline] - pub fn documents(&'a self) -> documents::Documents<'a, T> { - documents::Documents::new(self.client, self.collection_name.to_owned()) + pub fn documents(&self) -> documents::Documents<'c, 'n, T> { + documents::Documents::new(self.client, self.collection_name) } /// Provides access to the API endpoints for a single document within a Typesense collection. #[inline] - pub fn document(&'a self, document_id: impl Into) -> document::Document<'a, T> { - document::Document::new( - self.client, - self.collection_name.to_owned(), - document_id.into(), - ) + pub fn document(&self, document_id: impl Into) -> document::Document<'c, 'n, T> { + document::Document::new(self.client, self.collection_name, document_id.into()) } /// Retrieves the details of a collection, given its name. diff --git a/typesense/src/client/collections.rs b/typesense/src/client/collections.rs index 7273c7d..e196a84 100644 --- a/typesense/src/client/collections.rs +++ b/typesense/src/client/collections.rs @@ -14,14 +14,14 @@ use typesense_codegen::{ /// Provides methods for interacting with Typesense collections and aliases. /// /// This struct is created by calling `client.collections()`. -pub struct Collections<'a> { - pub(super) client: &'a Client, +pub struct Collections<'c> { + pub(super) client: &'c Client, } -impl<'a> Collections<'a> { +impl<'c> Collections<'c> { /// Creates a new `Collection` instance #[inline] - pub(super) fn new(client: &'a Client) -> Self { + pub(super) fn new(client: &'c Client) -> Self { Self { client } } diff --git a/typesense/src/client/key.rs b/typesense/src/client/key.rs index 3af249f..03e9536 100644 --- a/typesense/src/client/key.rs +++ b/typesense/src/client/key.rs @@ -8,15 +8,15 @@ use typesense_codegen::{apis::keys_api, models}; /// Provides methods for managing a specific Typesense API key. /// /// This struct is created by calling `client.key(key_id)`. -pub struct Key<'a> { - pub(super) client: &'a Client, +pub struct Key<'c> { + pub(super) client: &'c Client, pub(super) key_id: i64, } -impl<'a> Key<'a> { +impl<'c> Key<'c> { /// Creates a new `Key` instance for a specific key ID. #[inline] - pub(super) fn new(client: &'a Client, key_id: i64) -> Self { + pub(super) fn new(client: &'c Client, key_id: i64) -> Self { Self { client, key_id } } diff --git a/typesense/src/client/keys.rs b/typesense/src/client/keys.rs index 70dd976..a7979f0 100644 --- a/typesense/src/client/keys.rs +++ b/typesense/src/client/keys.rs @@ -14,14 +14,14 @@ use typesense_codegen::apis::keys_api; /// Provides methods for managing a collection of Typesense API keys. /// /// This struct is created by calling `client.keys()`. -pub struct Keys<'a> { - pub(super) client: &'a Client, +pub struct Keys<'c> { + pub(super) client: &'c Client, } -impl<'a> Keys<'a> { +impl<'c> Keys<'c> { /// Creates a new `Keys` instance. #[inline] - pub(super) fn new(client: &'a Client) -> Self { + pub(super) fn new(client: &'c Client) -> Self { Self { client } } diff --git a/typesense/src/client/mod.rs b/typesense/src/client/mod.rs index 1289404..9ba3e3b 100644 --- a/typesense/src/client/mod.rs +++ b/typesense/src/client/mod.rs @@ -404,11 +404,11 @@ impl Client { /// # } /// ``` #[inline] - pub fn collection_of<'a, T>(&'a self, collection_name: impl Into) -> Collection<'a, T> + pub fn collection_of<'c, 'n, T>(&'c self, collection_name: &'n str) -> Collection<'c, 'n, T> where T: DeserializeOwned + Serialize + Send + Sync, { - Collection::new(self, collection_name.into()) + Collection::new(self, collection_name) } /// Provides access to API endpoints for a specific collection using schemaless `serde_json::Value` documents. @@ -440,11 +440,11 @@ impl Client { /// # } /// ``` #[inline] - pub fn collection<'a>( - &'a self, - collection_name: impl Into, - ) -> Collection<'a, serde_json::Value> { - Collection::new(self, collection_name.into()) + pub fn collection<'c, 'n>( + &'c self, + collection_name: &'n str, + ) -> Collection<'c, 'n, serde_json::Value> { + self.collection_of(collection_name) } /// Provides access to endpoints for managing the collection of API keys. diff --git a/typesense/src/client/multi_search.rs b/typesense/src/client/multi_search.rs index 1df379b..3188a01 100644 --- a/typesense/src/client/multi_search.rs +++ b/typesense/src/client/multi_search.rs @@ -14,14 +14,14 @@ use typesense_codegen::{ /// Provides methods for performing multi-search operations across multiple collections. /// /// This struct is created by calling `client.multi_search()`. -pub struct MultiSearch<'a> { - pub(super) client: &'a Client, +pub struct MultiSearch<'c> { + pub(super) client: &'c Client, } -impl<'a> MultiSearch<'a> { +impl<'c> MultiSearch<'c> { /// Creates a new `MultiSearch` instance. #[inline] - pub(super) fn new(client: &'a Client) -> Self { + pub(super) fn new(client: &'c Client) -> Self { Self { client } } From cbabbc51ecf16a2300210eda041e4793cdea27fe Mon Sep 17 00:00:00 2001 From: RoDmitry Date: Fri, 12 Sep 2025 13:38:47 +0000 Subject: [PATCH 28/41] codegen apis ref params --- README.md | 12 +++- .../reqwest/api.mustache | 6 +- typesense/src/client/collections.rs | 21 ++---- typesense/src/client/mod.rs | 3 +- typesense_codegen/.openapi-generator/VERSION | 2 +- typesense_codegen/README.md | 2 +- typesense_codegen/src/apis/analytics_api.rs | 21 +++--- typesense_codegen/src/apis/collections_api.rs | 29 ++++---- .../src/apis/conversations_api.rs | 15 ++-- typesense_codegen/src/apis/curation_api.rs | 17 ++--- typesense_codegen/src/apis/debug_api.rs | 1 + typesense_codegen/src/apis/documents_api.rs | 69 ++++++++++--------- typesense_codegen/src/apis/health_api.rs | 1 + typesense_codegen/src/apis/keys_api.rs | 7 +- .../src/apis/nl_search_models_api.rs | 15 ++-- typesense_codegen/src/apis/operations_api.rs | 5 +- typesense_codegen/src/apis/override_api.rs | 7 +- typesense_codegen/src/apis/presets_api.rs | 13 ++-- typesense_codegen/src/apis/stemming_api.rs | 7 +- typesense_codegen/src/apis/stopwords_api.rs | 13 ++-- typesense_codegen/src/apis/synonyms_api.rs | 13 ++-- .../src/models/analytics_event.rs | 1 + .../models/analytics_event_create_response.rs | 1 + .../src/models/analytics_event_data.rs | 1 + .../src/models/analytics_events_response.rs | 1 + .../analytics_events_response_events_inner.rs | 1 + .../src/models/analytics_rule.rs | 1 + .../src/models/analytics_rule_create.rs | 1 + .../models/analytics_rule_create_params.rs | 1 + .../src/models/analytics_rule_update.rs | 1 + .../src/models/analytics_status.rs | 1 + typesense_codegen/src/models/api_key.rs | 1 + .../src/models/api_key_delete_response.rs | 1 + .../src/models/api_key_schema.rs | 1 + .../src/models/api_keys_response.rs | 1 + typesense_codegen/src/models/api_response.rs | 1 + .../src/models/api_stats_response.rs | 1 + .../src/models/collection_alias.rs | 1 + .../src/models/collection_alias_schema.rs | 1 + .../src/models/collection_aliases_response.rs | 1 + .../src/models/collection_response.rs | 1 + .../src/models/collection_schema.rs | 1 + .../src/models/collection_update_schema.rs | 1 + .../conversation_model_create_schema.rs | 1 + .../src/models/conversation_model_schema.rs | 1 + .../conversation_model_update_schema.rs | 1 + .../create_analytics_rule_200_response.rs | 1 + ...nalytics_rule_200_response_one_of_inner.rs | 1 + ...s_rule_200_response_one_of_inner_any_of.rs | 1 + .../models/create_analytics_rule_request.rs | 1 + .../src/models/debug_200_response.rs | 1 + .../models/delete_documents_200_response.rs | 1 + .../src/models/delete_documents_parameters.rs | 1 + .../delete_stopwords_set_200_response.rs | 1 + typesense_codegen/src/models/dirty_values.rs | 1 + .../src/models/drop_tokens_mode.rs | 1 + .../src/models/export_documents_parameters.rs | 1 + typesense_codegen/src/models/facet_counts.rs | 1 + .../src/models/facet_counts_counts_inner.rs | 1 + .../src/models/facet_counts_stats.rs | 1 + typesense_codegen/src/models/field.rs | 1 + typesense_codegen/src/models/field_embed.rs | 1 + .../src/models/field_embed_model_config.rs | 1 + .../src/models/get_collections_parameters.rs | 1 + typesense_codegen/src/models/health_status.rs | 1 + .../src/models/import_documents_parameters.rs | 1 + typesense_codegen/src/models/index_action.rs | 1 + ...list_stemming_dictionaries_200_response.rs | 1 + .../multi_search_collection_parameters.rs | 1 + .../src/models/multi_search_parameters.rs | 1 + .../src/models/multi_search_result.rs | 1 + .../src/models/multi_search_result_item.rs | 1 + .../models/multi_search_searches_parameter.rs | 1 + .../src/models/nl_search_model_base.rs | 1 + .../models/nl_search_model_create_schema.rs | 1 + .../models/nl_search_model_delete_schema.rs | 1 + .../src/models/nl_search_model_schema.rs | 1 + .../src/models/preset_delete_schema.rs | 1 + typesense_codegen/src/models/preset_schema.rs | 1 + .../src/models/preset_upsert_schema.rs | 1 + .../src/models/preset_upsert_schema_value.rs | 1 + .../src/models/presets_retrieve_schema.rs | 1 + .../src/models/schema_change_status.rs | 1 + .../src/models/search_grouped_hit.rs | 1 + .../src/models/search_highlight.rs | 1 + .../src/models/search_override.rs | 1 + .../models/search_override_delete_response.rs | 1 + .../src/models/search_override_exclude.rs | 1 + .../src/models/search_override_include.rs | 1 + .../src/models/search_override_rule.rs | 1 + .../src/models/search_override_schema.rs | 1 + .../src/models/search_overrides_response.rs | 1 + .../src/models/search_parameters.rs | 1 + .../src/models/search_request_params.rs | 1 + .../search_request_params_voice_query.rs | 1 + typesense_codegen/src/models/search_result.rs | 1 + .../src/models/search_result_conversation.rs | 1 + .../src/models/search_result_hit.rs | 1 + .../search_result_hit_hybrid_search_info.rs | 1 + .../search_result_hit_text_match_info.rs | 1 + .../src/models/search_synonym.rs | 1 + .../models/search_synonym_delete_response.rs | 1 + .../src/models/search_synonym_schema.rs | 1 + .../src/models/search_synonyms_response.rs | 1 + .../src/models/stemming_dictionary.rs | 1 + .../models/stemming_dictionary_words_inner.rs | 1 + .../models/stopwords_set_retrieve_schema.rs | 1 + .../src/models/stopwords_set_schema.rs | 1 + .../src/models/stopwords_set_upsert_schema.rs | 1 + .../stopwords_sets_retrieve_all_schema.rs | 1 + .../src/models/success_status.rs | 1 + .../src/models/synonym_item_schema.rs | 1 + .../src/models/synonym_set_create_schema.rs | 1 + .../src/models/synonym_set_delete_schema.rs | 1 + .../src/models/synonym_set_schema.rs | 1 + .../models/synonym_sets_retrieve_schema.rs | 1 + .../models/toggle_slow_request_log_request.rs | 1 + .../models/update_documents_200_response.rs | 1 + .../src/models/update_documents_parameters.rs | 1 + .../voice_query_model_collection_config.rs | 1 + 120 files changed, 245 insertions(+), 133 deletions(-) diff --git a/README.md b/README.md index f99ccab..192c714 100644 --- a/README.md +++ b/README.md @@ -5,14 +5,20 @@ Rust client library for Typesense | Work In Progress & Help Wanted! -OpenAPI codegen folder was generated with: +`preprocessed_openapi.yml` is generated by `xtask`. + +OpenAPI codegen folder can be regenerated with: ``` docker run --rm \ -v $PWD:/local openapitools/openapi-generator-cli generate \ - -i /local/openapi.yml \ + -i /local/preprocessed_openapi.yml \ -g rust \ - -o /local/typesense_codegen_new + -o /local/typesense_codegen \ + -t /local/openapi-generator-template \ + --additional-properties library=reqwest \ + --additional-properties supportMiddleware=true \ + --additional-properties useSingleRequestParameter=true ``` If you'd like to contribute, please join our [Slack Community](https://join.slack.com/t/typesense-community/shared_invite/zt-mx4nbsbn-AuOL89O7iBtvkz136egSJg) and say hello! diff --git a/openapi-generator-template/reqwest/api.mustache b/openapi-generator-template/reqwest/api.mustache index e64b087..428b461 100644 --- a/openapi-generator-template/reqwest/api.mustache +++ b/openapi-generator-template/reqwest/api.mustache @@ -94,7 +94,7 @@ pub enum {{{operationIdCamelCase}}}Error { {{#vendorExtensions.x-group-parameters}} pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}{{{vendorExtensions.x-rust-generic-parameter}}}(configuration: &configuration::Configuration{{#allParams}}{{#-first}}, {{! ### Params -}}params: {{{operationIdCamelCase}}}Params{{/-first}}{{/allParams}}{{! +}}params: &{{{operationIdCamelCase}}}Params{{/-first}}{{/allParams}}{{! ### Function return type }}) -> Result<{{#vendorExtensions.x-rust-return-type}}{{{.}}}{{/vendorExtensions.x-rust-return-type}}{{^vendorExtensions.x-rust-return-type}}{{#isResponseFile}}{{#supportAsync}}reqwest::Response{{/supportAsync}}{{^supportAsync}}reqwest::blocking::Response{{/supportAsync}}{{/isResponseFile}}{{^isResponseFile}}{{#supportMultipleResponses}}ResponseContent<{{{operationIdCamelCase}}}Success>{{/supportMultipleResponses}}{{^supportMultipleResponses}}{{^returnType}}(){{/returnType}}{{{returnType}}}{{/supportMultipleResponses}}{{/isResponseFile}}{{/vendorExtensions.x-rust-return-type}}, Error<{{{operationIdCamelCase}}}Error>> { {{/vendorExtensions.x-group-parameters}} @@ -132,7 +132,7 @@ pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}{{{vendorExtensi {{/allParams}} {{/vendorExtensions.x-group-parameters}} - let uri_str = format!("{}{{{path}}}", configuration.base_path{{#pathParams}}, {{{baseName}}}={{#isString}}crate::apis::urlencode({{/isString}}{{{vendorExtensions.x-rust-param-identifier}}}{{^required}}.unwrap(){{/required}}{{#required}}{{#isNullable}}.unwrap(){{/isNullable}}{{/required}}{{#isArray}}.join(",").as_ref(){{/isArray}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}.to_string(){{/isContainer}}{{/isPrimitiveType}}{{/isUuid}}{{/isString}}{{#isString}}){{/isString}}{{/pathParams}}); + let uri_str = format!("{}{{{path}}}", configuration.base_path{{#pathParams}}, {{{baseName}}}={{#isString}}crate::apis::urlencode(&{{/isString}}{{{vendorExtensions.x-rust-param-identifier}}}{{^required}}.unwrap(){{/required}}{{#required}}{{#isNullable}}.unwrap(){{/isNullable}}{{/required}}{{#isArray}}.join(",").as_ref(){{/isArray}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}.to_string(){{/isContainer}}{{/isPrimitiveType}}{{/isUuid}}{{/isString}}{{#isString}}){{/isString}}{{/pathParams}}); let mut req_builder = configuration.client.request(reqwest::Method::{{{httpMethod}}}, &uri_str); {{#queryParams}} @@ -437,7 +437,7 @@ pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}{{{vendorExtensi {{#vendorExtensions.x-rust-body-is-raw-text}} {{! If the flag is true, we generate only the raw text body logic }} {{#bodyParams}} - req_builder = req_builder.header(reqwest::header::CONTENT_TYPE, "text/plain").body({{{vendorExtensions.x-rust-param-identifier}}}); + req_builder = req_builder.header(reqwest::header::CONTENT_TYPE, "text/plain").body({{{vendorExtensions.x-rust-param-identifier}}}.to_owned()); {{/bodyParams}} {{/vendorExtensions.x-rust-body-is-raw-text}} {{! Now, handle the case where the extension is NOT present. This is the "else" block }} diff --git a/typesense/src/client/collections.rs b/typesense/src/client/collections.rs index e196a84..060bf94 100644 --- a/typesense/src/client/collections.rs +++ b/typesense/src/client/collections.rs @@ -4,10 +4,7 @@ use crate::{Client, Error, execute_wrapper}; use typesense_codegen::{ - apis::{ - collections_api::{self, GetCollectionsParams}, - configuration, - }, + apis::collections_api::{self, GetCollectionsParams}, models::{self, GetCollectionsParameters}, }; @@ -44,15 +41,11 @@ impl<'c> Collections<'c> { &self, params: GetCollectionsParameters, ) -> Result, Error> { - self.client - .execute(|config: &configuration::Configuration| { - let params_for_move = GetCollectionsParams { - exclude_fields: params.exclude_fields.clone(), - limit: params.limit, - offset: params.offset, - }; - collections_api::get_collections(config, params_for_move) - }) - .await + let params = GetCollectionsParams { + exclude_fields: params.exclude_fields, + limit: params.limit, + offset: params.offset, + }; + execute_wrapper!(self, collections_api::get_collections, params) } } diff --git a/typesense/src/client/mod.rs b/typesense/src/client/mod.rs index 9ba3e3b..1aaed1e 100644 --- a/typesense/src/client/mod.rs +++ b/typesense/src/client/mod.rs @@ -147,8 +147,7 @@ macro_rules! execute_wrapper { .client .execute( |config: &typesense_codegen::apis::configuration::Configuration| { - let params_cloned = $params.clone(); - $call(config, params_cloned) + $call(config, &$params) }, ) .await diff --git a/typesense_codegen/.openapi-generator/VERSION b/typesense_codegen/.openapi-generator/VERSION index e465da4..5e52829 100644 --- a/typesense_codegen/.openapi-generator/VERSION +++ b/typesense_codegen/.openapi-generator/VERSION @@ -1 +1 @@ -7.14.0 +7.16.0-SNAPSHOT diff --git a/typesense_codegen/README.md b/typesense_codegen/README.md index f16906b..768dcfa 100644 --- a/typesense_codegen/README.md +++ b/typesense_codegen/README.md @@ -9,7 +9,7 @@ This API client was generated by the [OpenAPI Generator](https://openapi-generat - API version: 30.0 - Package version: 30.0 -- Generator version: 7.14.0 +- Generator version: 7.16.0-SNAPSHOT - Build package: `org.openapitools.codegen.languages.RustClientCodegen` ## Installation diff --git a/typesense_codegen/src/apis/analytics_api.rs b/typesense_codegen/src/apis/analytics_api.rs index 611ea8a..2fdfbda 100644 --- a/typesense_codegen/src/apis/analytics_api.rs +++ b/typesense_codegen/src/apis/analytics_api.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech @@ -138,7 +139,7 @@ pub enum UpsertAnalyticsRuleError { /// Submit a single analytics event. The event must correspond to an existing analytics rule by name. pub async fn create_analytics_event( configuration: &configuration::Configuration, - params: CreateAnalyticsEventParams, + params: &CreateAnalyticsEventParams, ) -> Result> { let uri_str = format!("{}/analytics/events", configuration.base_path); let mut req_builder = configuration @@ -198,7 +199,7 @@ pub async fn create_analytics_event( /// Create one or more analytics rules. You can send a single rule object or an array of rule objects. pub async fn create_analytics_rule( configuration: &configuration::Configuration, - params: CreateAnalyticsRuleParams, + params: &CreateAnalyticsRuleParams, ) -> Result> { let uri_str = format!("{}/analytics/rules", configuration.base_path); let mut req_builder = configuration @@ -258,12 +259,12 @@ pub async fn create_analytics_rule( /// Permanently deletes an analytics rule, given it's name pub async fn delete_analytics_rule( configuration: &configuration::Configuration, - params: DeleteAnalyticsRuleParams, + params: &DeleteAnalyticsRuleParams, ) -> Result> { let uri_str = format!( "{}/analytics/rules/{ruleName}", configuration.base_path, - ruleName = crate::apis::urlencode(params.rule_name) + ruleName = crate::apis::urlencode(¶ms.rule_name) ); let mut req_builder = configuration .client @@ -379,7 +380,7 @@ pub async fn flush_analytics( /// Retrieve the most recent events for a user and rule. pub async fn get_analytics_events( configuration: &configuration::Configuration, - params: GetAnalyticsEventsParams, + params: &GetAnalyticsEventsParams, ) -> Result> { let uri_str = format!("{}/analytics/events", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -495,12 +496,12 @@ pub async fn get_analytics_status( /// Retrieve the details of an analytics rule, given it's name pub async fn retrieve_analytics_rule( configuration: &configuration::Configuration, - params: RetrieveAnalyticsRuleParams, + params: &RetrieveAnalyticsRuleParams, ) -> Result> { let uri_str = format!( "{}/analytics/rules/{ruleName}", configuration.base_path, - ruleName = crate::apis::urlencode(params.rule_name) + ruleName = crate::apis::urlencode(¶ms.rule_name) ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -556,7 +557,7 @@ pub async fn retrieve_analytics_rule( /// Retrieve all analytics rules. Use the optional rule_tag filter to narrow down results. pub async fn retrieve_analytics_rules( configuration: &configuration::Configuration, - params: RetrieveAnalyticsRulesParams, + params: &RetrieveAnalyticsRulesParams, ) -> Result, Error> { let uri_str = format!("{}/analytics/rules", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -616,12 +617,12 @@ pub async fn retrieve_analytics_rules( /// Upserts an analytics rule with the given name. pub async fn upsert_analytics_rule( configuration: &configuration::Configuration, - params: UpsertAnalyticsRuleParams, + params: &UpsertAnalyticsRuleParams, ) -> Result> { let uri_str = format!( "{}/analytics/rules/{ruleName}", configuration.base_path, - ruleName = crate::apis::urlencode(params.rule_name) + ruleName = crate::apis::urlencode(¶ms.rule_name) ); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); diff --git a/typesense_codegen/src/apis/collections_api.rs b/typesense_codegen/src/apis/collections_api.rs index 03cb661..fab2565 100644 --- a/typesense_codegen/src/apis/collections_api.rs +++ b/typesense_codegen/src/apis/collections_api.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech @@ -149,7 +150,7 @@ pub enum UpsertAliasError { /// When a collection is created, we give it a name and describe the fields that will be indexed from the documents added to the collection. pub async fn create_collection( configuration: &configuration::Configuration, - params: CreateCollectionParams, + params: &CreateCollectionParams, ) -> Result> { let uri_str = format!("{}/collections", configuration.base_path); let mut req_builder = configuration @@ -208,12 +209,12 @@ pub async fn create_collection( pub async fn delete_alias( configuration: &configuration::Configuration, - params: DeleteAliasParams, + params: &DeleteAliasParams, ) -> Result> { let uri_str = format!( "{}/aliases/{aliasName}", configuration.base_path, - aliasName = crate::apis::urlencode(params.alias_name) + aliasName = crate::apis::urlencode(¶ms.alias_name) ); let mut req_builder = configuration .client @@ -271,12 +272,12 @@ pub async fn delete_alias( /// Permanently drops a collection. This action cannot be undone. For large collections, this might have an impact on read latencies. pub async fn delete_collection( configuration: &configuration::Configuration, - params: DeleteCollectionParams, + params: &DeleteCollectionParams, ) -> Result> { let uri_str = format!( "{}/collections/{collectionName}", configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name) + collectionName = crate::apis::urlencode(¶ms.collection_name) ); let mut req_builder = configuration .client @@ -334,12 +335,12 @@ pub async fn delete_collection( /// Find out which collection an alias points to by fetching it pub async fn get_alias( configuration: &configuration::Configuration, - params: GetAliasParams, + params: &GetAliasParams, ) -> Result> { let uri_str = format!( "{}/aliases/{aliasName}", configuration.base_path, - aliasName = crate::apis::urlencode(params.alias_name) + aliasName = crate::apis::urlencode(¶ms.alias_name) ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -451,12 +452,12 @@ pub async fn get_aliases( /// Retrieve the details of a collection, given its name. pub async fn get_collection( configuration: &configuration::Configuration, - params: GetCollectionParams, + params: &GetCollectionParams, ) -> Result> { let uri_str = format!( "{}/collections/{collectionName}", configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name) + collectionName = crate::apis::urlencode(¶ms.collection_name) ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -512,7 +513,7 @@ pub async fn get_collection( /// Returns a summary of all your collections. The collections are returned sorted by creation date, with the most recent collections appearing first. pub async fn get_collections( configuration: &configuration::Configuration, - params: GetCollectionsParams, + params: &GetCollectionsParams, ) -> Result, Error> { let uri_str = format!("{}/collections", configuration.base_path); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -578,12 +579,12 @@ pub async fn get_collections( /// Update a collection's schema to modify the fields and their types. pub async fn update_collection( configuration: &configuration::Configuration, - params: UpdateCollectionParams, + params: &UpdateCollectionParams, ) -> Result> { let uri_str = format!( "{}/collections/{collectionName}", configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name) + collectionName = crate::apis::urlencode(¶ms.collection_name) ); let mut req_builder = configuration .client @@ -642,12 +643,12 @@ pub async fn update_collection( /// Create or update a collection alias. An alias is a virtual collection name that points to a real collection. If you're familiar with symbolic links on Linux, it's very similar to that. Aliases are useful when you want to reindex your data in the background on a new collection and switch your application to it without any changes to your code. pub async fn upsert_alias( configuration: &configuration::Configuration, - params: UpsertAliasParams, + params: &UpsertAliasParams, ) -> Result> { let uri_str = format!( "{}/aliases/{aliasName}", configuration.base_path, - aliasName = crate::apis::urlencode(params.alias_name) + aliasName = crate::apis::urlencode(¶ms.alias_name) ); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); diff --git a/typesense_codegen/src/apis/conversations_api.rs b/typesense_codegen/src/apis/conversations_api.rs index 8f6b5e3..cef0821 100644 --- a/typesense_codegen/src/apis/conversations_api.rs +++ b/typesense_codegen/src/apis/conversations_api.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech @@ -79,7 +80,7 @@ pub enum UpdateConversationModelError { /// Create a Conversation Model pub async fn create_conversation_model( configuration: &configuration::Configuration, - params: CreateConversationModelParams, + params: &CreateConversationModelParams, ) -> Result> { let uri_str = format!("{}/conversations/models", configuration.base_path); let mut req_builder = configuration @@ -139,12 +140,12 @@ pub async fn create_conversation_model( /// Delete a conversation model pub async fn delete_conversation_model( configuration: &configuration::Configuration, - params: DeleteConversationModelParams, + params: &DeleteConversationModelParams, ) -> Result> { let uri_str = format!( "{}/conversations/models/{modelId}", configuration.base_path, - modelId = crate::apis::urlencode(params.model_id) + modelId = crate::apis::urlencode(¶ms.model_id) ); let mut req_builder = configuration .client @@ -259,12 +260,12 @@ pub async fn retrieve_all_conversation_models( /// Retrieve a conversation model pub async fn retrieve_conversation_model( configuration: &configuration::Configuration, - params: RetrieveConversationModelParams, + params: &RetrieveConversationModelParams, ) -> Result> { let uri_str = format!( "{}/conversations/models/{modelId}", configuration.base_path, - modelId = crate::apis::urlencode(params.model_id) + modelId = crate::apis::urlencode(¶ms.model_id) ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -320,12 +321,12 @@ pub async fn retrieve_conversation_model( /// Update a conversation model pub async fn update_conversation_model( configuration: &configuration::Configuration, - params: UpdateConversationModelParams, + params: &UpdateConversationModelParams, ) -> Result> { let uri_str = format!( "{}/conversations/models/{modelId}", configuration.base_path, - modelId = crate::apis::urlencode(params.model_id) + modelId = crate::apis::urlencode(¶ms.model_id) ); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); diff --git a/typesense_codegen/src/apis/curation_api.rs b/typesense_codegen/src/apis/curation_api.rs index 853f07a..6a05944 100644 --- a/typesense_codegen/src/apis/curation_api.rs +++ b/typesense_codegen/src/apis/curation_api.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech @@ -64,13 +65,13 @@ pub enum UpsertSearchOverrideError { pub async fn delete_search_override( configuration: &configuration::Configuration, - params: DeleteSearchOverrideParams, + params: &DeleteSearchOverrideParams, ) -> Result> { let uri_str = format!( "{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name), - overrideId = crate::apis::urlencode(params.override_id) + collectionName = crate::apis::urlencode(¶ms.collection_name), + overrideId = crate::apis::urlencode(¶ms.override_id) ); let mut req_builder = configuration .client @@ -127,12 +128,12 @@ pub async fn delete_search_override( pub async fn get_search_overrides( configuration: &configuration::Configuration, - params: GetSearchOverridesParams, + params: &GetSearchOverridesParams, ) -> Result> { let uri_str = format!( "{}/collections/{collectionName}/overrides", configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name) + collectionName = crate::apis::urlencode(¶ms.collection_name) ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -188,13 +189,13 @@ pub async fn get_search_overrides( /// Create or update an override to promote certain documents over others. Using overrides, you can include or exclude specific documents for a given query. pub async fn upsert_search_override( configuration: &configuration::Configuration, - params: UpsertSearchOverrideParams, + params: &UpsertSearchOverrideParams, ) -> Result> { let uri_str = format!( "{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name), - overrideId = crate::apis::urlencode(params.override_id) + collectionName = crate::apis::urlencode(¶ms.collection_name), + overrideId = crate::apis::urlencode(¶ms.override_id) ); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); diff --git a/typesense_codegen/src/apis/debug_api.rs b/typesense_codegen/src/apis/debug_api.rs index 2d90714..86fc9ea 100644 --- a/typesense_codegen/src/apis/debug_api.rs +++ b/typesense_codegen/src/apis/debug_api.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/apis/documents_api.rs b/typesense_codegen/src/apis/documents_api.rs index 3fcc069..48c2b31 100644 --- a/typesense_codegen/src/apis/documents_api.rs +++ b/typesense_codegen/src/apis/documents_api.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech @@ -402,13 +403,13 @@ pub enum UpsertSearchOverrideError { /// Delete an individual document from a collection by using its ID. pub async fn delete_document( configuration: &configuration::Configuration, - params: DeleteDocumentParams, + params: &DeleteDocumentParams, ) -> Result> { let uri_str = format!( "{}/collections/{collectionName}/documents/{documentId}", configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name), - documentId = crate::apis::urlencode(params.document_id) + collectionName = crate::apis::urlencode(¶ms.collection_name), + documentId = crate::apis::urlencode(¶ms.document_id) ); let mut req_builder = configuration .client @@ -466,12 +467,12 @@ pub async fn delete_document( /// Delete a bunch of documents that match a specific filter condition. Use the `batch_size` parameter to control the number of documents that should deleted at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. pub async fn delete_documents( configuration: &configuration::Configuration, - params: DeleteDocumentsParams, + params: &DeleteDocumentsParams, ) -> Result> { let uri_str = format!( "{}/collections/{collectionName}/documents", configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name) + collectionName = crate::apis::urlencode(¶ms.collection_name) ); let mut req_builder = configuration .client @@ -540,13 +541,13 @@ pub async fn delete_documents( pub async fn delete_search_override( configuration: &configuration::Configuration, - params: DeleteSearchOverrideParams, + params: &DeleteSearchOverrideParams, ) -> Result> { let uri_str = format!( "{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name), - overrideId = crate::apis::urlencode(params.override_id) + collectionName = crate::apis::urlencode(¶ms.collection_name), + overrideId = crate::apis::urlencode(¶ms.override_id) ); let mut req_builder = configuration .client @@ -604,12 +605,12 @@ pub async fn delete_search_override( /// Export all documents in a collection in JSON lines format. pub async fn export_documents( configuration: &configuration::Configuration, - params: ExportDocumentsParams, + params: &ExportDocumentsParams, ) -> Result> { let uri_str = format!( "{}/collections/{collectionName}/documents/export", configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name) + collectionName = crate::apis::urlencode(¶ms.collection_name) ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -669,13 +670,13 @@ pub async fn export_documents( /// Fetch an individual document from a collection by using its ID. pub async fn get_document( configuration: &configuration::Configuration, - params: GetDocumentParams, + params: &GetDocumentParams, ) -> Result> { let uri_str = format!( "{}/collections/{collectionName}/documents/{documentId}", configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name), - documentId = crate::apis::urlencode(params.document_id) + collectionName = crate::apis::urlencode(¶ms.collection_name), + documentId = crate::apis::urlencode(¶ms.document_id) ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -731,13 +732,13 @@ pub async fn get_document( /// Retrieve the details of a search override, given its id. pub async fn get_search_override( configuration: &configuration::Configuration, - params: GetSearchOverrideParams, + params: &GetSearchOverrideParams, ) -> Result> { let uri_str = format!( "{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name), - overrideId = crate::apis::urlencode(params.override_id) + collectionName = crate::apis::urlencode(¶ms.collection_name), + overrideId = crate::apis::urlencode(¶ms.override_id) ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -792,12 +793,12 @@ pub async fn get_search_override( pub async fn get_search_overrides( configuration: &configuration::Configuration, - params: GetSearchOverridesParams, + params: &GetSearchOverridesParams, ) -> Result> { let uri_str = format!( "{}/collections/{collectionName}/overrides", configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name) + collectionName = crate::apis::urlencode(¶ms.collection_name) ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -853,12 +854,12 @@ pub async fn get_search_overrides( /// The documents to be imported must be formatted in a newline delimited JSON structure. You can feed the output file from a Typesense export operation directly as import. pub async fn import_documents( configuration: &configuration::Configuration, - params: ImportDocumentsParams, + params: &ImportDocumentsParams, ) -> Result> { let uri_str = format!( "{}/collections/{collectionName}/documents/import", configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name) + collectionName = crate::apis::urlencode(¶ms.collection_name) ); let mut req_builder = configuration .client @@ -896,7 +897,7 @@ pub async fn import_documents( }; req_builder = req_builder .header(reqwest::header::CONTENT_TYPE, "text/plain") - .body(params.body); + .body(params.body.to_owned()); let req = req_builder.build()?; let resp = configuration.client.execute(req).await?; @@ -933,12 +934,12 @@ pub async fn import_documents( /// A document to be indexed in a given collection must conform to the schema of the collection. pub async fn index_document( configuration: &configuration::Configuration, - params: IndexDocumentParams, + params: &IndexDocumentParams, ) -> Result> { let uri_str = format!( "{}/collections/{collectionName}/documents", configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name) + collectionName = crate::apis::urlencode(¶ms.collection_name) ); let mut req_builder = configuration .client @@ -1003,7 +1004,7 @@ pub async fn index_document( /// This is especially useful to avoid round-trip network latencies incurred otherwise if each of these requests are sent in separate HTTP requests. You can also use this feature to do a federated search across multiple collections in a single HTTP request. pub async fn multi_search( configuration: &configuration::Configuration, - params: MultiSearchParams, + params: &MultiSearchParams, ) -> Result> { let uri_str = format!("{}/multi_search", configuration.base_path); let mut req_builder = configuration @@ -1265,12 +1266,12 @@ pub async fn multi_search( /// Search for documents in a collection that match the search criteria. pub async fn search_collection serde::Deserialize<'de> + Serialize>( configuration: &configuration::Configuration, - params: SearchCollectionParams, + params: &SearchCollectionParams, ) -> Result, Error> { let uri_str = format!( "{}/collections/{collectionName}/documents/search", configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name) + collectionName = crate::apis::urlencode(¶ms.collection_name) ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -1549,13 +1550,13 @@ pub async fn search_collection serde::Deserialize<'de> + Serialize>( /// Update an individual document from a collection by using its ID. The update can be partial. pub async fn update_document( configuration: &configuration::Configuration, - params: UpdateDocumentParams, + params: &UpdateDocumentParams, ) -> Result> { let uri_str = format!( "{}/collections/{collectionName}/documents/{documentId}", configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name), - documentId = crate::apis::urlencode(params.document_id) + collectionName = crate::apis::urlencode(¶ms.collection_name), + documentId = crate::apis::urlencode(¶ms.document_id) ); let mut req_builder = configuration .client @@ -1617,12 +1618,12 @@ pub async fn update_document( /// The filter_by query parameter is used to filter to specify a condition against which the documents are matched. The request body contains the fields that should be updated for any documents that match the filter condition. This endpoint is only available if the Typesense server is version `0.25.0.rc12` or later. pub async fn update_documents( configuration: &configuration::Configuration, - params: UpdateDocumentsParams, + params: &UpdateDocumentsParams, ) -> Result> { let uri_str = format!( "{}/collections/{collectionName}/documents", configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name) + collectionName = crate::apis::urlencode(¶ms.collection_name) ); let mut req_builder = configuration .client @@ -1684,13 +1685,13 @@ pub async fn update_documents( /// Create or update an override to promote certain documents over others. Using overrides, you can include or exclude specific documents for a given query. pub async fn upsert_search_override( configuration: &configuration::Configuration, - params: UpsertSearchOverrideParams, + params: &UpsertSearchOverrideParams, ) -> Result> { let uri_str = format!( "{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name), - overrideId = crate::apis::urlencode(params.override_id) + collectionName = crate::apis::urlencode(¶ms.collection_name), + overrideId = crate::apis::urlencode(¶ms.override_id) ); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); diff --git a/typesense_codegen/src/apis/health_api.rs b/typesense_codegen/src/apis/health_api.rs index d615a43..1a61750 100644 --- a/typesense_codegen/src/apis/health_api.rs +++ b/typesense_codegen/src/apis/health_api.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/apis/keys_api.rs b/typesense_codegen/src/apis/keys_api.rs index dc1b6a7..9a1b350 100644 --- a/typesense_codegen/src/apis/keys_api.rs +++ b/typesense_codegen/src/apis/keys_api.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech @@ -69,7 +70,7 @@ pub enum GetKeysError { /// Create an API Key with fine-grain access control. You can restrict access on both a per-collection and per-action level. The generated key is returned only during creation. You want to store this key carefully in a secure place. pub async fn create_key( configuration: &configuration::Configuration, - params: CreateKeyParams, + params: &CreateKeyParams, ) -> Result> { let uri_str = format!("{}/keys", configuration.base_path); let mut req_builder = configuration @@ -128,7 +129,7 @@ pub async fn create_key( pub async fn delete_key( configuration: &configuration::Configuration, - params: DeleteKeyParams, + params: &DeleteKeyParams, ) -> Result> { let uri_str = format!( "{}/keys/{keyId}", @@ -191,7 +192,7 @@ pub async fn delete_key( /// Retrieve (metadata about) a key. Only the key prefix is returned when you retrieve a key. Due to security reasons, only the create endpoint returns the full API key. pub async fn get_key( configuration: &configuration::Configuration, - params: GetKeyParams, + params: &GetKeyParams, ) -> Result> { let uri_str = format!( "{}/keys/{keyId}", diff --git a/typesense_codegen/src/apis/nl_search_models_api.rs b/typesense_codegen/src/apis/nl_search_models_api.rs index 2672a9b..dfe3f42 100644 --- a/typesense_codegen/src/apis/nl_search_models_api.rs +++ b/typesense_codegen/src/apis/nl_search_models_api.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech @@ -85,7 +86,7 @@ pub enum UpdateNlSearchModelError { /// Create a new NL search model. pub async fn create_nl_search_model( configuration: &configuration::Configuration, - params: CreateNlSearchModelParams, + params: &CreateNlSearchModelParams, ) -> Result> { let uri_str = format!("{}/nl_search_models", configuration.base_path); let mut req_builder = configuration @@ -145,12 +146,12 @@ pub async fn create_nl_search_model( /// Delete a specific NL search model by its ID. pub async fn delete_nl_search_model( configuration: &configuration::Configuration, - params: DeleteNlSearchModelParams, + params: &DeleteNlSearchModelParams, ) -> Result> { let uri_str = format!( "{}/nl_search_models/{modelId}", configuration.base_path, - modelId = crate::apis::urlencode(params.model_id) + modelId = crate::apis::urlencode(¶ms.model_id) ); let mut req_builder = configuration .client @@ -264,12 +265,12 @@ pub async fn retrieve_all_nl_search_models( /// Retrieve a specific NL search model by its ID. pub async fn retrieve_nl_search_model( configuration: &configuration::Configuration, - params: RetrieveNlSearchModelParams, + params: &RetrieveNlSearchModelParams, ) -> Result> { let uri_str = format!( "{}/nl_search_models/{modelId}", configuration.base_path, - modelId = crate::apis::urlencode(params.model_id) + modelId = crate::apis::urlencode(¶ms.model_id) ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -325,12 +326,12 @@ pub async fn retrieve_nl_search_model( /// Update an existing NL search model. pub async fn update_nl_search_model( configuration: &configuration::Configuration, - params: UpdateNlSearchModelParams, + params: &UpdateNlSearchModelParams, ) -> Result> { let uri_str = format!( "{}/nl_search_models/{modelId}", configuration.base_path, - modelId = crate::apis::urlencode(params.model_id) + modelId = crate::apis::urlencode(¶ms.model_id) ); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); diff --git a/typesense_codegen/src/apis/operations_api.rs b/typesense_codegen/src/apis/operations_api.rs index e111439..ab149ed 100644 --- a/typesense_codegen/src/apis/operations_api.rs +++ b/typesense_codegen/src/apis/operations_api.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech @@ -368,7 +369,7 @@ pub async fn retrieve_metrics( /// Creates a point-in-time snapshot of a Typesense node's state and data in the specified directory. You can then backup the snapshot directory that gets created and later restore it as a data directory, as needed. pub async fn take_snapshot( configuration: &configuration::Configuration, - params: TakeSnapshotParams, + params: &TakeSnapshotParams, ) -> Result> { let uri_str = format!("{}/operations/snapshot", configuration.base_path); let mut req_builder = configuration @@ -428,7 +429,7 @@ pub async fn take_snapshot( /// Enable logging of requests that take over a defined threshold of time. Default is `-1` which disables slow request logging. Slow requests are logged to the primary log file, with the prefix SLOW REQUEST. pub async fn toggle_slow_request_log( configuration: &configuration::Configuration, - params: ToggleSlowRequestLogParams, + params: &ToggleSlowRequestLogParams, ) -> Result> { let uri_str = format!("{}/config", configuration.base_path); let mut req_builder = configuration diff --git a/typesense_codegen/src/apis/override_api.rs b/typesense_codegen/src/apis/override_api.rs index 58b33a3..119ae1a 100644 --- a/typesense_codegen/src/apis/override_api.rs +++ b/typesense_codegen/src/apis/override_api.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech @@ -31,13 +32,13 @@ pub enum GetSearchOverrideError { /// Retrieve the details of a search override, given its id. pub async fn get_search_override( configuration: &configuration::Configuration, - params: GetSearchOverrideParams, + params: &GetSearchOverrideParams, ) -> Result> { let uri_str = format!( "{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, - collectionName = crate::apis::urlencode(params.collection_name), - overrideId = crate::apis::urlencode(params.override_id) + collectionName = crate::apis::urlencode(¶ms.collection_name), + overrideId = crate::apis::urlencode(¶ms.override_id) ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); diff --git a/typesense_codegen/src/apis/presets_api.rs b/typesense_codegen/src/apis/presets_api.rs index 1f8722c..1786754 100644 --- a/typesense_codegen/src/apis/presets_api.rs +++ b/typesense_codegen/src/apis/presets_api.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech @@ -69,12 +70,12 @@ pub enum UpsertPresetError { /// Permanently deletes a preset, given it's name. pub async fn delete_preset( configuration: &configuration::Configuration, - params: DeletePresetParams, + params: &DeletePresetParams, ) -> Result> { let uri_str = format!( "{}/presets/{presetId}", configuration.base_path, - presetId = crate::apis::urlencode(params.preset_id) + presetId = crate::apis::urlencode(¶ms.preset_id) ); let mut req_builder = configuration .client @@ -188,12 +189,12 @@ pub async fn retrieve_all_presets( /// Retrieve the details of a preset, given it's name. pub async fn retrieve_preset( configuration: &configuration::Configuration, - params: RetrievePresetParams, + params: &RetrievePresetParams, ) -> Result> { let uri_str = format!( "{}/presets/{presetId}", configuration.base_path, - presetId = crate::apis::urlencode(params.preset_id) + presetId = crate::apis::urlencode(¶ms.preset_id) ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -249,12 +250,12 @@ pub async fn retrieve_preset( /// Create or update an existing preset. pub async fn upsert_preset( configuration: &configuration::Configuration, - params: UpsertPresetParams, + params: &UpsertPresetParams, ) -> Result> { let uri_str = format!( "{}/presets/{presetId}", configuration.base_path, - presetId = crate::apis::urlencode(params.preset_id) + presetId = crate::apis::urlencode(¶ms.preset_id) ); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); diff --git a/typesense_codegen/src/apis/stemming_api.rs b/typesense_codegen/src/apis/stemming_api.rs index a8c0c2b..586048e 100644 --- a/typesense_codegen/src/apis/stemming_api.rs +++ b/typesense_codegen/src/apis/stemming_api.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech @@ -54,12 +55,12 @@ pub enum ListStemmingDictionariesError { /// Fetch details of a specific stemming dictionary. pub async fn get_stemming_dictionary( configuration: &configuration::Configuration, - params: GetStemmingDictionaryParams, + params: &GetStemmingDictionaryParams, ) -> Result> { let uri_str = format!( "{}/stemming/dictionaries/{dictionaryId}", configuration.base_path, - dictionaryId = crate::apis::urlencode(params.dictionary_id) + dictionaryId = crate::apis::urlencode(¶ms.dictionary_id) ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -115,7 +116,7 @@ pub async fn get_stemming_dictionary( /// Upload a JSONL file containing word mappings to create or update a stemming dictionary. pub async fn import_stemming_dictionary( configuration: &configuration::Configuration, - params: ImportStemmingDictionaryParams, + params: &ImportStemmingDictionaryParams, ) -> Result> { let uri_str = format!("{}/stemming/dictionaries/import", configuration.base_path); let mut req_builder = configuration diff --git a/typesense_codegen/src/apis/stopwords_api.rs b/typesense_codegen/src/apis/stopwords_api.rs index b60555a..fea216c 100644 --- a/typesense_codegen/src/apis/stopwords_api.rs +++ b/typesense_codegen/src/apis/stopwords_api.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech @@ -69,12 +70,12 @@ pub enum UpsertStopwordsSetError { /// Permanently deletes a stopwords set, given it's name. pub async fn delete_stopwords_set( configuration: &configuration::Configuration, - params: DeleteStopwordsSetParams, + params: &DeleteStopwordsSetParams, ) -> Result> { let uri_str = format!( "{}/stopwords/{setId}", configuration.base_path, - setId = crate::apis::urlencode(params.set_id) + setId = crate::apis::urlencode(¶ms.set_id) ); let mut req_builder = configuration .client @@ -132,12 +133,12 @@ pub async fn delete_stopwords_set( /// Retrieve the details of a stopwords set, given it's name. pub async fn retrieve_stopwords_set( configuration: &configuration::Configuration, - params: RetrieveStopwordsSetParams, + params: &RetrieveStopwordsSetParams, ) -> Result> { let uri_str = format!( "{}/stopwords/{setId}", configuration.base_path, - setId = crate::apis::urlencode(params.set_id) + setId = crate::apis::urlencode(¶ms.set_id) ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -249,12 +250,12 @@ pub async fn retrieve_stopwords_sets( /// When an analytics rule is created, we give it a name and describe the type, the source collections and the destination collection. pub async fn upsert_stopwords_set( configuration: &configuration::Configuration, - params: UpsertStopwordsSetParams, + params: &UpsertStopwordsSetParams, ) -> Result> { let uri_str = format!( "{}/stopwords/{setId}", configuration.base_path, - setId = crate::apis::urlencode(params.set_id) + setId = crate::apis::urlencode(¶ms.set_id) ); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); diff --git a/typesense_codegen/src/apis/synonyms_api.rs b/typesense_codegen/src/apis/synonyms_api.rs index 70d92ce..2bd3580 100644 --- a/typesense_codegen/src/apis/synonyms_api.rs +++ b/typesense_codegen/src/apis/synonyms_api.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech @@ -69,12 +70,12 @@ pub enum UpsertSynonymSetError { /// Delete a specific synonym set by its name pub async fn delete_synonym_set( configuration: &configuration::Configuration, - params: DeleteSynonymSetParams, + params: &DeleteSynonymSetParams, ) -> Result> { let uri_str = format!( "{}/synonym_sets/{synonymSetName}", configuration.base_path, - synonymSetName = crate::apis::urlencode(params.synonym_set_name) + synonymSetName = crate::apis::urlencode(¶ms.synonym_set_name) ); let mut req_builder = configuration .client @@ -132,12 +133,12 @@ pub async fn delete_synonym_set( /// Retrieve a specific synonym set by its name pub async fn retrieve_synonym_set( configuration: &configuration::Configuration, - params: RetrieveSynonymSetParams, + params: &RetrieveSynonymSetParams, ) -> Result> { let uri_str = format!( "{}/synonym_sets/{synonymSetName}", configuration.base_path, - synonymSetName = crate::apis::urlencode(params.synonym_set_name) + synonymSetName = crate::apis::urlencode(¶ms.synonym_set_name) ); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); @@ -249,12 +250,12 @@ pub async fn retrieve_synonym_sets( /// Create or update a synonym set with the given name pub async fn upsert_synonym_set( configuration: &configuration::Configuration, - params: UpsertSynonymSetParams, + params: &UpsertSynonymSetParams, ) -> Result> { let uri_str = format!( "{}/synonym_sets/{synonymSetName}", configuration.base_path, - synonymSetName = crate::apis::urlencode(params.synonym_set_name) + synonymSetName = crate::apis::urlencode(¶ms.synonym_set_name) ); let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); diff --git a/typesense_codegen/src/models/analytics_event.rs b/typesense_codegen/src/models/analytics_event.rs index 805e7e3..7ab05e0 100644 --- a/typesense_codegen/src/models/analytics_event.rs +++ b/typesense_codegen/src/models/analytics_event.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/analytics_event_create_response.rs b/typesense_codegen/src/models/analytics_event_create_response.rs index 9f2b9fa..2018290 100644 --- a/typesense_codegen/src/models/analytics_event_create_response.rs +++ b/typesense_codegen/src/models/analytics_event_create_response.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/analytics_event_data.rs b/typesense_codegen/src/models/analytics_event_data.rs index e4bf678..7c28241 100644 --- a/typesense_codegen/src/models/analytics_event_data.rs +++ b/typesense_codegen/src/models/analytics_event_data.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/analytics_events_response.rs b/typesense_codegen/src/models/analytics_events_response.rs index a218617..a0de4e0 100644 --- a/typesense_codegen/src/models/analytics_events_response.rs +++ b/typesense_codegen/src/models/analytics_events_response.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/analytics_events_response_events_inner.rs b/typesense_codegen/src/models/analytics_events_response_events_inner.rs index 971fbdc..9744a20 100644 --- a/typesense_codegen/src/models/analytics_events_response_events_inner.rs +++ b/typesense_codegen/src/models/analytics_events_response_events_inner.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/analytics_rule.rs b/typesense_codegen/src/models/analytics_rule.rs index 31a29ea..4c01197 100644 --- a/typesense_codegen/src/models/analytics_rule.rs +++ b/typesense_codegen/src/models/analytics_rule.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/analytics_rule_create.rs b/typesense_codegen/src/models/analytics_rule_create.rs index 819bde2..b9f8993 100644 --- a/typesense_codegen/src/models/analytics_rule_create.rs +++ b/typesense_codegen/src/models/analytics_rule_create.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/analytics_rule_create_params.rs b/typesense_codegen/src/models/analytics_rule_create_params.rs index e53c4db..6127dd3 100644 --- a/typesense_codegen/src/models/analytics_rule_create_params.rs +++ b/typesense_codegen/src/models/analytics_rule_create_params.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/analytics_rule_update.rs b/typesense_codegen/src/models/analytics_rule_update.rs index 68015ed..3a42cc4 100644 --- a/typesense_codegen/src/models/analytics_rule_update.rs +++ b/typesense_codegen/src/models/analytics_rule_update.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/analytics_status.rs b/typesense_codegen/src/models/analytics_status.rs index ffed203..ee3f151 100644 --- a/typesense_codegen/src/models/analytics_status.rs +++ b/typesense_codegen/src/models/analytics_status.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/api_key.rs b/typesense_codegen/src/models/api_key.rs index 2fce4d2..511f8b9 100644 --- a/typesense_codegen/src/models/api_key.rs +++ b/typesense_codegen/src/models/api_key.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/api_key_delete_response.rs b/typesense_codegen/src/models/api_key_delete_response.rs index 1969865..b9b453e 100644 --- a/typesense_codegen/src/models/api_key_delete_response.rs +++ b/typesense_codegen/src/models/api_key_delete_response.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/api_key_schema.rs b/typesense_codegen/src/models/api_key_schema.rs index 585aeef..095e5ec 100644 --- a/typesense_codegen/src/models/api_key_schema.rs +++ b/typesense_codegen/src/models/api_key_schema.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/api_keys_response.rs b/typesense_codegen/src/models/api_keys_response.rs index 5a4a893..784a6bf 100644 --- a/typesense_codegen/src/models/api_keys_response.rs +++ b/typesense_codegen/src/models/api_keys_response.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/api_response.rs b/typesense_codegen/src/models/api_response.rs index b6b5a90..0a27c4f 100644 --- a/typesense_codegen/src/models/api_response.rs +++ b/typesense_codegen/src/models/api_response.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/api_stats_response.rs b/typesense_codegen/src/models/api_stats_response.rs index efd8b83..c35c77a 100644 --- a/typesense_codegen/src/models/api_stats_response.rs +++ b/typesense_codegen/src/models/api_stats_response.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/collection_alias.rs b/typesense_codegen/src/models/collection_alias.rs index 8b6623e..b5a61fe 100644 --- a/typesense_codegen/src/models/collection_alias.rs +++ b/typesense_codegen/src/models/collection_alias.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/collection_alias_schema.rs b/typesense_codegen/src/models/collection_alias_schema.rs index 8bb1001..b35d641 100644 --- a/typesense_codegen/src/models/collection_alias_schema.rs +++ b/typesense_codegen/src/models/collection_alias_schema.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/collection_aliases_response.rs b/typesense_codegen/src/models/collection_aliases_response.rs index ab2b741..3cf2d25 100644 --- a/typesense_codegen/src/models/collection_aliases_response.rs +++ b/typesense_codegen/src/models/collection_aliases_response.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/collection_response.rs b/typesense_codegen/src/models/collection_response.rs index d65cc95..1039909 100644 --- a/typesense_codegen/src/models/collection_response.rs +++ b/typesense_codegen/src/models/collection_response.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/collection_schema.rs b/typesense_codegen/src/models/collection_schema.rs index 177ff60..b861bee 100644 --- a/typesense_codegen/src/models/collection_schema.rs +++ b/typesense_codegen/src/models/collection_schema.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/collection_update_schema.rs b/typesense_codegen/src/models/collection_update_schema.rs index 4446d29..27a4d09 100644 --- a/typesense_codegen/src/models/collection_update_schema.rs +++ b/typesense_codegen/src/models/collection_update_schema.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/conversation_model_create_schema.rs b/typesense_codegen/src/models/conversation_model_create_schema.rs index 418b696..fc587c3 100644 --- a/typesense_codegen/src/models/conversation_model_create_schema.rs +++ b/typesense_codegen/src/models/conversation_model_create_schema.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/conversation_model_schema.rs b/typesense_codegen/src/models/conversation_model_schema.rs index 356d03f..1738f77 100644 --- a/typesense_codegen/src/models/conversation_model_schema.rs +++ b/typesense_codegen/src/models/conversation_model_schema.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/conversation_model_update_schema.rs b/typesense_codegen/src/models/conversation_model_update_schema.rs index 636bcde..1335019 100644 --- a/typesense_codegen/src/models/conversation_model_update_schema.rs +++ b/typesense_codegen/src/models/conversation_model_update_schema.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/create_analytics_rule_200_response.rs b/typesense_codegen/src/models/create_analytics_rule_200_response.rs index b1fb869..80053ca 100644 --- a/typesense_codegen/src/models/create_analytics_rule_200_response.rs +++ b/typesense_codegen/src/models/create_analytics_rule_200_response.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs index 86ba06a..bb9f001 100644 --- a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs +++ b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs index c10566b..08500ef 100644 --- a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs +++ b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/create_analytics_rule_request.rs b/typesense_codegen/src/models/create_analytics_rule_request.rs index b01b6b0..262570e 100644 --- a/typesense_codegen/src/models/create_analytics_rule_request.rs +++ b/typesense_codegen/src/models/create_analytics_rule_request.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/debug_200_response.rs b/typesense_codegen/src/models/debug_200_response.rs index f166294..946d84e 100644 --- a/typesense_codegen/src/models/debug_200_response.rs +++ b/typesense_codegen/src/models/debug_200_response.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/delete_documents_200_response.rs b/typesense_codegen/src/models/delete_documents_200_response.rs index 670c8dd..169020c 100644 --- a/typesense_codegen/src/models/delete_documents_200_response.rs +++ b/typesense_codegen/src/models/delete_documents_200_response.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/delete_documents_parameters.rs b/typesense_codegen/src/models/delete_documents_parameters.rs index d8ed65f..55e8241 100644 --- a/typesense_codegen/src/models/delete_documents_parameters.rs +++ b/typesense_codegen/src/models/delete_documents_parameters.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/delete_stopwords_set_200_response.rs b/typesense_codegen/src/models/delete_stopwords_set_200_response.rs index dea1137..03b93ef 100644 --- a/typesense_codegen/src/models/delete_stopwords_set_200_response.rs +++ b/typesense_codegen/src/models/delete_stopwords_set_200_response.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/dirty_values.rs b/typesense_codegen/src/models/dirty_values.rs index a9aab89..8caeab9 100644 --- a/typesense_codegen/src/models/dirty_values.rs +++ b/typesense_codegen/src/models/dirty_values.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/drop_tokens_mode.rs b/typesense_codegen/src/models/drop_tokens_mode.rs index 01eced2..5b8ba01 100644 --- a/typesense_codegen/src/models/drop_tokens_mode.rs +++ b/typesense_codegen/src/models/drop_tokens_mode.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/export_documents_parameters.rs b/typesense_codegen/src/models/export_documents_parameters.rs index 22fdd2c..36984f8 100644 --- a/typesense_codegen/src/models/export_documents_parameters.rs +++ b/typesense_codegen/src/models/export_documents_parameters.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/facet_counts.rs b/typesense_codegen/src/models/facet_counts.rs index 14437c8..d9cbdf3 100644 --- a/typesense_codegen/src/models/facet_counts.rs +++ b/typesense_codegen/src/models/facet_counts.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/facet_counts_counts_inner.rs b/typesense_codegen/src/models/facet_counts_counts_inner.rs index 2f2405b..bc6ede2 100644 --- a/typesense_codegen/src/models/facet_counts_counts_inner.rs +++ b/typesense_codegen/src/models/facet_counts_counts_inner.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/facet_counts_stats.rs b/typesense_codegen/src/models/facet_counts_stats.rs index 45e8a91..7f0d9dd 100644 --- a/typesense_codegen/src/models/facet_counts_stats.rs +++ b/typesense_codegen/src/models/facet_counts_stats.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/field.rs b/typesense_codegen/src/models/field.rs index 548e721..39bacbb 100644 --- a/typesense_codegen/src/models/field.rs +++ b/typesense_codegen/src/models/field.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/field_embed.rs b/typesense_codegen/src/models/field_embed.rs index 274e47c..0e84fd9 100644 --- a/typesense_codegen/src/models/field_embed.rs +++ b/typesense_codegen/src/models/field_embed.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/field_embed_model_config.rs b/typesense_codegen/src/models/field_embed_model_config.rs index 6aca8a1..ee40bea 100644 --- a/typesense_codegen/src/models/field_embed_model_config.rs +++ b/typesense_codegen/src/models/field_embed_model_config.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/get_collections_parameters.rs b/typesense_codegen/src/models/get_collections_parameters.rs index 8ecdcbe..02497f6 100644 --- a/typesense_codegen/src/models/get_collections_parameters.rs +++ b/typesense_codegen/src/models/get_collections_parameters.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/health_status.rs b/typesense_codegen/src/models/health_status.rs index 7a7489c..66cdf6b 100644 --- a/typesense_codegen/src/models/health_status.rs +++ b/typesense_codegen/src/models/health_status.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/import_documents_parameters.rs b/typesense_codegen/src/models/import_documents_parameters.rs index b5fbc23..e17494a 100644 --- a/typesense_codegen/src/models/import_documents_parameters.rs +++ b/typesense_codegen/src/models/import_documents_parameters.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/index_action.rs b/typesense_codegen/src/models/index_action.rs index 207dfe3..eb52174 100644 --- a/typesense_codegen/src/models/index_action.rs +++ b/typesense_codegen/src/models/index_action.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs b/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs index f4c66ee..9985e0d 100644 --- a/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs +++ b/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/multi_search_collection_parameters.rs b/typesense_codegen/src/models/multi_search_collection_parameters.rs index ff03484..76f99e0 100644 --- a/typesense_codegen/src/models/multi_search_collection_parameters.rs +++ b/typesense_codegen/src/models/multi_search_collection_parameters.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/multi_search_parameters.rs b/typesense_codegen/src/models/multi_search_parameters.rs index 8d4cbda..21b2db0 100644 --- a/typesense_codegen/src/models/multi_search_parameters.rs +++ b/typesense_codegen/src/models/multi_search_parameters.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/multi_search_result.rs b/typesense_codegen/src/models/multi_search_result.rs index 30e4d0c..bef6780 100644 --- a/typesense_codegen/src/models/multi_search_result.rs +++ b/typesense_codegen/src/models/multi_search_result.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/multi_search_result_item.rs b/typesense_codegen/src/models/multi_search_result_item.rs index 7cc6252..64794c8 100644 --- a/typesense_codegen/src/models/multi_search_result_item.rs +++ b/typesense_codegen/src/models/multi_search_result_item.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/multi_search_searches_parameter.rs b/typesense_codegen/src/models/multi_search_searches_parameter.rs index faded5b..36cd062 100644 --- a/typesense_codegen/src/models/multi_search_searches_parameter.rs +++ b/typesense_codegen/src/models/multi_search_searches_parameter.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/nl_search_model_base.rs b/typesense_codegen/src/models/nl_search_model_base.rs index d5c8523..5bb066f 100644 --- a/typesense_codegen/src/models/nl_search_model_base.rs +++ b/typesense_codegen/src/models/nl_search_model_base.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/nl_search_model_create_schema.rs b/typesense_codegen/src/models/nl_search_model_create_schema.rs index 86b3173..34cb2d4 100644 --- a/typesense_codegen/src/models/nl_search_model_create_schema.rs +++ b/typesense_codegen/src/models/nl_search_model_create_schema.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/nl_search_model_delete_schema.rs b/typesense_codegen/src/models/nl_search_model_delete_schema.rs index 670ba3e..f31df7d 100644 --- a/typesense_codegen/src/models/nl_search_model_delete_schema.rs +++ b/typesense_codegen/src/models/nl_search_model_delete_schema.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/nl_search_model_schema.rs b/typesense_codegen/src/models/nl_search_model_schema.rs index 809b9ca..b2066e0 100644 --- a/typesense_codegen/src/models/nl_search_model_schema.rs +++ b/typesense_codegen/src/models/nl_search_model_schema.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/preset_delete_schema.rs b/typesense_codegen/src/models/preset_delete_schema.rs index 325f9b2..5203796 100644 --- a/typesense_codegen/src/models/preset_delete_schema.rs +++ b/typesense_codegen/src/models/preset_delete_schema.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/preset_schema.rs b/typesense_codegen/src/models/preset_schema.rs index 959f873..c12caca 100644 --- a/typesense_codegen/src/models/preset_schema.rs +++ b/typesense_codegen/src/models/preset_schema.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/preset_upsert_schema.rs b/typesense_codegen/src/models/preset_upsert_schema.rs index 298465d..92eff0d 100644 --- a/typesense_codegen/src/models/preset_upsert_schema.rs +++ b/typesense_codegen/src/models/preset_upsert_schema.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/preset_upsert_schema_value.rs b/typesense_codegen/src/models/preset_upsert_schema_value.rs index 3dae812..43335aa 100644 --- a/typesense_codegen/src/models/preset_upsert_schema_value.rs +++ b/typesense_codegen/src/models/preset_upsert_schema_value.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/presets_retrieve_schema.rs b/typesense_codegen/src/models/presets_retrieve_schema.rs index f80b028..e64ecf1 100644 --- a/typesense_codegen/src/models/presets_retrieve_schema.rs +++ b/typesense_codegen/src/models/presets_retrieve_schema.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/schema_change_status.rs b/typesense_codegen/src/models/schema_change_status.rs index f1d32b0..22bb410 100644 --- a/typesense_codegen/src/models/schema_change_status.rs +++ b/typesense_codegen/src/models/schema_change_status.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/search_grouped_hit.rs b/typesense_codegen/src/models/search_grouped_hit.rs index f8af648..434b8fc 100644 --- a/typesense_codegen/src/models/search_grouped_hit.rs +++ b/typesense_codegen/src/models/search_grouped_hit.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/search_highlight.rs b/typesense_codegen/src/models/search_highlight.rs index 248c63c..c45afcc 100644 --- a/typesense_codegen/src/models/search_highlight.rs +++ b/typesense_codegen/src/models/search_highlight.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/search_override.rs b/typesense_codegen/src/models/search_override.rs index 981e36e..b1f8353 100644 --- a/typesense_codegen/src/models/search_override.rs +++ b/typesense_codegen/src/models/search_override.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/search_override_delete_response.rs b/typesense_codegen/src/models/search_override_delete_response.rs index d49997c..3949320 100644 --- a/typesense_codegen/src/models/search_override_delete_response.rs +++ b/typesense_codegen/src/models/search_override_delete_response.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/search_override_exclude.rs b/typesense_codegen/src/models/search_override_exclude.rs index b79ad04..58b01b9 100644 --- a/typesense_codegen/src/models/search_override_exclude.rs +++ b/typesense_codegen/src/models/search_override_exclude.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/search_override_include.rs b/typesense_codegen/src/models/search_override_include.rs index f932f3b..7756358 100644 --- a/typesense_codegen/src/models/search_override_include.rs +++ b/typesense_codegen/src/models/search_override_include.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/search_override_rule.rs b/typesense_codegen/src/models/search_override_rule.rs index ffd8516..de9ebf5 100644 --- a/typesense_codegen/src/models/search_override_rule.rs +++ b/typesense_codegen/src/models/search_override_rule.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/search_override_schema.rs b/typesense_codegen/src/models/search_override_schema.rs index f4ebed0..1b0eede 100644 --- a/typesense_codegen/src/models/search_override_schema.rs +++ b/typesense_codegen/src/models/search_override_schema.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/search_overrides_response.rs b/typesense_codegen/src/models/search_overrides_response.rs index c778bab..fd8aba3 100644 --- a/typesense_codegen/src/models/search_overrides_response.rs +++ b/typesense_codegen/src/models/search_overrides_response.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/search_parameters.rs b/typesense_codegen/src/models/search_parameters.rs index 9fe147c..860beff 100644 --- a/typesense_codegen/src/models/search_parameters.rs +++ b/typesense_codegen/src/models/search_parameters.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/search_request_params.rs b/typesense_codegen/src/models/search_request_params.rs index 43cb36d..7e67048 100644 --- a/typesense_codegen/src/models/search_request_params.rs +++ b/typesense_codegen/src/models/search_request_params.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/search_request_params_voice_query.rs b/typesense_codegen/src/models/search_request_params_voice_query.rs index 5a91f01..97e78ef 100644 --- a/typesense_codegen/src/models/search_request_params_voice_query.rs +++ b/typesense_codegen/src/models/search_request_params_voice_query.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/search_result.rs b/typesense_codegen/src/models/search_result.rs index 2bd87b9..f5ea5b5 100644 --- a/typesense_codegen/src/models/search_result.rs +++ b/typesense_codegen/src/models/search_result.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/search_result_conversation.rs b/typesense_codegen/src/models/search_result_conversation.rs index 880066e..380be44 100644 --- a/typesense_codegen/src/models/search_result_conversation.rs +++ b/typesense_codegen/src/models/search_result_conversation.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/search_result_hit.rs b/typesense_codegen/src/models/search_result_hit.rs index 0ab30a1..abe92e4 100644 --- a/typesense_codegen/src/models/search_result_hit.rs +++ b/typesense_codegen/src/models/search_result_hit.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs b/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs index 19b072a..ed0bea0 100644 --- a/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs +++ b/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/search_result_hit_text_match_info.rs b/typesense_codegen/src/models/search_result_hit_text_match_info.rs index 69b3500..e77c40f 100644 --- a/typesense_codegen/src/models/search_result_hit_text_match_info.rs +++ b/typesense_codegen/src/models/search_result_hit_text_match_info.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/search_synonym.rs b/typesense_codegen/src/models/search_synonym.rs index 3e2b22a..3d81eb7 100644 --- a/typesense_codegen/src/models/search_synonym.rs +++ b/typesense_codegen/src/models/search_synonym.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/search_synonym_delete_response.rs b/typesense_codegen/src/models/search_synonym_delete_response.rs index 8da893a..c69e47b 100644 --- a/typesense_codegen/src/models/search_synonym_delete_response.rs +++ b/typesense_codegen/src/models/search_synonym_delete_response.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/search_synonym_schema.rs b/typesense_codegen/src/models/search_synonym_schema.rs index 49aa1a5..192829f 100644 --- a/typesense_codegen/src/models/search_synonym_schema.rs +++ b/typesense_codegen/src/models/search_synonym_schema.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/search_synonyms_response.rs b/typesense_codegen/src/models/search_synonyms_response.rs index 17866d6..40434ca 100644 --- a/typesense_codegen/src/models/search_synonyms_response.rs +++ b/typesense_codegen/src/models/search_synonyms_response.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/stemming_dictionary.rs b/typesense_codegen/src/models/stemming_dictionary.rs index c2b31ee..e90942c 100644 --- a/typesense_codegen/src/models/stemming_dictionary.rs +++ b/typesense_codegen/src/models/stemming_dictionary.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/stemming_dictionary_words_inner.rs b/typesense_codegen/src/models/stemming_dictionary_words_inner.rs index a9ffaf0..30cbd40 100644 --- a/typesense_codegen/src/models/stemming_dictionary_words_inner.rs +++ b/typesense_codegen/src/models/stemming_dictionary_words_inner.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs b/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs index 43348b3..b1b6913 100644 --- a/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs +++ b/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/stopwords_set_schema.rs b/typesense_codegen/src/models/stopwords_set_schema.rs index f31e4cb..8f13dee 100644 --- a/typesense_codegen/src/models/stopwords_set_schema.rs +++ b/typesense_codegen/src/models/stopwords_set_schema.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/stopwords_set_upsert_schema.rs b/typesense_codegen/src/models/stopwords_set_upsert_schema.rs index 5145f5e..1facab5 100644 --- a/typesense_codegen/src/models/stopwords_set_upsert_schema.rs +++ b/typesense_codegen/src/models/stopwords_set_upsert_schema.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs b/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs index a0838e4..84703ac 100644 --- a/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs +++ b/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/success_status.rs b/typesense_codegen/src/models/success_status.rs index 3056e25..c88ecb9 100644 --- a/typesense_codegen/src/models/success_status.rs +++ b/typesense_codegen/src/models/success_status.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/synonym_item_schema.rs b/typesense_codegen/src/models/synonym_item_schema.rs index ab068c8..bb03da3 100644 --- a/typesense_codegen/src/models/synonym_item_schema.rs +++ b/typesense_codegen/src/models/synonym_item_schema.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/synonym_set_create_schema.rs b/typesense_codegen/src/models/synonym_set_create_schema.rs index 3ec60f2..818ae98 100644 --- a/typesense_codegen/src/models/synonym_set_create_schema.rs +++ b/typesense_codegen/src/models/synonym_set_create_schema.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/synonym_set_delete_schema.rs b/typesense_codegen/src/models/synonym_set_delete_schema.rs index 18f5746..e127040 100644 --- a/typesense_codegen/src/models/synonym_set_delete_schema.rs +++ b/typesense_codegen/src/models/synonym_set_delete_schema.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/synonym_set_schema.rs b/typesense_codegen/src/models/synonym_set_schema.rs index dbdd6e6..f9e171c 100644 --- a/typesense_codegen/src/models/synonym_set_schema.rs +++ b/typesense_codegen/src/models/synonym_set_schema.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs b/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs index ca1262b..612c1a5 100644 --- a/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs +++ b/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/toggle_slow_request_log_request.rs b/typesense_codegen/src/models/toggle_slow_request_log_request.rs index 8ed0754..2957298 100644 --- a/typesense_codegen/src/models/toggle_slow_request_log_request.rs +++ b/typesense_codegen/src/models/toggle_slow_request_log_request.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/update_documents_200_response.rs b/typesense_codegen/src/models/update_documents_200_response.rs index 10bf4f9..88cc7b4 100644 --- a/typesense_codegen/src/models/update_documents_200_response.rs +++ b/typesense_codegen/src/models/update_documents_200_response.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/update_documents_parameters.rs b/typesense_codegen/src/models/update_documents_parameters.rs index d1dc93f..cf49cbb 100644 --- a/typesense_codegen/src/models/update_documents_parameters.rs +++ b/typesense_codegen/src/models/update_documents_parameters.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech diff --git a/typesense_codegen/src/models/voice_query_model_collection_config.rs b/typesense_codegen/src/models/voice_query_model_collection_config.rs index 9250347..38044c9 100644 --- a/typesense_codegen/src/models/voice_query_model_collection_config.rs +++ b/typesense_codegen/src/models/voice_query_model_collection_config.rs @@ -2,6 +2,7 @@ * Typesense API * * An open source search engine for building delightful search experiences. + * * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech From 439f80516937175d1fc6c4c1d655b0509ae0cdfe Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Fri, 12 Sep 2025 23:36:29 +0700 Subject: [PATCH 29/41] README: add instructions to use the xtask --- README.md | 32 +++++++++++++++++++------------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 192c714..0bc0914 100644 --- a/README.md +++ b/README.md @@ -5,20 +5,26 @@ Rust client library for Typesense | Work In Progress & Help Wanted! -`preprocessed_openapi.yml` is generated by `xtask`. +### Development -OpenAPI codegen folder can be regenerated with: +When updating or adding new parameters and endpoints, make changes directly in the [Typesense API spec repository](https://github.com/typesense/typesense-api-spec). +Once your changes are merged, you can update this project as follows: + +```bash +cargo xtask fetch code-gen ``` -docker run --rm \ - -v $PWD:/local openapitools/openapi-generator-cli generate \ - -i /local/preprocessed_openapi.yml \ - -g rust \ - -o /local/typesense_codegen \ - -t /local/openapi-generator-template \ - --additional-properties library=reqwest \ - --additional-properties supportMiddleware=true \ - --additional-properties useSingleRequestParameter=true -``` -If you'd like to contribute, please join our [Slack Community](https://join.slack.com/t/typesense-community/shared_invite/zt-mx4nbsbn-AuOL89O7iBtvkz136egSJg) and say hello! +This will: + +- Download the latest API spec. +- Write it to our local [`openapi.yml`](./openapi.yml). +- Preprocess it into [`preprocessed_openapi.yml`](./preprocessed_openapi.yml). +- Regenerate the `/typesense_codegen` crate. + +The preprocessing step does two things: + +- Unwrap/flatten the URL params defined as objects into individual URL parameters (in [`preprocess_openapi.rs`](xtask/src/preprocess_openapi.rs)) +- Inject OpenAPI vendor attributes (e.g., generic parameters, schema builders) into the spec before code generation (in [`add_vendor_attributes.rs`](./xtask/src/add_vendor_attributes.rs)) + +If you'd like to contribute, please join our [Slack Community](https://join.slack.com/t/typesense-community/shared_invite/zt-mx4nbsbn-AuOL89O7iBtvkz136egSJg) and say hello! From 49af86378530be59f30e308b049fd226fca320a3 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Fri, 12 Sep 2025 23:39:04 +0700 Subject: [PATCH 30/41] Readme tweak --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0bc0914..e42df01 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ Rust client library for Typesense | Work In Progress & Help Wanted! When updating or adding new parameters and endpoints, make changes directly in the [Typesense API spec repository](https://github.com/typesense/typesense-api-spec). -Once your changes are merged, you can update this project as follows: +Once your changes are merged, you can update this project as follows (you can also run tasks individually): ```bash cargo xtask fetch code-gen @@ -24,7 +24,7 @@ This will: The preprocessing step does two things: -- Unwrap/flatten the URL params defined as objects into individual URL parameters (in [`preprocess_openapi.rs`](xtask/src/preprocess_openapi.rs)) +- Flatten the URL params defined as objects into individual URL parameters (in [`preprocess_openapi.rs`](xtask/src/preprocess_openapi.rs)) - Inject OpenAPI vendor attributes (e.g., generic parameters, schema builders) into the spec before code generation (in [`add_vendor_attributes.rs`](./xtask/src/add_vendor_attributes.rs)) If you'd like to contribute, please join our [Slack Community](https://join.slack.com/t/typesense-community/shared_invite/zt-mx4nbsbn-AuOL89O7iBtvkz136egSJg) and say hello! From 7f7794f2775a587e6568d7077488aed9a5a98fcf Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Sat, 13 Sep 2025 13:52:19 +0700 Subject: [PATCH 31/41] README: code gen docker command --- README.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/README.md b/README.md index e42df01..625f55c 100644 --- a/README.md +++ b/README.md @@ -27,4 +27,18 @@ The preprocessing step does two things: - Flatten the URL params defined as objects into individual URL parameters (in [`preprocess_openapi.rs`](xtask/src/preprocess_openapi.rs)) - Inject OpenAPI vendor attributes (e.g., generic parameters, schema builders) into the spec before code generation (in [`add_vendor_attributes.rs`](./xtask/src/add_vendor_attributes.rs)) +You can also run `code-gen` directly through Docker: + +``` +docker run --rm \ + -v $PWD:/local openapitools/openapi-generator-cli generate \ + -i /local/preprocessed_openapi.yml \ + -g rust \ + -o /local/typesense_codegen \ + -t /local/openapi-generator-template \ + --additional-properties library=reqwest \ + --additional-properties supportMiddleware=true \ + --additional-properties useSingleRequestParameter=true +``` + If you'd like to contribute, please join our [Slack Community](https://join.slack.com/t/typesense-community/shared_invite/zt-mx4nbsbn-AuOL89O7iBtvkz136egSJg) and say hello! From 1c9d56fb36a4e334a1246b64a84fc89d14786808 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Sat, 13 Sep 2025 23:12:51 +0700 Subject: [PATCH 32/41] remove unused openapi template files --- openapi-generator-template/.travis.yml | 1 - openapi-generator-template/Cargo.mustache | 109 ------------------ .../git_push.sh.mustache | 57 --------- openapi-generator-template/gitignore.mustache | 3 - typesense_codegen/.openapi-generator-ignore | 5 +- typesense_codegen/.openapi-generator/FILES | 3 - typesense_codegen/.openapi-generator/VERSION | 2 +- typesense_codegen/.travis.yml | 1 - typesense_codegen/README.md | 2 +- typesense_codegen/git_push.sh | 57 --------- 10 files changed, 6 insertions(+), 234 deletions(-) delete mode 100644 openapi-generator-template/.travis.yml delete mode 100644 openapi-generator-template/Cargo.mustache delete mode 100644 openapi-generator-template/git_push.sh.mustache delete mode 100644 openapi-generator-template/gitignore.mustache delete mode 100644 typesense_codegen/.travis.yml delete mode 100644 typesense_codegen/git_push.sh diff --git a/openapi-generator-template/.travis.yml b/openapi-generator-template/.travis.yml deleted file mode 100644 index 22761ba..0000000 --- a/openapi-generator-template/.travis.yml +++ /dev/null @@ -1 +0,0 @@ -language: rust diff --git a/openapi-generator-template/Cargo.mustache b/openapi-generator-template/Cargo.mustache deleted file mode 100644 index 30f73e8..0000000 --- a/openapi-generator-template/Cargo.mustache +++ /dev/null @@ -1,109 +0,0 @@ -[package] -name = "{{{packageName}}}" -version = "{{#lambdaVersion}}{{{packageVersion}}}{{/lambdaVersion}}" -{{#infoEmail}} -authors = ["{{{.}}}"] -{{/infoEmail}} -{{^infoEmail}} -authors = ["OpenAPI Generator team and contributors"] -{{/infoEmail}} -{{#appDescription}} -description = "{{{.}}}" -{{/appDescription}} -{{#licenseInfo}} -license = "{{.}}" -{{/licenseInfo}} -{{^licenseInfo}} -# Override this license by providing a License Object in the OpenAPI. -license = "Unlicense" -{{/licenseInfo}} -edition = "2021" -{{#publishRustRegistry}} -publish = ["{{.}}"] -{{/publishRustRegistry}} -{{#repositoryUrl}} -repository = "{{.}}" -{{/repositoryUrl}} -{{#documentationUrl}} -documentation = "{{.}}" -{{/documentationUrl}} -{{#homePageUrl}} -homepage = "{{.}}" -{{/homePageUrl}} - -[dependencies] -serde = { version = "^1.0", features = ["derive"] } -{{#serdeWith}} -serde_with = { version = "^3.8", default-features = false, features = ["base64", "std", "macros"] } -{{/serdeWith}} -serde_json = "^1.0" -serde_repr = "^0.1" -url = "^2.5" -{{#hasUUIDs}} -uuid = { version = "^1.8", features = ["serde", "v4"] } -{{/hasUUIDs}} -{{#hyper}} -{{#hyper0x}} -hyper = { version = "~0.14", features = ["full"] } -hyper-tls = "~0.5" -{{/hyper0x}} -{{^hyper0x}} -hyper = { version = "^1.3.1", features = ["full"] } -hyper-util = { version = "0.1.5", features = ["client", "client-legacy", "http1", "http2"] } -http-body-util = { version = "0.1.2" } -{{/hyper0x}} -http = "~0.2" -base64 = "~0.7.0" -futures = "^0.3" -{{/hyper}} -{{#withAWSV4Signature}} -aws-sigv4 = "0.3.0" -http = "0.2.5" -secrecy = "0.8.0" -{{/withAWSV4Signature}} -{{#reqwest}} -{{^supportAsync}} -reqwest = { version = "^0.12", default-features = false, features = ["json", "blocking", "multipart"] } -{{#supportMiddleware}} -reqwest-middleware = { version = "^0.4", features = ["json", "blocking", "multipart"] } -{{/supportMiddleware}} -{{/supportAsync}} -{{#supportAsync}} -reqwest = { version = "^0.12", default-features = false, features = ["json", "multipart"] } -{{#supportMiddleware}} -reqwest-middleware = { version = "^0.4", features = ["json", "multipart"] } -{{/supportMiddleware}} -{{#supportTokenSource}} -async-trait = "^0.1" -# TODO: propose to Yoshidan to externalize this as non google related crate, so that it can easily be extended for other cloud providers. -google-cloud-token = "^0.1" -{{/supportTokenSource}} -{{/supportAsync}} -{{/reqwest}} -{{#reqwestTrait}} -async-trait = "^0.1" -reqwest = { version = "^0.12", default-features = false, features = ["json", "multipart"] } -{{#supportMiddleware}} -reqwest-middleware = { version = "^0.4", features = ["json", "multipart"] } -{{/supportMiddleware}} -{{#supportTokenSource}} -# TODO: propose to Yoshidan to externalize this as non google related crate, so that it can easily be extended for other cloud providers. -google-cloud-token = "^0.1" -{{/supportTokenSource}} -{{#mockall}} -mockall = { version = "^0.13", optional = true} -{{/mockall}} -{{#useBonBuilder}} -bon = { version = "2.3", optional = true } -{{/useBonBuilder}} -[features] -default = ["native-tls"] -native-tls = ["reqwest/native-tls"] -rustls = ["reqwest/rustls-tls"] -{{#mockall}} -mockall = ["dep:mockall"] -{{/mockall}} -{{#useBonBuilder}} -bon = ["dep:bon"] -{{/useBonBuilder}} -{{/reqwestTrait}} diff --git a/openapi-generator-template/git_push.sh.mustache b/openapi-generator-template/git_push.sh.mustache deleted file mode 100644 index 0e3776a..0000000 --- a/openapi-generator-template/git_push.sh.mustache +++ /dev/null @@ -1,57 +0,0 @@ -#!/bin/sh -# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ -# -# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" - -git_user_id=$1 -git_repo_id=$2 -release_note=$3 -git_host=$4 - -if [ "$git_host" = "" ]; then - git_host="{{{gitHost}}}" - echo "[INFO] No command line input provided. Set \$git_host to $git_host" -fi - -if [ "$git_user_id" = "" ]; then - git_user_id="{{{gitUserId}}}" - echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" -fi - -if [ "$git_repo_id" = "" ]; then - git_repo_id="{{{gitRepoId}}}" - echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" -fi - -if [ "$release_note" = "" ]; then - release_note="{{{releaseNote}}}" - echo "[INFO] No command line input provided. Set \$release_note to $release_note" -fi - -# Initialize the local directory as a Git repository -git init - -# Adds the files in the local repository and stages them for commit. -git add . - -# Commits the tracked changes and prepares them to be pushed to a remote repository. -git commit -m "$release_note" - -# Sets the new remote -git_remote=$(git remote) -if [ "$git_remote" = "" ]; then # git remote not defined - - if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." - git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git - else - git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git - fi - -fi - -git pull origin master - -# Pushes (Forces) the changes in the local repository up to the remote repository -echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" -git push origin master 2>&1 | grep -v 'To https' diff --git a/openapi-generator-template/gitignore.mustache b/openapi-generator-template/gitignore.mustache deleted file mode 100644 index 6aa1064..0000000 --- a/openapi-generator-template/gitignore.mustache +++ /dev/null @@ -1,3 +0,0 @@ -/target/ -**/*.rs.bk -Cargo.lock diff --git a/typesense_codegen/.openapi-generator-ignore b/typesense_codegen/.openapi-generator-ignore index b2708db..d37a8f8 100644 --- a/typesense_codegen/.openapi-generator-ignore +++ b/typesense_codegen/.openapi-generator-ignore @@ -25,4 +25,7 @@ Cargo.toml src/apis/configuration.rs src/apis/mod.rs -src/lib.rs \ No newline at end of file +src/lib.rs +.gitignore +.travis.yml +git_push.sh \ No newline at end of file diff --git a/typesense_codegen/.openapi-generator/FILES b/typesense_codegen/.openapi-generator/FILES index 79da908..7675467 100644 --- a/typesense_codegen/.openapi-generator/FILES +++ b/typesense_codegen/.openapi-generator/FILES @@ -1,5 +1,3 @@ -.gitignore -.travis.yml README.md docs/AnalyticsApi.md docs/AnalyticsEvent.md @@ -115,7 +113,6 @@ docs/ToggleSlowRequestLogRequest.md docs/UpdateDocuments200Response.md docs/UpdateDocumentsParameters.md docs/VoiceQueryModelCollectionConfig.md -git_push.sh src/apis/analytics_api.rs src/apis/collections_api.rs src/apis/conversations_api.rs diff --git a/typesense_codegen/.openapi-generator/VERSION b/typesense_codegen/.openapi-generator/VERSION index 5e52829..e465da4 100644 --- a/typesense_codegen/.openapi-generator/VERSION +++ b/typesense_codegen/.openapi-generator/VERSION @@ -1 +1 @@ -7.16.0-SNAPSHOT +7.14.0 diff --git a/typesense_codegen/.travis.yml b/typesense_codegen/.travis.yml deleted file mode 100644 index 22761ba..0000000 --- a/typesense_codegen/.travis.yml +++ /dev/null @@ -1 +0,0 @@ -language: rust diff --git a/typesense_codegen/README.md b/typesense_codegen/README.md index 768dcfa..f16906b 100644 --- a/typesense_codegen/README.md +++ b/typesense_codegen/README.md @@ -9,7 +9,7 @@ This API client was generated by the [OpenAPI Generator](https://openapi-generat - API version: 30.0 - Package version: 30.0 -- Generator version: 7.16.0-SNAPSHOT +- Generator version: 7.14.0 - Build package: `org.openapitools.codegen.languages.RustClientCodegen` ## Installation diff --git a/typesense_codegen/git_push.sh b/typesense_codegen/git_push.sh deleted file mode 100644 index f53a75d..0000000 --- a/typesense_codegen/git_push.sh +++ /dev/null @@ -1,57 +0,0 @@ -#!/bin/sh -# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ -# -# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" - -git_user_id=$1 -git_repo_id=$2 -release_note=$3 -git_host=$4 - -if [ "$git_host" = "" ]; then - git_host="github.com" - echo "[INFO] No command line input provided. Set \$git_host to $git_host" -fi - -if [ "$git_user_id" = "" ]; then - git_user_id="GIT_USER_ID" - echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" -fi - -if [ "$git_repo_id" = "" ]; then - git_repo_id="GIT_REPO_ID" - echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" -fi - -if [ "$release_note" = "" ]; then - release_note="Minor update" - echo "[INFO] No command line input provided. Set \$release_note to $release_note" -fi - -# Initialize the local directory as a Git repository -git init - -# Adds the files in the local repository and stages them for commit. -git add . - -# Commits the tracked changes and prepares them to be pushed to a remote repository. -git commit -m "$release_note" - -# Sets the new remote -git_remote=$(git remote) -if [ "$git_remote" = "" ]; then # git remote not defined - - if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." - git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git - else - git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git - fi - -fi - -git pull origin master - -# Pushes (Forces) the changes in the local repository up to the remote repository -echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" -git push origin master 2>&1 | grep -v 'To https' From ea3a1265d8de224b554e2805e985a7a0866cc528 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Sat, 13 Sep 2025 23:21:44 +0700 Subject: [PATCH 33/41] modify the open api template instead of ignoring`apis/mod.rs` and `lib.rs` --- openapi-generator-template/lib.mustache | 15 ++--------- .../reqwest/api_mod.mustache | 27 +++++++++++-------- typesense_codegen/.openapi-generator-ignore | 3 +-- typesense_codegen/.openapi-generator/FILES | 2 ++ typesense_codegen/src/apis/mod.rs | 8 +++--- 5 files changed, 25 insertions(+), 30 deletions(-) diff --git a/openapi-generator-template/lib.mustache b/openapi-generator-template/lib.mustache index b51df2b..f9a96b5 100644 --- a/openapi-generator-template/lib.mustache +++ b/openapi-generator-template/lib.mustache @@ -1,17 +1,6 @@ #![allow(unused_imports)] -#![allow(clippy::too_many_arguments)] - -extern crate serde_repr; -extern crate serde; -extern crate serde_json; -extern crate url; -{{#hyper}} -extern crate hyper; -extern crate futures; -{{/hyper}} -{{#reqwest}} -extern crate reqwest; -{{/reqwest}} +#![allow(clippy::all)] +#![allow(elided_lifetimes_in_paths)] pub mod apis; pub mod models; diff --git a/openapi-generator-template/reqwest/api_mod.mustache b/openapi-generator-template/reqwest/api_mod.mustache index 4d5df28..6a78390 100644 --- a/openapi-generator-template/reqwest/api_mod.mustache +++ b/openapi-generator-template/reqwest/api_mod.mustache @@ -1,5 +1,5 @@ -use std::error; -use std::fmt; +use std::{error, fmt}; + {{#withAWSV4Signature}} use aws_sigv4; {{/withAWSV4Signature}} @@ -15,6 +15,7 @@ pub struct ResponseContent { pub enum Error { Reqwest(reqwest::Error), {{#supportMiddleware}} + #[cfg(not(target_family = "wasm"))] ReqwestMiddleware(reqwest_middleware::Error), {{/supportMiddleware}} Serde(serde_json::Error), @@ -35,6 +36,7 @@ impl fmt::Display for Error { let (module, e) = match self { Error::Reqwest(e) => ("reqwest", e.to_string()), {{#supportMiddleware}} + #[cfg(not(target_family = "wasm"))] Error::ReqwestMiddleware(e) => ("reqwest-middleware", e.to_string()), {{/supportMiddleware}} Error::Serde(e) => ("serde", e.to_string()), @@ -49,7 +51,7 @@ impl fmt::Display for Error { {{/supportTokenSource}} {{/supportAsync}} }; - write!(f, "error in {}: {}", module, e) + write!(f, "error in {module}: {e}") } } @@ -58,6 +60,7 @@ impl error::Error for Error { Some(match self { Error::Reqwest(e) => e, {{#supportMiddleware}} + #[cfg(not(target_family = "wasm"))] Error::ReqwestMiddleware(e) => e, {{/supportMiddleware}} Error::Serde(e) => e, @@ -82,6 +85,7 @@ impl From for Error { } {{#supportMiddleware}} +#[cfg(not(target_family = "wasm"))] impl From for Error { fn from(e: reqwest_middleware::Error) -> Self { Error::ReqwestMiddleware(e) @@ -111,20 +115,21 @@ pub fn parse_deep_object(prefix: &str, value: &serde_json::Value) -> Vec<(String for (key, value) in object { match value { - serde_json::Value::Object(_) => params.append(&mut parse_deep_object( - &format!("{}[{}]", prefix, key), - value, - )), + serde_json::Value::Object(_) => { + params.append(&mut parse_deep_object(&format!("{prefix}[{key}]"), value)) + } serde_json::Value::Array(array) => { for (i, value) in array.iter().enumerate() { params.append(&mut parse_deep_object( - &format!("{}[{}][{}]", prefix, key, i), + &format!("{prefix}[{key}][{i}]"), value, )); } - }, - serde_json::Value::String(s) => params.push((format!("{}[{}]", prefix, key), s.clone())), - _ => params.push((format!("{}[{}]", prefix, key), value.to_string())), + } + serde_json::Value::String(s) => { + params.push((format!("{prefix}[{key}]"), s.clone())) + } + _ => params.push((format!("{prefix}[{key}]"), value.to_string())), } } diff --git a/typesense_codegen/.openapi-generator-ignore b/typesense_codegen/.openapi-generator-ignore index d37a8f8..3eed36b 100644 --- a/typesense_codegen/.openapi-generator-ignore +++ b/typesense_codegen/.openapi-generator-ignore @@ -24,8 +24,7 @@ Cargo.toml src/apis/configuration.rs -src/apis/mod.rs -src/lib.rs + .gitignore .travis.yml git_push.sh \ No newline at end of file diff --git a/typesense_codegen/.openapi-generator/FILES b/typesense_codegen/.openapi-generator/FILES index 7675467..2a46e2a 100644 --- a/typesense_codegen/.openapi-generator/FILES +++ b/typesense_codegen/.openapi-generator/FILES @@ -121,6 +121,7 @@ src/apis/debug_api.rs src/apis/documents_api.rs src/apis/health_api.rs src/apis/keys_api.rs +src/apis/mod.rs src/apis/nl_search_models_api.rs src/apis/operations_api.rs src/apis/override_api.rs @@ -128,6 +129,7 @@ src/apis/presets_api.rs src/apis/stemming_api.rs src/apis/stopwords_api.rs src/apis/synonyms_api.rs +src/lib.rs src/models/analytics_event.rs src/models/analytics_event_create_response.rs src/models/analytics_event_data.rs diff --git a/typesense_codegen/src/apis/mod.rs b/typesense_codegen/src/apis/mod.rs index 9b18bf9..12bf0c1 100644 --- a/typesense_codegen/src/apis/mod.rs +++ b/typesense_codegen/src/apis/mod.rs @@ -10,7 +10,7 @@ pub struct ResponseContent { #[derive(Debug)] pub enum Error { Reqwest(reqwest::Error), - #[cfg(not(target_arch = "wasm32"))] + #[cfg(not(target_family = "wasm"))] ReqwestMiddleware(reqwest_middleware::Error), Serde(serde_json::Error), Io(std::io::Error), @@ -21,7 +21,7 @@ impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let (module, e) = match self { Error::Reqwest(e) => ("reqwest", e.to_string()), - #[cfg(not(target_arch = "wasm32"))] + #[cfg(not(target_family = "wasm"))] Error::ReqwestMiddleware(e) => ("reqwest-middleware", e.to_string()), Error::Serde(e) => ("serde", e.to_string()), Error::Io(e) => ("IO", e.to_string()), @@ -35,7 +35,7 @@ impl error::Error for Error { fn source(&self) -> Option<&(dyn error::Error + 'static)> { Some(match self { Error::Reqwest(e) => e, - #[cfg(not(target_arch = "wasm32"))] + #[cfg(not(target_family = "wasm"))] Error::ReqwestMiddleware(e) => e, Error::Serde(e) => e, Error::Io(e) => e, @@ -50,7 +50,7 @@ impl From for Error { } } -#[cfg(not(target_arch = "wasm32"))] +#[cfg(not(target_family = "wasm"))] impl From for Error { fn from(e: reqwest_middleware::Error) -> Self { Error::ReqwestMiddleware(e) From 8b7a0774d3ffb68ee8703afed73a1ff39c32d400 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Sun, 14 Sep 2025 10:15:23 +0700 Subject: [PATCH 34/41] remove `openapi-generator-template/request.rs` --- openapi-generator-template/request.rs | 247 -------------------------- 1 file changed, 247 deletions(-) delete mode 100644 openapi-generator-template/request.rs diff --git a/openapi-generator-template/request.rs b/openapi-generator-template/request.rs deleted file mode 100644 index a6f7b74..0000000 --- a/openapi-generator-template/request.rs +++ /dev/null @@ -1,247 +0,0 @@ -use std::collections::HashMap; -use std::pin::Pin; - -use futures; -use futures::Future; -use futures::future::*; -use http_body_util::BodyExt; -use hyper; -use hyper_util::client::legacy::connect::Connect; -use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, HeaderValue, USER_AGENT}; -use serde; -use serde_json; - -use super::{configuration, Error}; - -pub(crate) struct ApiKey { - pub in_header: bool, - pub in_query: bool, - pub param_name: String, -} - -impl ApiKey { - fn key(&self, prefix: &Option, key: &str) -> String { - match prefix { - None => key.to_owned(), - Some(ref prefix) => format!("{} {}", prefix, key), - } - } -} - -#[allow(dead_code)] -pub(crate) enum Auth { - None, - ApiKey(ApiKey), - Basic, - Oauth, -} - -/// If the authorization type is unspecified then it will be automatically detected based -/// on the configuration. This functionality is useful when the OpenAPI definition does not -/// include an authorization scheme. -pub(crate) struct Request { - auth: Option, - method: hyper::Method, - path: String, - query_params: HashMap, - no_return_type: bool, - path_params: HashMap, - form_params: HashMap, - header_params: HashMap, - // TODO: multiple body params are possible technically, but not supported here. - serialized_body: Option, -} - -#[allow(dead_code)] -impl Request { - pub fn new(method: hyper::Method, path: String) -> Self { - Request { - auth: None, - method, - path, - query_params: HashMap::new(), - path_params: HashMap::new(), - form_params: HashMap::new(), - header_params: HashMap::new(), - serialized_body: None, - no_return_type: false, - } - } - - pub fn with_body_param(mut self, param: T) -> Self { - self.serialized_body = Some(serde_json::to_string(¶m).unwrap()); - self - } - - pub fn with_header_param(mut self, basename: String, param: String) -> Self { - self.header_params.insert(basename, param); - self - } - - #[allow(unused)] - pub fn with_query_param(mut self, basename: String, param: String) -> Self { - self.query_params.insert(basename, param); - self - } - - #[allow(unused)] - pub fn with_path_param(mut self, basename: String, param: String) -> Self { - self.path_params.insert(basename, param); - self - } - - #[allow(unused)] - pub fn with_form_param(mut self, basename: String, param: String) -> Self { - self.form_params.insert(basename, param); - self - } - - pub fn returns_nothing(mut self) -> Self { - self.no_return_type = true; - self - } - - pub fn with_auth(mut self, auth: Auth) -> Self { - self.auth = Some(auth); - self - } - - pub fn execute<'a, C, U>( - self, - conf: &configuration::Configuration, - ) -> Pin> + 'a + Send>> - where - C: Connect + Clone + std::marker::Send + Sync, - U: Sized + std::marker::Send + 'a, - for<'de> U: serde::Deserialize<'de>, - { - let mut query_string = ::url::form_urlencoded::Serializer::new("".to_owned()); - - let mut path = self.path; - for (k, v) in self.path_params { - // replace {id} with the value of the id path param - path = path.replace(&format!("{{{}}}", k), &v); - } - - for (key, val) in self.query_params { - query_string.append_pair(&key, &val); - } - - let mut uri_str = format!("{}{}", conf.base_path, path); - - let query_string_str = query_string.finish(); - if !query_string_str.is_empty() { - uri_str += "?"; - uri_str += &query_string_str; - } - let uri: hyper::Uri = match uri_str.parse() { - Err(e) => return Box::pin(futures::future::err(Error::UriError(e))), - Ok(u) => u, - }; - - let mut req_builder = hyper::Request::builder() - .uri(uri) - .method(self.method); - - // Detect the authorization type if it hasn't been set. - let auth = self.auth.unwrap_or_else(|| - if conf.api_key.is_some() { - panic!("Cannot automatically set the API key from the configuration, it must be specified in the OpenAPI definition") - } else if conf.oauth_access_token.is_some() { - Auth::Oauth - } else if conf.basic_auth.is_some() { - Auth::Basic - } else { - Auth::None - } - ); - match auth { - Auth::ApiKey(apikey) => { - if let Some(ref key) = conf.api_key { - let val = apikey.key(&key.prefix, &key.key); - if apikey.in_query { - query_string.append_pair(&apikey.param_name, &val); - } - if apikey.in_header { - req_builder = req_builder.header(&apikey.param_name, val); - } - } - } - Auth::Basic => { - if let Some(ref auth_conf) = conf.basic_auth { - let mut text = auth_conf.0.clone(); - text.push(':'); - if let Some(ref pass) = auth_conf.1 { - text.push_str(&pass[..]); - } - let encoded = base64::encode(&text); - req_builder = req_builder.header(AUTHORIZATION, encoded); - } - } - Auth::Oauth => { - if let Some(ref token) = conf.oauth_access_token { - let text = "Bearer ".to_owned() + token; - req_builder = req_builder.header(AUTHORIZATION, text); - } - } - Auth::None => {} - } - - if let Some(ref user_agent) = conf.user_agent { - req_builder = req_builder.header(USER_AGENT, match HeaderValue::from_str(user_agent) { - Ok(header_value) => header_value, - Err(e) => return Box::pin(futures::future::err(super::Error::Header(e))) - }); - } - - for (k, v) in self.header_params { - req_builder = req_builder.header(&k, v); - } - - let req_headers = req_builder.headers_mut().unwrap(); - let request_result = if self.form_params.len() > 0 { - req_headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/x-www-form-urlencoded")); - let mut enc = ::url::form_urlencoded::Serializer::new("".to_owned()); - for (k, v) in self.form_params { - enc.append_pair(&k, &v); - } - req_builder.body(enc.finish()) - } else if let Some(body) = self.serialized_body { - req_headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); - req_headers.insert(CONTENT_LENGTH, body.len().into()); - req_builder.body(body) - } else { - req_builder.body(String::new()) - }; - let request = match request_result { - Ok(request) => request, - Err(e) => return Box::pin(futures::future::err(Error::from(e))) - }; - - let no_return_type = self.no_return_type; - Box::pin(conf.client - .request(request) - .map_err(|e| Error::from(e)) - .and_then(move |response| { - let status = response.status(); - if !status.is_success() { - futures::future::err::(Error::from((status, response.into_body()))).boxed() - } else if no_return_type { - // This is a hack; if there's no_ret_type, U is (), but serde_json gives an - // error when deserializing "" into (), so deserialize 'null' into it - // instead. - // An alternate option would be to require U: Default, and then return - // U::default() here instead since () implements that, but then we'd - // need to impl default for all models. - futures::future::ok::(serde_json::from_str("null").expect("serde null value")).boxed() - } else { - let collect = response.into_body().collect().map_err(Error::from); - collect.map(|collected| { - collected.and_then(|collected| { - serde_json::from_slice(&collected.to_bytes()).map_err(Error::from) - }) - }).boxed() - } - })) - } -} From 605d47667549bdd33d36ead34fede6e6b9c70730 Mon Sep 17 00:00:00 2001 From: RoDmitry Date: Mon, 15 Sep 2025 12:23:24 +0000 Subject: [PATCH 35/41] expose pub ResponseContent --- typesense/src/error.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/typesense/src/error.rs b/typesense/src/error.rs index e6b705c..e0f7530 100644 --- a/typesense/src/error.rs +++ b/typesense/src/error.rs @@ -1,7 +1,7 @@ //! Contains the error types for the Typesense client use thiserror::Error; -pub use typesense_codegen::apis::Error as ApiError; +pub use typesense_codegen::apis::{Error as ApiError, ResponseContent}; /// The primary error type for the Typesense client. /// From c2bb563eb25119b36a270aa3e455b596f2edb8c3 Mon Sep 17 00:00:00 2001 From: RoDmitry Date: Mon, 15 Sep 2025 13:12:08 +0000 Subject: [PATCH 36/41] Avoid apikey clone --- openapi-generator-template/lib.mustache | 3 +- .../reqwest/api.mustache | 8 +-- typesense_codegen/.openapi-generator/VERSION | 2 +- typesense_codegen/README.md | 2 +- typesense_codegen/src/apis/analytics_api.rs | 36 ++++++------ typesense_codegen/src/apis/collections_api.rs | 36 ++++++------ .../src/apis/conversations_api.rs | 20 +++---- typesense_codegen/src/apis/curation_api.rs | 12 ++-- typesense_codegen/src/apis/debug_api.rs | 4 +- typesense_codegen/src/apis/documents_api.rs | 56 +++++++++---------- typesense_codegen/src/apis/health_api.rs | 4 +- typesense_codegen/src/apis/keys_api.rs | 16 +++--- .../src/apis/nl_search_models_api.rs | 20 +++---- typesense_codegen/src/apis/operations_api.rs | 32 +++++------ typesense_codegen/src/apis/override_api.rs | 4 +- typesense_codegen/src/apis/presets_api.rs | 16 +++--- typesense_codegen/src/apis/stemming_api.rs | 12 ++-- typesense_codegen/src/apis/stopwords_api.rs | 16 +++--- typesense_codegen/src/apis/synonyms_api.rs | 16 +++--- typesense_codegen/src/lib.rs | 3 +- 20 files changed, 160 insertions(+), 158 deletions(-) diff --git a/openapi-generator-template/lib.mustache b/openapi-generator-template/lib.mustache index f9a96b5..d9c227b 100644 --- a/openapi-generator-template/lib.mustache +++ b/openapi-generator-template/lib.mustache @@ -1,5 +1,6 @@ #![allow(unused_imports)] -#![allow(clippy::all)] +#![allow(clippy::empty_docs)] +#![allow(clippy::needless_return)] #![allow(elided_lifetimes_in_paths)] pub mod apis; diff --git a/openapi-generator-template/reqwest/api.mustache b/openapi-generator-template/reqwest/api.mustache index 428b461..e56af93 100644 --- a/openapi-generator-template/reqwest/api.mustache +++ b/openapi-generator-template/reqwest/api.mustache @@ -241,8 +241,8 @@ pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}{{{vendorExtensi if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.query(&[("{{{keyParamName}}}", value)]); } @@ -312,8 +312,8 @@ pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}{{{vendorExtensi if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("{{{keyParamName}}}", value); }; diff --git a/typesense_codegen/.openapi-generator/VERSION b/typesense_codegen/.openapi-generator/VERSION index e465da4..5e52829 100644 --- a/typesense_codegen/.openapi-generator/VERSION +++ b/typesense_codegen/.openapi-generator/VERSION @@ -1 +1 @@ -7.14.0 +7.16.0-SNAPSHOT diff --git a/typesense_codegen/README.md b/typesense_codegen/README.md index f16906b..768dcfa 100644 --- a/typesense_codegen/README.md +++ b/typesense_codegen/README.md @@ -9,7 +9,7 @@ This API client was generated by the [OpenAPI Generator](https://openapi-generat - API version: 30.0 - Package version: 30.0 -- Generator version: 7.14.0 +- Generator version: 7.16.0-SNAPSHOT - Build package: `org.openapitools.codegen.languages.RustClientCodegen` ## Installation diff --git a/typesense_codegen/src/apis/analytics_api.rs b/typesense_codegen/src/apis/analytics_api.rs index 2fdfbda..ef17e52 100644 --- a/typesense_codegen/src/apis/analytics_api.rs +++ b/typesense_codegen/src/apis/analytics_api.rs @@ -152,8 +152,8 @@ pub async fn create_analytics_event( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -212,8 +212,8 @@ pub async fn create_analytics_rule( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -276,8 +276,8 @@ pub async fn delete_analytics_rule( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -334,8 +334,8 @@ pub async fn flush_analytics( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -394,8 +394,8 @@ pub async fn get_analytics_events( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -450,8 +450,8 @@ pub async fn get_analytics_status( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -511,8 +511,8 @@ pub async fn retrieve_analytics_rule( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -571,8 +571,8 @@ pub async fn retrieve_analytics_rules( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -632,8 +632,8 @@ pub async fn upsert_analytics_rule( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; diff --git a/typesense_codegen/src/apis/collections_api.rs b/typesense_codegen/src/apis/collections_api.rs index fab2565..b965f8c 100644 --- a/typesense_codegen/src/apis/collections_api.rs +++ b/typesense_codegen/src/apis/collections_api.rs @@ -163,8 +163,8 @@ pub async fn create_collection( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -226,8 +226,8 @@ pub async fn delete_alias( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -289,8 +289,8 @@ pub async fn delete_collection( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -350,8 +350,8 @@ pub async fn get_alias( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -406,8 +406,8 @@ pub async fn get_aliases( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -467,8 +467,8 @@ pub async fn get_collection( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -533,8 +533,8 @@ pub async fn get_collections( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -596,8 +596,8 @@ pub async fn update_collection( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -658,8 +658,8 @@ pub async fn upsert_alias( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; diff --git a/typesense_codegen/src/apis/conversations_api.rs b/typesense_codegen/src/apis/conversations_api.rs index cef0821..c495f6b 100644 --- a/typesense_codegen/src/apis/conversations_api.rs +++ b/typesense_codegen/src/apis/conversations_api.rs @@ -93,8 +93,8 @@ pub async fn create_conversation_model( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -157,8 +157,8 @@ pub async fn delete_conversation_model( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -213,8 +213,8 @@ pub async fn retrieve_all_conversation_models( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -275,8 +275,8 @@ pub async fn retrieve_conversation_model( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -336,8 +336,8 @@ pub async fn update_conversation_model( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; diff --git a/typesense_codegen/src/apis/curation_api.rs b/typesense_codegen/src/apis/curation_api.rs index 6a05944..4d3c9c6 100644 --- a/typesense_codegen/src/apis/curation_api.rs +++ b/typesense_codegen/src/apis/curation_api.rs @@ -83,8 +83,8 @@ pub async fn delete_search_override( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -143,8 +143,8 @@ pub async fn get_search_overrides( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -205,8 +205,8 @@ pub async fn upsert_search_override( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; diff --git a/typesense_codegen/src/apis/debug_api.rs b/typesense_codegen/src/apis/debug_api.rs index 86fc9ea..73a5dba 100644 --- a/typesense_codegen/src/apis/debug_api.rs +++ b/typesense_codegen/src/apis/debug_api.rs @@ -33,8 +33,8 @@ pub async fn debug( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; diff --git a/typesense_codegen/src/apis/documents_api.rs b/typesense_codegen/src/apis/documents_api.rs index 48c2b31..92a3e8e 100644 --- a/typesense_codegen/src/apis/documents_api.rs +++ b/typesense_codegen/src/apis/documents_api.rs @@ -421,8 +421,8 @@ pub async fn delete_document( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -496,8 +496,8 @@ pub async fn delete_documents( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -559,8 +559,8 @@ pub async fn delete_search_override( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -629,8 +629,8 @@ pub async fn export_documents( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -686,8 +686,8 @@ pub async fn get_document( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -748,8 +748,8 @@ pub async fn get_search_override( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -808,8 +808,8 @@ pub async fn get_search_overrides( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -890,8 +890,8 @@ pub async fn import_documents( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -957,8 +957,8 @@ pub async fn index_document( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -1219,8 +1219,8 @@ pub async fn multi_search( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -1504,8 +1504,8 @@ pub async fn search_collection serde::Deserialize<'de> + Serialize>( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -1571,8 +1571,8 @@ pub async fn update_document( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -1638,8 +1638,8 @@ pub async fn update_documents( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -1701,8 +1701,8 @@ pub async fn upsert_search_override( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; diff --git a/typesense_codegen/src/apis/health_api.rs b/typesense_codegen/src/apis/health_api.rs index 1a61750..8cc1524 100644 --- a/typesense_codegen/src/apis/health_api.rs +++ b/typesense_codegen/src/apis/health_api.rs @@ -33,8 +33,8 @@ pub async fn health( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; diff --git a/typesense_codegen/src/apis/keys_api.rs b/typesense_codegen/src/apis/keys_api.rs index 9a1b350..c702492 100644 --- a/typesense_codegen/src/apis/keys_api.rs +++ b/typesense_codegen/src/apis/keys_api.rs @@ -83,8 +83,8 @@ pub async fn create_key( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -146,8 +146,8 @@ pub async fn delete_key( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -207,8 +207,8 @@ pub async fn get_key( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -262,8 +262,8 @@ pub async fn get_keys( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; diff --git a/typesense_codegen/src/apis/nl_search_models_api.rs b/typesense_codegen/src/apis/nl_search_models_api.rs index dfe3f42..5458cbb 100644 --- a/typesense_codegen/src/apis/nl_search_models_api.rs +++ b/typesense_codegen/src/apis/nl_search_models_api.rs @@ -99,8 +99,8 @@ pub async fn create_nl_search_model( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -163,8 +163,8 @@ pub async fn delete_nl_search_model( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -219,8 +219,8 @@ pub async fn retrieve_all_nl_search_models( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -280,8 +280,8 @@ pub async fn retrieve_nl_search_model( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -341,8 +341,8 @@ pub async fn update_nl_search_model( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; diff --git a/typesense_codegen/src/apis/operations_api.rs b/typesense_codegen/src/apis/operations_api.rs index ab149ed..8a1b91d 100644 --- a/typesense_codegen/src/apis/operations_api.rs +++ b/typesense_codegen/src/apis/operations_api.rs @@ -97,8 +97,8 @@ pub async fn clear_cache( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -155,8 +155,8 @@ pub async fn compact_db( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -211,8 +211,8 @@ pub async fn get_schema_changes( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -267,8 +267,8 @@ pub async fn retrieve_api_stats( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -323,8 +323,8 @@ pub async fn retrieve_metrics( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -383,8 +383,8 @@ pub async fn take_snapshot( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -442,8 +442,8 @@ pub async fn toggle_slow_request_log( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -501,8 +501,8 @@ pub async fn vote( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; diff --git a/typesense_codegen/src/apis/override_api.rs b/typesense_codegen/src/apis/override_api.rs index 119ae1a..9eadf5a 100644 --- a/typesense_codegen/src/apis/override_api.rs +++ b/typesense_codegen/src/apis/override_api.rs @@ -48,8 +48,8 @@ pub async fn get_search_override( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; diff --git a/typesense_codegen/src/apis/presets_api.rs b/typesense_codegen/src/apis/presets_api.rs index 1786754..8b296b2 100644 --- a/typesense_codegen/src/apis/presets_api.rs +++ b/typesense_codegen/src/apis/presets_api.rs @@ -87,8 +87,8 @@ pub async fn delete_preset( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -143,8 +143,8 @@ pub async fn retrieve_all_presets( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -204,8 +204,8 @@ pub async fn retrieve_preset( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -265,8 +265,8 @@ pub async fn upsert_preset( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; diff --git a/typesense_codegen/src/apis/stemming_api.rs b/typesense_codegen/src/apis/stemming_api.rs index 586048e..cd5e9cb 100644 --- a/typesense_codegen/src/apis/stemming_api.rs +++ b/typesense_codegen/src/apis/stemming_api.rs @@ -70,8 +70,8 @@ pub async fn get_stemming_dictionary( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -130,8 +130,8 @@ pub async fn import_stemming_dictionary( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -187,8 +187,8 @@ pub async fn list_stemming_dictionaries( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; diff --git a/typesense_codegen/src/apis/stopwords_api.rs b/typesense_codegen/src/apis/stopwords_api.rs index fea216c..76c120b 100644 --- a/typesense_codegen/src/apis/stopwords_api.rs +++ b/typesense_codegen/src/apis/stopwords_api.rs @@ -87,8 +87,8 @@ pub async fn delete_stopwords_set( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -148,8 +148,8 @@ pub async fn retrieve_stopwords_set( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -204,8 +204,8 @@ pub async fn retrieve_stopwords_sets( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -265,8 +265,8 @@ pub async fn upsert_stopwords_set( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; diff --git a/typesense_codegen/src/apis/synonyms_api.rs b/typesense_codegen/src/apis/synonyms_api.rs index 2bd3580..90777fa 100644 --- a/typesense_codegen/src/apis/synonyms_api.rs +++ b/typesense_codegen/src/apis/synonyms_api.rs @@ -87,8 +87,8 @@ pub async fn delete_synonym_set( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -148,8 +148,8 @@ pub async fn retrieve_synonym_set( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -204,8 +204,8 @@ pub async fn retrieve_synonym_sets( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; @@ -265,8 +265,8 @@ pub async fn upsert_synonym_set( if let Some(ref apikey) = configuration.api_key { let key = &apikey.key; let value = match apikey.prefix { - Some(ref prefix) => format!("{prefix} {key}"), - None => key.clone(), + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; diff --git a/typesense_codegen/src/lib.rs b/typesense_codegen/src/lib.rs index f9a96b5..d9c227b 100644 --- a/typesense_codegen/src/lib.rs +++ b/typesense_codegen/src/lib.rs @@ -1,5 +1,6 @@ #![allow(unused_imports)] -#![allow(clippy::all)] +#![allow(clippy::empty_docs)] +#![allow(clippy::needless_return)] #![allow(elided_lifetimes_in_paths)] pub mod apis; From 0070ab28e1491813f1c151639500e764bb5319ce Mon Sep 17 00:00:00 2001 From: RoDmitry Date: Mon, 15 Sep 2025 16:18:07 +0000 Subject: [PATCH 37/41] Rename generic --- typesense/src/client/collection/document.rs | 16 ++++++++-------- typesense/src/client/collection/documents.rs | 16 ++++++++-------- typesense/src/client/collection/mod.rs | 14 +++++++------- 3 files changed, 23 insertions(+), 23 deletions(-) diff --git a/typesense/src/client/collection/document.rs b/typesense/src/client/collection/document.rs index 81f5550..35f7115 100644 --- a/typesense/src/client/collection/document.rs +++ b/typesense/src/client/collection/document.rs @@ -13,19 +13,19 @@ use typesense_codegen::apis::documents_api; /// This struct is created by calling a method like `client.collection("collection_name").document("document_id")` or `client.collection_of::("collection_name").document("document_id")`. /// The generic `T` represents the shape of the document and must implement `Serialize` and `DeserializeOwned`. /// If `T` is not specified, it defaults to `serde_json::Value` for schemaless interactions. -pub struct Document<'c, 'n, T = serde_json::Value> +pub struct Document<'c, 'n, D = serde_json::Value> where - T: DeserializeOwned + Serialize + Send + Sync, + D: DeserializeOwned + Serialize + Send + Sync, { pub(super) client: &'c Client, pub(super) collection_name: &'n str, pub(super) document_id: String, - pub(super) _phantom: std::marker::PhantomData, + pub(super) _phantom: std::marker::PhantomData, } -impl<'c, 'n, T> Document<'c, 'n, T> +impl<'c, 'n, D> Document<'c, 'n, D> where - T: DeserializeOwned + Serialize + Send + Sync, + D: DeserializeOwned + Serialize + Send + Sync, { /// Creates a new `Document` instance for a specific document ID. #[inline] @@ -42,7 +42,7 @@ where /// /// # Returns /// A `Result` containing the strongly-typed document `T` if successful. - pub async fn retrieve(&self) -> Result> { + pub async fn retrieve(&self) -> Result> { let params = documents_api::GetDocumentParams { collection_name: self.collection_name.to_owned(), document_id: self.document_id.to_owned(), @@ -100,7 +100,7 @@ where &self, partial_document: U, params: Option, - ) -> Result> { + ) -> Result> { let params = documents_api::UpdateDocumentParams { collection_name: self.collection_name.to_owned(), document_id: self.document_id.to_owned(), @@ -119,7 +119,7 @@ where /// /// # Returns /// A `Result` containing the deleted document deserialized into `T`. - pub async fn delete(&self) -> Result> { + pub async fn delete(&self) -> Result> { let params = documents_api::DeleteDocumentParams { collection_name: self.collection_name.to_owned(), document_id: self.document_id.to_owned(), diff --git a/typesense/src/client/collection/documents.rs b/typesense/src/client/collection/documents.rs index 5da26aa..75944b2 100644 --- a/typesense/src/client/collection/documents.rs +++ b/typesense/src/client/collection/documents.rs @@ -21,18 +21,18 @@ use typesense_codegen::{ /// This struct is generic over the document type `T`. If created via `client.collection(...)`, /// `T` defaults to `serde_json::Value`. If created via `client.collection_of::(...)`, /// `T` will be `MyType`. -pub struct Documents<'c, 'n, T = serde_json::Value> +pub struct Documents<'c, 'n, D = serde_json::Value> where - T: DeserializeOwned + Serialize + Send + Sync, + D: DeserializeOwned + Serialize + Send + Sync, { pub(super) client: &'c Client, pub(super) collection_name: &'n str, - pub(super) _phantom: std::marker::PhantomData, + pub(super) _phantom: std::marker::PhantomData, } -impl<'c, 'n, T> Documents<'c, 'n, T> +impl<'c, 'n, D> Documents<'c, 'n, D> where - T: DeserializeOwned + Serialize + Send + Sync, + D: DeserializeOwned + Serialize + Send + Sync, { /// Creates a new `Documents` instance. #[inline] @@ -76,7 +76,7 @@ where &self, document: U, params: Option, - ) -> Result> { + ) -> Result> { let doc_value = serde_json::to_value(document)?; let result_value = self.index(doc_value, "create", params).await?; serde_json::from_value(result_value).map_err(Error::from) @@ -94,7 +94,7 @@ where &self, document: U, params: Option, - ) -> Result> { + ) -> Result> { let doc_value = serde_json::to_value(document)?; let result_value = self.index(doc_value, "upsert", params).await?; serde_json::from_value(result_value).map_err(Error::from) @@ -191,7 +191,7 @@ where pub async fn search( &self, params: raw_models::SearchParameters, - ) -> Result, Error> { + ) -> Result, Error> { let search_params = documents_api::SearchCollectionParams { collection_name: self.collection_name.to_owned(), diff --git a/typesense/src/client/collection/mod.rs b/typesense/src/client/collection/mod.rs index 05807fd..6249a1a 100644 --- a/typesense/src/client/collection/mod.rs +++ b/typesense/src/client/collection/mod.rs @@ -12,18 +12,18 @@ use typesense_codegen::{apis::collections_api, models}; /// Provides methods for interacting with a Typesense collection. /// /// This struct is created by calling `client.collection("collection_name")`. -pub struct Collection<'c, 'n, T = serde_json::Value> +pub struct Collection<'c, 'n, D = serde_json::Value> where - T: DeserializeOwned + Serialize + Send + Sync, + D: DeserializeOwned + Serialize + Send + Sync, { pub(super) client: &'c Client, pub(super) collection_name: &'n str, - pub(super) _phantom: std::marker::PhantomData, + pub(super) _phantom: std::marker::PhantomData, } -impl<'c, 'n, T> Collection<'c, 'n, T> +impl<'c, 'n, D> Collection<'c, 'n, D> where - T: DeserializeOwned + Serialize + Send + Sync, + D: DeserializeOwned + Serialize + Send + Sync, { /// Creates a new `Collection` instance. #[inline] @@ -37,13 +37,13 @@ where /// Provides access to the document-related API endpoints for a specific collection. #[inline] - pub fn documents(&self) -> documents::Documents<'c, 'n, T> { + pub fn documents(&self) -> documents::Documents<'c, 'n, D> { documents::Documents::new(self.client, self.collection_name) } /// Provides access to the API endpoints for a single document within a Typesense collection. #[inline] - pub fn document(&self, document_id: impl Into) -> document::Document<'c, 'n, T> { + pub fn document(&self, document_id: impl Into) -> document::Document<'c, 'n, D> { document::Document::new(self.client, self.collection_name, document_id.into()) } From 9783c60ec4abc7ec87d0b41f443a5348d59c881c Mon Sep 17 00:00:00 2001 From: RoDmitry Date: Mon, 15 Sep 2025 17:27:13 +0000 Subject: [PATCH 38/41] Rename: collection() requires trait Document --- typesense/src/client/collection/document.rs | 35 +++++----- typesense/src/client/collection/documents.rs | 26 +++---- typesense/src/client/collection/mod.rs | 12 ++-- typesense/src/client/mod.rs | 71 ++++++++++++++++---- typesense/src/traits/document.rs | 3 + typesense/src/traits/multi_search_ext.rs | 6 +- typesense/tests/client/client_test.rs | 58 ++++++++++++---- typesense/tests/client/collections_test.rs | 22 ++++-- typesense/tests/client/documents_test.rs | 14 ++-- typesense/tests/client/multi_search_test.rs | 4 +- typesense_derive/src/lib.rs | 6 +- 11 files changed, 175 insertions(+), 82 deletions(-) diff --git a/typesense/src/client/collection/document.rs b/typesense/src/client/collection/document.rs index 35f7115..1398d60 100644 --- a/typesense/src/client/collection/document.rs +++ b/typesense/src/client/collection/document.rs @@ -2,7 +2,7 @@ //! //! An instance of `Document` is scoped to a specific document and is created //! via a parent `Collection` struct, for example: -//! `client.collection::("books").document("123")` +//! `client.collection::().document("123")` use crate::{Client, Error, execute_wrapper}; use serde::{Serialize, de::DeserializeOwned}; @@ -10,22 +10,23 @@ use typesense_codegen::apis::documents_api; /// Provides methods for interacting with a single document within a specific Typesense collection. /// -/// This struct is created by calling a method like `client.collection("collection_name").document("document_id")` or `client.collection_of::("collection_name").document("document_id")`. -/// The generic `T` represents the shape of the document and must implement `Serialize` and `DeserializeOwned`. -/// If `T` is not specified, it defaults to `serde_json::Value` for schemaless interactions. +/// This struct is created by calling a method like `client.collection_schemaless("collection_name").document("document_id")` +/// or `client.collection::().document("document_id")`. +/// The generic `D` represents the shape of the document and must implement `Serialize` and `DeserializeOwned`. +/// If `D` is not specified, it defaults to `serde_json::Value` for schemaless interactions. pub struct Document<'c, 'n, D = serde_json::Value> where - D: DeserializeOwned + Serialize + Send + Sync, + D: DeserializeOwned + Serialize, { - pub(super) client: &'c Client, - pub(super) collection_name: &'n str, - pub(super) document_id: String, - pub(super) _phantom: std::marker::PhantomData, + client: &'c Client, + collection_name: &'n str, + document_id: String, + _phantom: std::marker::PhantomData, } impl<'c, 'n, D> Document<'c, 'n, D> where - D: DeserializeOwned + Serialize + Send + Sync, + D: DeserializeOwned + Serialize, { /// Creates a new `Document` instance for a specific document ID. #[inline] @@ -38,10 +39,10 @@ where } } - /// Fetches this individual document from the collection and deserializes it into `T`. + /// Fetches this individual document from the collection and deserializes it into `D`. /// /// # Returns - /// A `Result` containing the strongly-typed document `T` if successful. + /// A `Result` containing the strongly-typed document `D` if successful. pub async fn retrieve(&self) -> Result> { let params = documents_api::GetDocumentParams { collection_name: self.collection_name.to_owned(), @@ -62,7 +63,7 @@ where /// * `params` - An optional `DocumentIndexParameters` struct to specify additional parameters, such as `dirty_values` which determines what Typesense should do when the type of a particular field being indexed does not match the previously inferred type for that field, or the one defined in the collection's schema. /// /// # Returns - /// A `Result` containing the full, updated document deserialized into `T`. + /// A `Result` containing the full, updated document deserialized into `D`. /// /// # Example /// ```no_run @@ -81,7 +82,7 @@ where /// let book_update = serde_json::json!({ "pages": 654 }); /// /// // Simple update - /// let updated_book = client.collection_of::("books").document("123") + /// let updated_book = client.collection_named::("books").document("123") /// .update(&book_update, None) /// .await?; /// @@ -89,7 +90,7 @@ where /// let params = models::DocumentIndexParameters { /// dirty_values: Some(models::DirtyValues::CoerceOrReject), /// }; - /// let updated_book_with_params = client.collection_of::("books").document("124") + /// let updated_book_with_params = client.collection_named::("books").document("124") /// .update(&book_update, Some(params)) /// .await?; /// # @@ -105,7 +106,7 @@ where collection_name: self.collection_name.to_owned(), document_id: self.document_id.to_owned(), body: serde_json::to_value(partial_document)?, - dirty_values: params.unwrap_or_default().dirty_values, + dirty_values: params.and_then(|d| d.dirty_values), }; let result_value = execute_wrapper!(self, documents_api::update_document, params)?; @@ -118,7 +119,7 @@ where /// The deleted document is returned. /// /// # Returns - /// A `Result` containing the deleted document deserialized into `T`. + /// A `Result` containing the deleted document deserialized into `D`. pub async fn delete(&self) -> Result> { let params = documents_api::DeleteDocumentParams { collection_name: self.collection_name.to_owned(), diff --git a/typesense/src/client/collection/documents.rs b/typesense/src/client/collection/documents.rs index 75944b2..c2c5d7d 100644 --- a/typesense/src/client/collection/documents.rs +++ b/typesense/src/client/collection/documents.rs @@ -1,8 +1,8 @@ //! Provides access to the document, search, and override-related API endpoints. //! //! An instance of `Documents` is scoped to a specific collection and is created -//! via the main `client.collection("collection_name").documents()` method or -//! `client.collection_of::("...").documents()`. +//! via the main `client.collection_schemaless("collection_name").documents()` method or +//! `client.collection_named::("...").documents()`. use crate::{ Client, Error, execute_wrapper, @@ -18,21 +18,21 @@ use typesense_codegen::{ }; /// Provides methods for interacting with documents within a specific Typesense collection. /// -/// This struct is generic over the document type `T`. If created via `client.collection(...)`, -/// `T` defaults to `serde_json::Value`. If created via `client.collection_of::(...)`, -/// `T` will be `MyType`. +/// This struct is generic over the document type `D`. If created via `client.collection_schemaless(...)`, +/// `D` defaults to `serde_json::Value`. If created via `client.collection_named::(...)`, +/// `D` will be `MyType`. pub struct Documents<'c, 'n, D = serde_json::Value> where - D: DeserializeOwned + Serialize + Send + Sync, + D: DeserializeOwned + Serialize, { - pub(super) client: &'c Client, - pub(super) collection_name: &'n str, - pub(super) _phantom: std::marker::PhantomData, + client: &'c Client, + collection_name: &'n str, + _phantom: std::marker::PhantomData, } impl<'c, 'n, D> Documents<'c, 'n, D> where - D: DeserializeOwned + Serialize + Send + Sync, + D: DeserializeOwned + Serialize, { /// Creates a new `Documents` instance. #[inline] @@ -58,7 +58,7 @@ where collection_name: self.collection_name.to_owned(), body: document, action: Some(action.to_owned()), - dirty_values: params.unwrap_or_default().dirty_values, // Or expose this as an argument if needed + dirty_values: params.and_then(|d| d.dirty_values), // Or expose this as an argument if needed }; execute_wrapper!(self, documents_api::index_document, params) } @@ -85,7 +85,7 @@ where /// Creates a new document or updates an existing one if an ID match is found. /// /// This method requires the full document to be sent. For partial updates, use - /// `collection("...").document("...").update()`. The indexed document is returned. + /// `collection().document("...").update()`. The indexed document is returned. /// /// # Arguments /// * `document` - A serializable struct or a `serde_json::Value` representing the document to upsert. @@ -184,7 +184,7 @@ where } /// Searches for documents in the collection that match the given criteria. - /// The search results will have their `document` field deserialized into type `T`. + /// The search results will have their `document` field deserialized into type `D`. /// /// # Arguments /// * `params` - A `SearchParameters` struct containing all search parameters. diff --git a/typesense/src/client/collection/mod.rs b/typesense/src/client/collection/mod.rs index 6249a1a..ba06950 100644 --- a/typesense/src/client/collection/mod.rs +++ b/typesense/src/client/collection/mod.rs @@ -11,19 +11,19 @@ use typesense_codegen::{apis::collections_api, models}; /// Provides methods for interacting with a Typesense collection. /// -/// This struct is created by calling `client.collection("collection_name")`. +/// This struct is created by calling `client.collection()`. pub struct Collection<'c, 'n, D = serde_json::Value> where - D: DeserializeOwned + Serialize + Send + Sync, + D: DeserializeOwned + Serialize, { - pub(super) client: &'c Client, - pub(super) collection_name: &'n str, - pub(super) _phantom: std::marker::PhantomData, + client: &'c Client, + collection_name: &'n str, + _phantom: std::marker::PhantomData, } impl<'c, 'n, D> Collection<'c, 'n, D> where - D: DeserializeOwned + Serialize + Send + Sync, + D: DeserializeOwned + Serialize, { /// Creates a new `Collection` instance. #[inline] diff --git a/typesense/src/client/mod.rs b/typesense/src/client/mod.rs index 1aaed1e..cd5e5be 100644 --- a/typesense/src/client/mod.rs +++ b/typesense/src/client/mod.rs @@ -33,7 +33,7 @@ //! .unwrap(); //! //! // Retrieve details for a collection -//! let collection = client.collection("products").retrieve().await?; +//! let collection = client.collection_schemaless("products").retrieve().await?; //! println!("Collection Name: {}", collection.name); //! //! // Search for a document @@ -44,7 +44,7 @@ //! }; //! //! let search_results = client -//! .collection("products") +//! .collection_schemaless("products") //! .documents() //! .search(search_params) //! .await?; @@ -84,7 +84,7 @@ //! .unwrap(); //! //! // Retrieve details for a collection -//! match client.collection("products").retrieve().await { +//! match client.collection_schemaless("products").retrieve().await { //! Ok(collection) => println!("Collection Name: {}", collection.name), //! Err(e) => eprintln!("Error retrieving collection: {}", e), //! } @@ -96,7 +96,7 @@ //! ..Default::default() //! }; //! -//! match client.collection("products").documents().search(search_params).await { +//! match client.collection_schemaless("products").documents().search(search_params).await { //! Ok(search_results) => { //! println!("Found {} hits.", search_results.found.unwrap_or(0)); //! } @@ -112,7 +112,7 @@ mod key; mod keys; mod multi_search; -use crate::Error; +use crate::{Error, traits::Document}; use collection::Collection; use collections::Collections; use key::Key; @@ -368,7 +368,7 @@ impl Client { /// stored in that collection. /// /// # Type Parameters - /// * `T` - The type of the documents in the collection. It must be serializable and deserializable. + /// * `D` - The type of the documents in the collection. It must be serializable and deserializable. /// /// # Arguments /// * `collection_name` - The name of the collection to interact with. @@ -392,7 +392,7 @@ impl Client { /// # .build() /// # .unwrap(); /// // Get a typed handle to the "books" collection - /// let books_collection = client.collection_of::("books"); + /// let books_collection = client.collection_named::("books"); /// /// // Retrieve a single book, it returns `Result` /// let book = books_collection.document("123").retrieve().await?; @@ -403,17 +403,62 @@ impl Client { /// # } /// ``` #[inline] - pub fn collection_of<'c, 'n, T>(&'c self, collection_name: &'n str) -> Collection<'c, 'n, T> + pub fn collection_named<'c, 'n, D>(&'c self, collection_name: &'n str) -> Collection<'c, 'n, D> where - T: DeserializeOwned + Serialize + Send + Sync, + D: DeserializeOwned + Serialize, { Collection::new(self, collection_name) } + /// Provides access to API endpoints for a specific collection. + /// + /// This method returns a `Collection` handle, which is generic over the type of document + /// stored in that collection. + /// + /// # Type Parameters + /// * `D` - The type of the documents in the collection. It must be of trait Document. + /// + /// # Example: Working with a strongly-typed collection + /// + /// When you want to retrieve or search for documents and have them automatically + /// deserialized into your own structs. + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { + /// # use typesense::{Client, Typesense}; + /// # use serde::{Serialize, Deserialize}; + /// # + /// # #[derive(Typesense, Serialize, Deserialize, Debug)] + /// # struct Book { id: String, title: String } + /// # async fn run() -> Result<(), Box> { + /// # let client = Client::builder() + /// # .nodes(vec!["http://localhost:8108"]) + /// # .api_key("xyz") + /// # .build() + /// # .unwrap(); + /// // Get a typed handle to the "books" collection + /// let books_collection = client.collection::(); + /// + /// // Retrieve a single book, it returns `Result` + /// let book = books_collection.document("123").retrieve().await?; + /// println!("Retrieved book: {:?}", book); + /// # + /// # Ok(()) + /// # } + /// # } + /// ``` + #[inline] + pub fn collection<'c, 'n, D>(&'c self) -> Collection<'c, 'n, D> + where + D: Document, + { + Collection::new(self, D::COLLECTION_NAME) + } + /// Provides access to API endpoints for a specific collection using schemaless `serde_json::Value` documents. /// /// This is the simplest way to interact with a collection when you do not need strong typing. - /// It is a convenient shorthand for `client.collection_of::("...")`. + /// It is a convenient shorthand for `client.collection_named::("...")`. /// /// The returned handle can be used for both document operations (which will return `serde_json::Value`) /// and collection-level operations (like `.delete()` or `.retrieve()`). @@ -432,18 +477,18 @@ impl Client { /// # .api_key("xyz") /// # .build() /// # .unwrap(); - /// let products_collection = client.collection("products"); + /// let products_collection = client.collection_schemaless("products"); /// # /// # Ok(()) /// # } /// # } /// ``` #[inline] - pub fn collection<'c, 'n>( + pub fn collection_schemaless<'c, 'n>( &'c self, collection_name: &'n str, ) -> Collection<'c, 'n, serde_json::Value> { - self.collection_of(collection_name) + Collection::new(self, collection_name) } /// Provides access to endpoints for managing the collection of API keys. diff --git a/typesense/src/traits/document.rs b/typesense/src/traits/document.rs index adf87e7..ace35f2 100644 --- a/typesense/src/traits/document.rs +++ b/typesense/src/traits/document.rs @@ -9,6 +9,9 @@ use serde::{Serialize, de::DeserializeOwned}; /// Trait that should implement every struct that wants to be represented as a Typesense /// Document pub trait Document: DeserializeOwned + Serialize { + /// Collection name + const COLLECTION_NAME: &'static str; + /// Collection schema associated with the document. fn collection_schema() -> CollectionSchema; } diff --git a/typesense/src/traits/multi_search_ext.rs b/typesense/src/traits/multi_search_ext.rs index 5be2bd5..7f47cf7 100644 --- a/typesense/src/traits/multi_search_ext.rs +++ b/typesense/src/traits/multi_search_ext.rs @@ -12,11 +12,11 @@ pub trait MultiSearchResultExt { /// * `index` - The zero-based index of the search result to parse. /// /// # Type Parameters - /// * `T` - The concrete document type to deserialize the hits into. - fn parse_at( + /// * `D` - The concrete document type to deserialize the hits into. + fn parse_at( &self, index: usize, - ) -> Result, MultiSearchParseError>; + ) -> Result, MultiSearchParseError>; } /// Small helpers to convert documents stored as `serde_json::Value` into a concrete `D`. diff --git a/typesense/tests/client/client_test.rs b/typesense/tests/client/client_test.rs index d28d9ed..05f3883 100644 --- a/typesense/tests/client/client_test.rs +++ b/typesense/tests/client/client_test.rs @@ -61,7 +61,7 @@ async fn test_success_on_first_node() { let client = get_client(vec![server1.uri()], None); - let result = client.collection("products").retrieve().await; + let result = client.collection_schemaless("products").retrieve().await; assert!(result.is_ok()); assert_eq!(result.unwrap().name, "products"); @@ -78,7 +78,7 @@ async fn test_failover_to_second_node() { let client = get_client(vec![server1.uri(), server2.uri()], None); - let result = client.collection("products").retrieve().await; + let result = client.collection_schemaless("products").retrieve().await; assert!(result.is_ok()); // The first server should have been tried and failed. @@ -96,7 +96,7 @@ async fn test_nearest_node_is_prioritized() { let client = get_client(vec![regular_server.uri()], Some(nearest_server.uri())); - let result = client.collection("products").retrieve().await; + let result = client.collection_schemaless("products").retrieve().await; assert!(result.is_ok()); // Only the nearest node should have received a request. @@ -113,7 +113,7 @@ async fn test_failover_from_nearest_to_regular_node() { let client = get_client(vec![regular_server.uri()], Some(nearest_server.uri())); - let result = client.collection("products").retrieve().await; + let result = client.collection_schemaless("products").retrieve().await; assert!(result.is_ok()); // Nearest node should have failed. @@ -134,7 +134,13 @@ async fn test_round_robin_failover() { let client = get_client(vec![server1.uri(), server2.uri(), server3.uri()], None); // First request should fail over to the third node - assert!(client.collection("products").retrieve().await.is_ok()); + assert!( + client + .collection_schemaless("products") + .retrieve() + .await + .is_ok() + ); assert_eq!(server1.received_requests().await.unwrap().len(), 1); assert_eq!(server2.received_requests().await.unwrap().len(), 1); @@ -151,7 +157,13 @@ async fn test_round_robin_failover() { server2.reset().await; setup_mock_server_ok(&server2, "products").await; - assert!(client.collection("products").retrieve().await.is_ok()); + assert!( + client + .collection_schemaless("products") + .retrieve() + .await + .is_ok() + ); // Server 3 was tried first and failed. assert_eq!(server3.received_requests().await.unwrap().len(), 1); @@ -179,12 +191,24 @@ async fn test_health_check_and_node_recovery() { .expect("Failed to create client"); // 1. First request fails over to server2, marking server1 as unhealthy. - assert!(client.collection("products").retrieve().await.is_ok()); + assert!( + client + .collection_schemaless("products") + .retrieve() + .await + .is_ok() + ); assert_eq!(server1.received_requests().await.unwrap().len(), 1); assert_eq!(server2.received_requests().await.unwrap().len(), 1); // 2. Immediate second request should go directly to server2. - assert!(client.collection("products").retrieve().await.is_ok()); + assert!( + client + .collection_schemaless("products") + .retrieve() + .await + .is_ok() + ); assert_eq!(server1.received_requests().await.unwrap().len(), 1); // No new request assert_eq!(server2.received_requests().await.unwrap().len(), 2); // Got another request @@ -196,7 +220,13 @@ async fn test_health_check_and_node_recovery() { setup_mock_server_ok(&server1, "products").await; // 5. The next request should try server1 again (due to healthcheck expiry) and succeed. - assert!(client.collection("products").retrieve().await.is_ok()); + assert!( + client + .collection_schemaless("products") + .retrieve() + .await + .is_ok() + ); assert_eq!(server1.received_requests().await.unwrap().len(), 1); // Server 1 received its first successful req assert_eq!(server2.received_requests().await.unwrap().len(), 2); // No new request for server 2 } @@ -210,7 +240,7 @@ async fn test_all_nodes_fail() { let client = get_client(vec![server1.uri(), server2.uri()], None); - let result = client.collection("products").retrieve().await; + let result = client.collection_schemaless("products").retrieve().await; assert!(result.is_err()); match result.err().unwrap() { @@ -233,7 +263,7 @@ async fn test_fail_fast_on_non_retriable_error() { let client = get_client(vec![server1.uri(), server2.uri()], None); - let result = client.collection("products").retrieve().await; + let result = client.collection_schemaless("products").retrieve().await; assert!(result.is_err()); // Check that the error is the non-retriable API error. @@ -264,9 +294,9 @@ async fn test_load_balancing_with_healthy_nodes() { let client = get_client(vec![server1.uri(), server2.uri(), server3.uri()], None); // 3. Make three consecutive requests - let result1 = client.collection("products").retrieve().await; - let result2 = client.collection("products").retrieve().await; - let result3 = client.collection("products").retrieve().await; + let result1 = client.collection_schemaless("products").retrieve().await; + let result2 = client.collection_schemaless("products").retrieve().await; + let result3 = client.collection_schemaless("products").retrieve().await; // 4. Assert all requests were successful assert!(result1.is_ok()); diff --git a/typesense/tests/client/collections_test.rs b/typesense/tests/client/collections_test.rs index ebfb919..70d471c 100644 --- a/typesense/tests/client/collections_test.rs +++ b/typesense/tests/client/collections_test.rs @@ -32,7 +32,10 @@ async fn logic_test_collections_and_collection_lifecycle() { assert_eq!(created_collection.name, collection_name); // --- 2. Retrieve the specific Collection (via `collection`) --- - let retrieve_one_result = client.collection(&collection_name).retrieve().await; + let retrieve_one_result = client + .collection_schemaless(&collection_name) + .retrieve() + .await; assert!( retrieve_one_result.is_ok(), "Failed to retrieve the newly created collection." @@ -80,7 +83,7 @@ async fn logic_test_collections_and_collection_lifecycle() { }; let update_result = client - .collection(&collection_name) + .collection_schemaless(&collection_name) .update(update_schema) .await; assert!(update_result.is_ok(), "Failed to update collection"); @@ -94,7 +97,10 @@ async fn logic_test_collections_and_collection_lifecycle() { ); // --- 6. Verify the update by retrieving the full schema again --- - let retrieve_after_update_result = client.collection(&collection_name).retrieve().await; + let retrieve_after_update_result = client + .collection_schemaless(&collection_name) + .retrieve() + .await; let retrieved_after_update = retrieve_after_update_result.unwrap(); // Initial fields: name, price. Update: +description, -price. Final fields: name, description. @@ -126,11 +132,17 @@ async fn logic_test_collections_and_collection_lifecycle() { ); // --- 7. Delete the Collection (via `collection`) --- - let delete_result = client.collection(&collection_name).delete().await; + let delete_result = client + .collection_schemaless(&collection_name) + .delete() + .await; assert!(delete_result.is_ok(), "Failed to delete collection"); // --- 8. Verify Deletion --- - let get_after_delete_result = client.collection(&collection_name).retrieve().await; + let get_after_delete_result = client + .collection_schemaless(&collection_name) + .retrieve() + .await; assert!( get_after_delete_result.is_err(), "Collection should not exist after deletion" diff --git a/typesense/tests/client/documents_test.rs b/typesense/tests/client/documents_test.rs index 63c37bf..04040a6 100644 --- a/typesense/tests/client/documents_test.rs +++ b/typesense/tests/client/documents_test.rs @@ -55,7 +55,7 @@ async fn run_test_document_lifecycle() { "author": "J.R.R. Tolkien", "publication_year": 1954 }); - let collection_client = client.collection(&collection_name); + let collection_client = client.collection_schemaless(&collection_name); let documents_client = collection_client.documents(); // --- 2. Create a document (via `documents().create()`) --- @@ -68,7 +68,7 @@ async fn run_test_document_lifecycle() { // --- 4. Retrieve a single document (via `document(id).retrieve()`) --- let retrieve_res = client - .collection(&collection_name) + .collection_schemaless(&collection_name) .document(book_1_id) .retrieve() .await; @@ -87,7 +87,7 @@ async fn run_test_document_lifecycle() { // --- 6. Update a single document --- let partial_update = json!({ "publication_year": 1980 }); let update_res = client - .collection(&collection_name) + .collection_schemaless(&collection_name) .document(book_1_id) .update(&partial_update, None) .await; @@ -95,7 +95,7 @@ async fn run_test_document_lifecycle() { // --- 7. Verify the single update --- let retrieve_after_update_res = client - .collection(&collection_name) + .collection_schemaless(&collection_name) .document(book_1_id) .retrieve() .await; @@ -107,7 +107,7 @@ async fn run_test_document_lifecycle() { // --- 8. Delete a single document --- let delete_res = client - .collection(&collection_name) + .collection_schemaless(&collection_name) .document(book_1_id) .delete() .await; @@ -115,7 +115,7 @@ async fn run_test_document_lifecycle() { // --- 9. Verify single deletion --- let retrieve_after_delete_res = client - .collection(&collection_name) + .collection_schemaless(&collection_name) .document(book_1_id) .retrieve() .await; @@ -244,7 +244,7 @@ async fn run_test_generic_document_lifecycle() { ); // Use the strongly-typed collection client - let typed_collection = client.collection_of::(&collection_name); + let typed_collection = client.collection_named::(&collection_name); let book_1 = Book { id: new_id("book_1"), diff --git a/typesense/tests/client/multi_search_test.rs b/typesense/tests/client/multi_search_test.rs index 1af56c1..643ff45 100644 --- a/typesense/tests/client/multi_search_test.rs +++ b/typesense/tests/client/multi_search_test.rs @@ -47,7 +47,7 @@ async fn setup_multi_search_tests( .join("\n"); client - .collection(products_collection_name) + .collection_schemaless(products_collection_name) .documents() .import_jsonl( product_docs, @@ -70,7 +70,7 @@ async fn setup_multi_search_tests( .join("\n"); client - .collection(brands_collection_name) + .collection_schemaless(brands_collection_name) .documents() .import_jsonl( brand_docs, diff --git a/typesense_derive/src/lib.rs b/typesense_derive/src/lib.rs index ba004af..a4fc97e 100644 --- a/typesense_derive/src/lib.rs +++ b/typesense_derive/src/lib.rs @@ -79,11 +79,13 @@ fn impl_typesense_collection(item: ItemStruct) -> syn::Result { let generated_code = quote! { impl #impl_generics typesense::prelude::Document for #ident #ty_generics #where_clause { + const COLLECTION_NAME: &str = #collection_name; + fn collection_schema() -> typesense::models::CollectionSchema { - let name = #collection_name.to_owned(); + let name = Self::COLLECTION_NAME.to_owned(); let fields = vec![#(#typesense_fields,)*]; - let mut builder = typesense::models::CollectionSchema::builder().name(name).fields(fields); + let builder = typesense::models::CollectionSchema::builder().name(name).fields(fields); #default_sorting_field #enable_nested_fields From 245b9a49e9bad21db431f2043fe98a4888c25f15 Mon Sep 17 00:00:00 2001 From: RoDmitry Date: Tue, 16 Sep 2025 14:30:10 +0000 Subject: [PATCH 39/41] Node::set_health --- typesense/src/client/mod.rs | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/typesense/src/client/mod.rs b/typesense/src/client/mod.rs index cd5e5be..11b232e 100644 --- a/typesense/src/client/mod.rs +++ b/typesense/src/client/mod.rs @@ -161,6 +161,16 @@ struct Node { is_healthy: AtomicBool, last_accessed: RwLock, } + +impl Node { + /// Sets the health status of the node + #[inline] + fn set_health(&self, is_healthy: bool) { + *self.last_accessed.write().unwrap() = Instant::now(); + self.is_healthy.store(is_healthy, Ordering::Relaxed); + } +} + /// The main entry point for all interactions with the Typesense API. /// /// The client manages connections to multiple nodes and provides access to different @@ -296,13 +306,6 @@ impl Client { self.nodes.get_safe_unchecked(index) } - /// Sets the health status of a given node after a request attempt. - #[inline] - fn set_node_health(&self, node: &Node, is_healthy: bool) { - *node.last_accessed.write().unwrap() = Instant::now(); - node.is_healthy.store(is_healthy, Ordering::Relaxed); - } - /// The core execution method that handles multi-node failover and retries. /// This internal method is called by all public API methods. pub(super) async fn execute(&'a self, api_call: F) -> Result> @@ -318,12 +321,12 @@ impl Client { let node = self.get_next_node(); match api_call(&node.config).await { Ok(response) => { - self.set_node_health(node, true); + node.set_health(true); return Ok(response); } Err(e) => { if is_retriable(&e) { - self.set_node_health(node, false); + node.set_health(false); last_api_error = Some(e); } else { return Err(e.into()); From 7347a04879750d1f0a88026ea827f945882ba626 Mon Sep 17 00:00:00 2001 From: RoDmitry Date: Sat, 20 Sep 2025 16:00:07 +0000 Subject: [PATCH 40/41] Legacy API --- typesense/src/client/mod.rs | 13 ++++++++++--- typesense/src/lib.rs | 2 ++ typesense_codegen/src/apis/configuration.rs | 4 +++- 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/typesense/src/client/mod.rs b/typesense/src/client/mod.rs index 11b232e..5ccdead 100644 --- a/typesense/src/client/mod.rs +++ b/typesense/src/client/mod.rs @@ -289,6 +289,7 @@ impl Client { self.current_node_index.fetch_add(1, Ordering::Relaxed) % self.nodes.len(), ) }; + for _ in 0..self.nodes.len() { let node = self.nodes.get_safe_unchecked(index); @@ -302,10 +303,16 @@ impl Client { // If all nodes are unhealthy and not due for a check, just pick the next one in the round-robin. // This gives it a chance to prove it has recovered. - let index = self.current_node_index.load(Ordering::Relaxed) % self.nodes.len(); + index = self.current_node_index.load(Ordering::Relaxed) % self.nodes.len(); self.nodes.get_safe_unchecked(index) } + /// For use in legacy APIs. + #[inline] + pub fn get_legacy_config(&self) -> &configuration::Configuration { + &self.get_next_node().config + } + /// The core execution method that handles multi-node failover and retries. /// This internal method is called by all public API methods. pub(super) async fn execute(&'a self, api_call: F) -> Result> @@ -367,7 +374,7 @@ impl Client { /// Provides access to API endpoints for a specific collection. /// - /// This method returns a `Collection` handle, which is generic over the type of document + /// This method returns a `Collection` handle, which is generic over the type of document /// stored in that collection. /// /// # Type Parameters @@ -415,7 +422,7 @@ impl Client { /// Provides access to API endpoints for a specific collection. /// - /// This method returns a `Collection` handle, which is generic over the type of document + /// This method returns a `Collection` handle, which is generic over the type of document /// stored in that collection. /// /// # Type Parameters diff --git a/typesense/src/lib.rs b/typesense/src/lib.rs index 1e603c0..9afac33 100644 --- a/typesense/src/lib.rs +++ b/typesense/src/lib.rs @@ -122,6 +122,8 @@ pub mod prelude; pub use client::{Client, ExponentialBackoff}; pub use error::*; +pub use typesense_codegen as legacy; + #[cfg(feature = "typesense_derive")] #[doc(hidden)] pub use typesense_derive::*; diff --git a/typesense_codegen/src/apis/configuration.rs b/typesense_codegen/src/apis/configuration.rs index d433e31..32cfc2e 100644 --- a/typesense_codegen/src/apis/configuration.rs +++ b/typesense_codegen/src/apis/configuration.rs @@ -35,12 +35,14 @@ pub struct ApiKey { } impl Configuration { + #[inline] pub fn new() -> Configuration { Configuration::default() } } impl Default for Configuration { + #[inline] fn default() -> Self { #[cfg(target_arch = "wasm32")] let client = reqwest::Client::new(); @@ -49,7 +51,7 @@ impl Default for Configuration { let client = reqwest_middleware::ClientBuilder::new(reqwest::Client::new()).build(); Configuration { base_path: "http://localhost".to_owned(), - user_agent: Some("OpenAPI-Generator/28.0/rust".to_owned()), + user_agent: Some("OpenAPI-Generator/30.0/rust".to_owned()), client, basic_auth: None, oauth_access_token: None, From ab05dcf6285421b310c47c301352b06892bf3697 Mon Sep 17 00:00:00 2001 From: RoDmitry Date: Sat, 20 Sep 2025 16:12:12 +0000 Subject: [PATCH 41/41] Fix test --- typesense/tests/derive/ui/wrong_sorting_field.stderr | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/typesense/tests/derive/ui/wrong_sorting_field.stderr b/typesense/tests/derive/ui/wrong_sorting_field.stderr index f8d61f5..919a41a 100644 --- a/typesense/tests/derive/ui/wrong_sorting_field.stderr +++ b/typesense/tests/derive/ui/wrong_sorting_field.stderr @@ -1,10 +1,10 @@ error: defined default_sorting_field = "wrong_field" does not match with any field. --> $DIR/wrong_sorting_field.rs:5:1 | -5 | / #[typesense(default_sorting_field = "wrong_field")] -6 | | struct Company { -7 | | company_name: String, -8 | | num_employees: i32, -9 | | country: String, + 5 | / #[typesense(default_sorting_field = "wrong_field")] + 6 | | struct Company { + 7 | | company_name: String, + 8 | | num_employees: i32, + 9 | | country: String, 10 | | } | |_^